messenger

package module
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2022 License: MIT Imports: 16 Imported by: 0

README

Messenger

Build Status Coverage GitHub release Go Report Card GoLang version pkg.go.dev

This is a Go library for making bots to be used on Facebook messenger. It is built on the Messenger Platform. One of the main goals of the project is to implement it in an idiomatic and easy to use fashion.

You can find examples for this library here.

Tips

  • Follow the quickstart guide for getting everything set up!
  • You need a Facebook development app, and a Facebook page in order to build things.
  • Use ngrok to tunnel your locally running bot so that Facebook can reach the webhook.

Projects

This is a list of projects use messenger. If you would like to add your own, submit a Pull Request adding it below.

  • meme-maker by @paked: A bot which, given a photo and a caption, will create a macro meme.
  • drone-facebook by @appleboy: Drone.io plugin which sends Facebook notifications

Documentation

Index

Constants

View Source
const (
	// ProfileURL is the API endpoint used for retrieving profiles.
	// Used in the form: https://graph.facebook.com/v2.6/<USER_ID>?fields=<PROFILE_FIELDS>&access_token=<PAGE_ACCESS_TOKEN>
	ProfileURL = "https://graph.facebook.com/v2.6/"

	// ProfileFields is a list of JSON field names which will be populated by the profile query.
	ProfileFields = "first_name,last_name,profile_pic"

	// SendSettingsURL is API endpoint for saving settings.
	SendSettingsURL = "https://graph.facebook.com/v2.6/me/thread_settings"

	// MessengerProfileURL is the API endpoint where you set properties that define various aspects of the following Messenger Platform features.
	// Used in the form https://graph.facebook.com/v2.6/me/messenger_profile?access_token=<PAGE_ACCESS_TOKEN>
	// https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/
	MessengerProfileURL = "https://graph.facebook.com/v2.6/me/messenger_profile"
)
View Source
const (
	// DefaultSendAPIVersion is a default Send API version
	DefaultSendAPIVersion = "v2.11"
	// SendMessageURL is API endpoint for sending messages.
	SendMessageURL = "https://graph.facebook.com/%s/me/messages"
	// ThreadControlURL is the API endpoint for passing thread control.
	ThreadControlURL = "https://graph.facebook.com/%s/me/pass_thread_control"
	// InboxPageID is managed by facebook for secondary pass to inbox features: https://developers.facebook.com/docs/messenger-platform/handover-protocol/pass-thread-control
	InboxPageID = 263902037430900

	// ImageAttachment is image attachment type.
	ImageAttachment AttachmentType = "image"
	// AudioAttachment is audio attachment type.
	AudioAttachment AttachmentType = "audio"
	// VideoAttachment is video attachment type.
	VideoAttachment AttachmentType = "video"
	// FileAttachment is file attachment type.
	FileAttachment AttachmentType = "file"

	// ResponseType is response messaging type.
	ResponseType MessagingType = "RESPONSE"
	// UpdateType is update messaging type.
	UpdateType MessagingType = "UPDATE"
	// MessageTagType is message_tag messaging type.
	MessageTagType MessagingType = "MESSAGE_TAG"
	// NonPromotionalSubscriptionType is NON_PROMOTIONAL_SUBSCRIPTION messaging type.
	NonPromotionalSubscriptionType MessagingType = "NON_PROMOTIONAL_SUBSCRIPTION"

	// TopElementStyle is compact.
	CompactTopElementStyle TopElementStyle = "compact"
	// TopElementStyle is large.
	LargeTopElementStyle TopElementStyle = "large"

	// ImageAspectRatio is horizontal (1.91:1). Default.
	HorizontalImageAspectRatio ImageAspectRatio = "horizontal"
	// ImageAspectRatio is square.
	SquareImageAspectRatio ImageAspectRatio = "square"
)
View Source
const (
	// WebviewCompact opens the page in a web view that takes half the screen
	// and covers only part of the conversation.
	WebviewCompact = "compact"

	// WebviewTall opens the page in a web view that covers about 75% of the
	// conversation.
	WebviewTall = "tall"

	// WebviewFull opens the page in a web view that completely covers the
	// conversation, and has a "back" button instead of a "close" one.
	WebviewFull = "full"
)

Defines the different sizes available when setting up a CallToActionsItem of type "web_url". These values can be used in the "WebviewHeightRatio" field.

Variables

View Source
var ErrUnmarshal = errors.New("unmarshal error")

Functions

This section is empty.

Types

type AccountLinking

type AccountLinking struct {
	// Sender is who the message was sent from.
	Sender Sender `json:"-"`
	// Recipient is who the message was sent to.
	Recipient Recipient `json:"-"`
	// Time is when the message was sent.
	Time time.Time `json:"-"`
	// Status represents the new account linking status.
	Status string `json:"status"`
	// AuthorizationCode is a pass-through code set during the linking process.
	AuthorizationCode string `json:"authorization_code"`
}

type AccountLinkingHandler

type AccountLinkingHandler func(AccountLinking, *Response)

AccountLinkingHandler is a handler used to react to an account being linked or unlinked.

type Action

type Action int

Action is used to determine what kind of message a webhook event is.

const (
	// UnknownAction means that the event was not able to be classified.
	UnknownAction Action = iota - 1
	// TextAction means that the event was a text message (May contain attachments).
	TextAction
	// DeliveryAction means that the event was advising of a successful delivery to a
	// previous recipient.
	DeliveryAction
	// ReadAction means that the event was a previous recipient reading their respective
	// messages.
	ReadAction
	// PostBackAction represents post call back.
	PostBackAction
	// OptInAction represents opting in through the Send to Messenger button.
	OptInAction
	// ReferralAction represents ?ref parameter in m.me URLs.
	ReferralAction
	// AccountLinkingAction means that the event concerns changes in account linking
	// status.
	AccountLinkingAction
)

type Address

type Address struct {
	Street1    string `json:"street_1,omitempty"`
	Street2    string `json:"street_2,omitempty"`
	City       string `json:"city,omitempty"`
	PostalCode string `json:"postal_code,omitempty"`
	State      string `json:"state,omitempty"`
	Country    string `json:"country,omitempty"`
}

type Adjustment

type Adjustment struct {
	Name   string  `json:"name,omitempty"`
	Amount float32 `json:"amount,omitempty"`
}

type AdsContextData added in v1.2.6

type AdsContextData struct {
	// Title of the Ad
	AdTitle string `json:"ad_title"`
	// Url of the image from the Ad the user is interested
	PhotoURL string `json:"photo_url,omitempty"`
	// Thumbnail url of the video from the ad
	VideoURL string `json:"video_url,omitempty"`
	// ID of the post
	PostID string `json:"post_id"`
	// Product ID from the Ad the user is interested
	ProductID string `json:"product_id,omitempty"`
}

AdsContextData represents data containing information about the CTM ad, the user initiated the thread from.

type Attachment

type Attachment struct {
	Title string `json:"title,omitempty"`
	URL   string `json:"url,omitempty"`
	// Type is what type the message is. (image, video, audio or location)
	Type string `json:"type"`
	// Payload is the information for the file which was sent in the attachment.
	Payload Payload `json:"payload"`
}

Attachment is a file which used in a message.

type AttachmentType

type AttachmentType string

AttachmentType is attachment type.

type Button added in v1.2.3

type Button struct {
	Type                string `json:"type,omitempty"`
	Title               string `json:"title,omitempty"`
	Payload             string `json:"payload,omitempty"`
	URL                 string `json:"url,omitempty"`
	WebviewHeightRatio  string `json:"webview_height_ratio,omitempty"`
	MessengerExtensions bool   `json:"messenger_extensions,omitempty"`
	FallbackURL         string `json:"fallback_url,omitempty"`
	WebviewShareButton  string `json:"webview_share_button,omitempty"`
}

type CallToActionsItem

type CallToActionsItem struct {
	Type               string `json:"type,omitempty"`
	Title              string `json:"title,omitempty"`
	Payload            string `json:"payload,omitempty"`
	URL                string `json:"url,omitempty"`
	WebviewHeightRatio string `json:"webview_height_ratio,omitempty"`
	MessengerExtension bool   `json:"messenger_extensions,omitempty"`
}

CallToActionsItem contains Get Started button or item of Persist Menu.

type CallToActionsSetting

type CallToActionsSetting struct {
	SettingType   string              `json:"setting_type"`
	ThreadState   string              `json:"thread_state"`
	CallToActions []CallToActionsItem `json:"call_to_actions"`
}

CallToActionsSetting is the settings for Get Started and Persist Menu.

type Coordinates

type Coordinates struct {
	// Lat is latitude
	Lat float64 `json:"lat"`
	// Long is longitude
	Long float64 `json:"long"`
}

Coordinates is a pair of latitude and longitude.

type DefaultAction

type DefaultAction struct {
	Type                string `json:"type"`
	URL                 string `json:"url,omitempty"`
	WebviewHeightRatio  string `json:"webview_height_ratio,omitempty"`
	MessengerExtensions bool   `json:"messenger_extensions,omitempty"`
	FallbackURL         string `json:"fallback_url,omitempty"`
	WebviewShareButton  string `json:"webview_share_button,omitempty"`
}

DefaultAction is a response containing default action properties.

type Delivery

type Delivery struct {
	// Mids are the IDs of the messages which were read.
	Mids []string `json:"mids"`
	// RawWatermark is the timestamp of when the delivery was.
	RawWatermark int64 `json:"watermark"`
	// Seq is the sequence the message was sent in.
	Seq int `json:"seq"`
}

Delivery represents a the event fired when Facebook delivers a message to the recipient.

func (Delivery) Watermark

func (d Delivery) Watermark() time.Time

Watermark is the RawWatermark timestamp rendered as a time.Time.

type DeliveryHandler

type DeliveryHandler func(Delivery, *Response)

DeliveryHandler is a handler used for responding to a delivery receipt.

type Entry

type Entry struct {
	// ID is the ID of the batch.
	ID int64 `json:"id,string"`
	// Time is when the batch was sent.
	Time int64 `json:"time"`
	// Messaging is the events that were sent in this Entry
	Messaging []MessageInfo `json:"messaging"`
}

Entry is a batch of events which were sent in this webhook trigger.

type GreetingInfo

type GreetingInfo struct {
	Text string `json:"text"`
}

GreetingInfo contains greeting message.

type GreetingSetting

type GreetingSetting struct {
	SettingType string       `json:"setting_type"`
	Greeting    GreetingInfo `json:"greeting"`
}

GreetingSetting is the setting for greeting message.

type HomeURL

type HomeURL struct {
	URL                string `json:"url,omitempty"`
	WebviewHeightRatio string `json:"webview_height_ratio,omitempty"`
	WebviewShareButton string `json:"webview_share_button,omitempty"`
	InTest             bool   `json:"in_test,omitempty"`
}

HomeURL is the settings for EnableChatExtension https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/home-url

type IGMessageProduct added in v1.2.0

type IGMessageProduct struct {
	// ID of the product.
	ID string `json:"id,omitempty"`
}

IGMessageProduct represents Instagram product.

type IGMessageReaction added in v1.2.0

type IGMessageReaction struct {
	// Mid is a message ID.
	Mid string `json:"mid"`
	// Action can be {react|unreact}
	Action string `json:"action"`
	// Reaction is a reaction name. Optional.
	Reaction string `json:"reaction,omitempty"`
	// Emoji is optional.
	Emoji string `json:"emoji,omitempty"`
}

IGMessageReaction represents reaction to the Instagram message.

type IGMessageRead added in v1.2.0

type IGMessageRead struct {
	// Mid is a message ID.
	Mid string `json:"mid"`
}

IGMessageRead represents data with the read message ID. Present in the Instagram webhook.

type IGMessageReferral added in v1.2.0

type IGMessageReferral struct {
	// Product data.
	Product IGMessageProduct `json:"product,omitempty"`
}

IGMessageReferral represents Instagram message referral with product ID.

type IGPostback added in v1.2.0

type IGPostback struct {
	// Selected icebreaker question or title for the CTA (Generic Template)
	Title string `json:"title,omitempty"`
	// Payload is user defined payload.
	Payload string `json:"payload"`
}

IGPostback represents Instagram postback webhook data.

type IGReplyTo added in v1.2.0

type IGReplyTo struct {
	// Mid is a message ID to which reply was sent.
	Mid string `json:"mid"`
	// Story data.
	Story *IGReplyToStory `json:"story,omitempty"`
}

IGReplyTo represents data of the thing to what reply has been sent.

type IGReplyToStory added in v1.2.0

type IGReplyToStory struct {
	// URL of the story.
	URL string `json:"url,omitempty"`
	// ID of the story.
	ID string `json:"id,omitempty"`
}

IGReplyToStory is a story data to which reply has been sent.

type ImageAspectRatio

type ImageAspectRatio string

type Message

type Message struct {
	// Sender is who the message was sent from.
	Sender Sender `json:"-"`
	// Recipient is who the message was sent to.
	Recipient Recipient `json:"-"`
	// Time is when the message was sent.
	Time time.Time `json:"-"`
	// Message is mine
	IsEcho bool `json:"is_echo,omitempty"`
	// Mid is the ID of the message.
	Metadata string `json:"metadata"`
	// Mid is the ID of the message.
	Mid string `json:"mid"`
	// Seq is order the message was sent in relation to other messages.
	Seq int `json:"seq"`
	// StickerID is the ID of the sticker user sent.
	StickerID int `json:"sticker_id"`
	// Text is the textual contents of the message.
	Text string `json:"text"`
	// Attachments is the information about the attachments which were sent
	// with the message.
	Attachments []Attachment `json:"attachments"`
	// Selected quick reply
	QuickReply *QuickReply `json:"quick_reply,omitempty"`
	// Entities for NLP
	// https://developers.facebook.com/docs/messenger-platform/built-in-nlp/
	NLP json.RawMessage `json:"nlp"`
	// Read Instagram message data to which this reply was sent to.
	Read *IGMessageRead `json:"read,omitempty"`
	// Reaction represents reaction to Instagram message.
	Reaction *IGMessageReaction `json:"reaction,omitempty"`
	// Referral with Instagram product data.
	Referral *IGMessageReferral `json:"referral,omitempty"`
	// IsUnsupported is being sent if Instagram message is not supported.
	IsUnsupported bool `json:"is_unsupported,omitempty"`
	// IsDeleted is being sent if message was deleted.
	IsDeleted bool `json:"is_deleted,omitempty"`
	// ReplyTo the Instagram story or to the message.
	ReplyTo *IGReplyTo `json:"reply_to"`
}

Message represents a Facebook messenger message.

func (*Message) GetNLP

func (m *Message) GetNLP(i interface{}) error

GetNLP simply unmarshals the NLP entities to the given struct and returns an error if it's not possible.

type MessageData

type MessageData struct {
	Text         string                       `json:"text,omitempty"`
	Attachment   *StructuredMessageAttachment `json:"attachment,omitempty"`
	QuickReplies []QuickReply                 `json:"quick_replies,omitempty"`
	Metadata     string                       `json:"metadata,omitempty"`
}

MessageData is a message consisting of text or an attachment, with an additional selection of optional quick replies.

type MessageHandler

type MessageHandler func(Message, *Response)

MessageHandler is a handler used for responding to a message containing text.

type MessageInfo

type MessageInfo struct {
	// Sender is who the event was sent from.
	Sender Sender `json:"sender"`
	// Recipient is who the event was sent to.
	Recipient Recipient `json:"recipient"`
	// Timestamp is the true time the event was triggered.
	Timestamp int64 `json:"timestamp"`
	// Message is the contents of a message if it is a MessageAction.
	// Nil if it is not a MessageAction.
	Message *Message `json:"message"`
	// Delivery is the contents of a message if it is a DeliveryAction.
	// Nil if it is not a DeliveryAction.
	Delivery *Delivery `json:"delivery"`

	PostBack *PostBack `json:"postback"`

	Read *Read `json:"read"`

	OptIn *OptIn `json:"optin"`

	ReferralMessage *ReferralMessage `json:"referral"`

	AccountLinking *AccountLinking `json:"account_linking"`
}

MessageInfo is an event that is fired by the webhook.

type MessagingType

type MessagingType string

type Messenger

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

Messenger is the client which manages communication with the Messenger Platform API.

func New

func New(mo Options) *Messenger

New creates a new Messenger. You pass in Options in order to affect settings.

func (*Messenger) Attachment

func (m *Messenger) Attachment(to Recipient, dataType AttachmentType, url string, messagingType MessagingType, metadata string, tags ...string) (QueryResponse, error)

Attachment sends an image, sound, video or a regular file to a given recipient.

func (*Messenger) CallToActionsSetting

func (m *Messenger) CallToActionsSetting(state string, actions []CallToActionsItem) (QueryResponse, error)

CallToActionsSetting sends settings for Get Started or Persistent Menu.

func (*Messenger) EnableChatExtension

func (m *Messenger) EnableChatExtension(homeURL HomeURL) error

EnableChatExtension set the homepage url required for a chat extension.

func (*Messenger) GreetingSetting

func (m *Messenger) GreetingSetting(text string) (QueryResponse, error)

GreetingSetting sends settings for greeting.

func (*Messenger) HandleAccountLinking

func (m *Messenger) HandleAccountLinking(f AccountLinkingHandler)

HandleAccountLinking adds a new AccountLinkingHandler to the Messenger.

func (*Messenger) HandleDelivery

func (m *Messenger) HandleDelivery(f DeliveryHandler)

HandleDelivery adds a new DeliveryHandler to the Messenger which will be triggered when a previously sent message is delivered to the recipient.

func (*Messenger) HandleMessage

func (m *Messenger) HandleMessage(f MessageHandler)

HandleMessage adds a new MessageHandler to the Messenger which will be triggered when a message is received by the client.

func (*Messenger) HandleOptIn

func (m *Messenger) HandleOptIn(f OptInHandler)

HandleOptIn adds a new OptInHandler to the Messenger which will be triggered once a user opts in to communicate with the bot.

func (*Messenger) HandlePostBack

func (m *Messenger) HandlePostBack(f PostBackHandler)

HandlePostBack adds a new PostBackHandler to the Messenger.

func (*Messenger) HandleRead

func (m *Messenger) HandleRead(f ReadHandler)

HandleRead adds a new DeliveryHandler to the Messenger which will be triggered when a previously sent message is read by the recipient.

func (*Messenger) HandleReferral

func (m *Messenger) HandleReferral(f ReferralHandler)

HandleReferral adds a new ReferralHandler to the Messenger.

func (*Messenger) Handler

func (m *Messenger) Handler() http.Handler

Handler returns the Messenger in HTTP client form.

func (*Messenger) ProfileByID

func (m *Messenger) ProfileByID(id int64, profileFields []string) (Profile, error)

ProfileByID retrieves the Facebook user profile associated with that ID. According to the messenger docs: https://developers.facebook.com/docs/messenger-platform/identity/user-profile, Developers must ask for access except for some fields that are accessible without permissions.

At the time of writing (2019-01-04), these fields are - Name - First Name - Last Name - Profile Picture.

func (*Messenger) Response

func (m *Messenger) Response(to int64) *Response

Response returns new Response object.

func (*Messenger) Send

func (m *Messenger) Send(to Recipient, message string, messagingType MessagingType, metadata string, tags ...string) (QueryResponse, error)

Send will send a textual message to a user. This user must have previously initiated a conversation with the bot.

func (*Messenger) SendGeneralMessage

func (m *Messenger) SendGeneralMessage(to Recipient, elements *[]StructuredMessageElement, messagingType MessagingType, metadata string, tags ...string) (QueryResponse, error)

SendGeneralMessage will send the GenericTemplate message.

func (*Messenger) SendWithReplies

func (m *Messenger) SendWithReplies(to Recipient, message string, replies []QuickReply, messagingType MessagingType, metadata string, tags ...string) (QueryResponse, error)

SendWithReplies sends a textual message to a user, but gives them the option of numerous quick response options.

func (*Messenger) SenderAction added in v1.3.0

func (m *Messenger) SenderAction(to Recipient, action SenderAction) (QueryResponse, error)

type OptIn

type OptIn struct {
	// Sender is the sender of the message
	Sender Sender `json:"-"`
	// Recipient is who the message was sent to.
	Recipient Recipient `json:"-"`
	// Time is when the message was sent.
	Time time.Time `json:"-"`
	// Ref is the reference as given
	Ref string `json:"ref"`
}

type OptInHandler

type OptInHandler func(OptIn, *Response)

OptInHandler is a handler used to handle opt-ins.

type Options

type Options struct {
	// Verify sets whether or not to be in the "verify" mode. Used for
	// verifying webhooks on the Facebook Developer Portal.
	Verify bool
	// AppSecret is the app secret from the Facebook Developer Portal. Used when
	// in the "verify" mode.
	AppSecret string
	// VerifyToken is the token to be used when verifying the webhook. Is set
	// when the webhook is created.
	VerifyToken string
	// Token is the access token of the Facebook page to send messages from.
	Token string
	// WebhookURL is where the Messenger client should listen for webhook events. Leaving the string blank implies a path of "/".
	WebhookURL string
	// Mux is shared mux between several Messenger objects
	Mux *http.ServeMux
	// SendAPIVersion is a Send API version
	SendAPIVersion string
}

Options are the settings used when creating a Messenger client.

type Payload

type Payload struct {
	URL   string `json:"url,omitempty"`
	Title string `json:"title,omitempty"`
	// Coordinates is Lat/Long pair of location pin
	Coordinates  *Coordinates `json:"coordinates,omitempty"`
	TemplateType string       `json:"template_type,omitempty"`
	Buttons      []Button     `json:"buttons,omitempty"`
}

Payload is the information on where an attachment is.

type PostBack

type PostBack struct {
	// Sender is who the message was sent from.
	Sender Sender `json:"-"`
	// Recipient is who the message was sent to.
	Recipient Recipient `json:"-"`
	// Time is when the message was sent.
	Time time.Time `json:"-"`
	// PostBack ID
	Payload string `json:"payload"`
	// Optional referral info
	Referral Referral `json:"referral"`
	// Title for the CTA that was clicked on
	Title string `json:"title"`
	// Message ID
	Mid string `json:"mid"`
}

PostBack represents postback callback.

type PostBackHandler

type PostBackHandler func(PostBack, *Response)

PostBackHandler is a handler used postback callbacks.

type Profile

type Profile struct {
	Name          string  `json:"name"`
	FirstName     string  `json:"first_name"`
	LastName      string  `json:"last_name"`
	ProfilePicURL string  `json:"profile_pic"`
	Locale        string  `json:"locale"`
	Timezone      float64 `json:"timezone"`
	Gender        string  `json:"gender"`
}

Profile is the public information of a Facebook user.

type QueryError

type QueryError struct {
	Message      string `json:"message"`
	Type         string `json:"type"`
	Code         int    `json:"code"`
	ErrorSubcode int    `json:"error_subcode"`
	FBTraceID    string `json:"fbtrace_id"`
}

QueryError is representing an error sent back by Facebook.

func (QueryError) Error

func (e QueryError) Error() string

QueryError implements error.

type QueryResponse

type QueryResponse struct {
	Error       *QueryError `json:"error,omitempty"`
	RecipientID string      `json:"recipient_id"`
	MessageID   string      `json:"message_id"`
}

QueryResponse is the response sent back by Facebook when setting up things like greetings or call-to-actions.

type QuickReply

type QuickReply struct {
	// ContentType is the type of reply
	ContentType string `json:"content_type,omitempty"`
	// Title is the reply title
	Title string `json:"title,omitempty"`
	// Payload is the  reply information
	Payload string `json:"payload"`
}

QuickReply is a file which used in a message.

type Read

type Read struct {
	// RawWatermark is the timestamp before which all messages have been read
	// by the user
	RawWatermark int64 `json:"watermark"`
	// Seq is the sequence the message was sent in.
	Seq int `json:"seq"`
	// Mid is the ID of the message.
	Mid string `json:"mid"`
}

Read represents a the event fired when a message is read by the recipient.

func (Read) Watermark

func (r Read) Watermark() time.Time

Watermark is the RawWatermark timestamp rendered as a time.Time.

type ReadHandler

type ReadHandler func(Read, *Response)

ReadHandler is a handler used for responding to a read receipt.

type ReceiptMessageElement

type ReceiptMessageElement struct {
	Quantity float32 `json:"quantity,omitempty"`
	Price    float32 `json:"price,omitempty"`
	Currency string  `json:"currency,omitempty"`
}

type ReceiptMessagePayload

type ReceiptMessagePayload struct {
	RecipientName string       `json:"recipient_name,omitempty"`
	OrderNumber   string       `json:"order_number,omitempty"`
	Currency      string       `json:"currency,omitempty"`
	PaymentMethod string       `json:"payment_method,omitempty"`
	Timestamp     int64        `json:"timestamp,omitempty"`
	Address       *Address     `json:"address,omitempty"`
	Summary       *Summary     `json:"summary,omitempty"`
	Adjustments   []Adjustment `json:"adjustments,omitempty"`
}

type Receive

type Receive struct {
	// Object should always be `page`. (I don't quite understand why)
	Object string `json:"object"`
	// Entry is all of the different messenger types which were
	// sent in this event.
	Entry []Entry `json:"entry"`
}

Receive is the format in which webhook events are sent.

type Recipient

type Recipient struct {
	ID        int64  `json:"id,string,omitempty"`
	PostID    string `json:"post_id,omitempty"`
	CommentID string `json:"comment_id,omitempty"`
}

Recipient is who the message was sent to.

type Referral

type Referral struct {
	// Data originally passed in the ref param
	Ref string `json:"ref"`
	// Source type
	Source string `json:"source"`
	// The identifier dor the referral
	Type string `json:"type"`
	// ID of the ad
	AdID string `json:"ad_id,omitempty"`
	// The data containing information about the CTM ad, the user initiated the thread from.
	AdsContextData AdsContextData `json:"ads_context_data,omitempty"`
	// URI of the site from which the message was sent to the Facebook chat plugin.
	RefererURI string `json:"referer_uri,omitempty"`
}

Referral represents referral info.

type ReferralHandler

type ReferralHandler func(ReferralMessage, *Response)

ReferralHandler is a handler used postback callbacks.

type ReferralMessage

type ReferralMessage struct {
	*Referral

	// Sender is the sender of the message
	Sender Sender `json:"-"`
	// Recipient is who the message was sent to.
	Recipient Recipient `json:"-"`
	// Time is when the message was sent.
	Time time.Time `json:"-"`
}

ReferralMessage represents referral endpoint.

type Response

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

Response is used for responding to events with messages.

func (*Response) Attachment

func (r *Response) Attachment(dataType AttachmentType, url string, messagingType MessagingType, metadata string, tags ...string) (QueryResponse, error)

Attachment sends an image, sound, video or a regular file to a chat.

func (*Response) AttachmentData

func (r *Response) AttachmentData(
	dataType AttachmentType, filename string, contentType string, filedata io.Reader) (QueryResponse, error)

AttachmentData sends an image, sound, video or a regular file to a chat via an io.Reader.

func (*Response) AttachmentWithReplies

func (r *Response) AttachmentWithReplies(attachment *StructuredMessageAttachment, replies []QuickReply, messagingType MessagingType, metadata string, tags ...string) (QueryResponse, error)

AttachmentWithReplies sends a attachment message with some replies.

func (*Response) ButtonTemplate

func (r *Response) ButtonTemplate(text string, buttons *[]StructuredMessageButton, messagingType MessagingType, metadata string, tags ...string) (QueryResponse, error)

ButtonTemplate sends a message with the main contents being button elements.

func (*Response) DispatchMessage

func (r *Response) DispatchMessage(m interface{}) (QueryResponse, error)

DispatchMessage posts the message to messenger, return the error if there's any.

func (*Response) GenericTemplate

func (r *Response) GenericTemplate(elements *[]StructuredMessageElement, messagingType MessagingType, metadata string, tags ...string) (QueryResponse, error)

GenericTemplate is a message which allows for structural elements to be sent.

func (*Response) Image

func (r *Response) Image(im image.Image) (QueryResponse, error)

Image sends an image.

func (*Response) ListTemplate

func (r *Response) ListTemplate(elements *[]StructuredMessageElement, messagingType MessagingType, tags ...string) (QueryResponse, error)

ListTemplate sends a list of elements.

func (*Response) PassThreadToInbox

func (r *Response) PassThreadToInbox() error

PassThreadToInbox Uses Messenger Handover Protocol for live inbox https://developers.facebook.com/docs/messenger-platform/handover-protocol/#inbox

func (*Response) SenderAction

func (r *Response) SenderAction(action SenderAction) (QueryResponse, error)

SenderAction sends an info about sender action.

func (*Response) SetToken

func (r *Response) SetToken(token string)

SetToken is for using DispatchMessage from outside.

func (*Response) Text

func (r *Response) Text(message string, messagingType MessagingType, metadata string, tags ...string) (QueryResponse, error)

Text sends a textual message.

func (*Response) TextWithReplies

func (r *Response) TextWithReplies(message string, replies []QuickReply, messagingType MessagingType, metadata string, tags ...string) (QueryResponse, error)

TextWithReplies sends a textual message with some replies messagingType should be one of the following: "RESPONSE","UPDATE","MESSAGE_TAG","NON_PROMOTIONAL_SUBSCRIPTION" only supply tags when messagingType == "MESSAGE_TAG" (see https://developers.facebook.com/docs/messenger-platform/send-messages#messaging_types for more).

type SendMessage

type SendMessage struct {
	MessagingType MessagingType `json:"messaging_type"`
	Recipient     Recipient     `json:"recipient"`
	Message       MessageData   `json:"message"`
	Tag           string        `json:"tag,omitempty"`
}

SendMessage is the information sent in an API request to Facebook.

type SendSenderAction

type SendSenderAction struct {
	Recipient    Recipient    `json:"recipient"`
	SenderAction SenderAction `json:"sender_action"`
}

SendSenderAction is the information about sender action.

type SendStructuredMessage

type SendStructuredMessage struct {
	MessagingType MessagingType         `json:"messaging_type"`
	Recipient     Recipient             `json:"recipient"`
	Message       StructuredMessageData `json:"message"`
	Tag           string                `json:"tag,omitempty"`
}

SendStructuredMessage is a structured message template.

type Sender

type Sender struct {
	ID int64 `json:"id,string"`
}

Sender is who the message was sent from.

type SenderAction added in v1.3.0

type SenderAction string

SenderAction is used to send a specific action (event) to the Facebook. The result of sending said action is supposed to give more interactivity to the bot.

const (
	// MarkSeen marks message as seen.
	MarkSeen SenderAction = "MARK_SEEN"
	// TypingOn turns on "Bot is typing..." indicator.
	TypingOn SenderAction = "TYPING_ON"
	// TypingOff turns off typing indicator.
	TypingOff SenderAction = "TYPING_OFF"
	// React to the message.
	React SenderAction = "REACT"
	// Unreact to the message (remove reaction).
	Unreact SenderAction = "UNREACT"
)

type StructuredMessageAttachment

type StructuredMessageAttachment struct {
	// Type must be template
	Title string         `json:"title,omitempty"`
	URL   string         `json:"url,omitempty"`
	Type  AttachmentType `json:"type"`
	// Payload is the information for the file which was sent in the attachment.
	Payload StructuredMessagePayload `json:"payload"`
}

StructuredMessageAttachment is the attachment of a structured message.

type StructuredMessageButton

type StructuredMessageButton struct {
	Type                string                 `json:"type"`
	URL                 string                 `json:"url,omitempty"`
	Title               string                 `json:"title,omitempty"`
	Payload             string                 `json:"payload,omitempty"`
	WebviewHeightRatio  string                 `json:"webview_height_ratio,omitempty"`
	MessengerExtensions bool                   `json:"messenger_extensions,omitempty"`
	FallbackURL         string                 `json:"fallback_url,omitempty"`
	WebviewShareButton  string                 `json:"webview_share_button,omitempty"`
	ShareContents       *StructuredMessageData `json:"share_contents,omitempty"`
}

StructuredMessageButton is a response containing buttons.

type StructuredMessageData

type StructuredMessageData struct {
	Attachment StructuredMessageAttachment `json:"attachment"`
	Metadata   string                      `json:"metadata,omitempty"`
}

StructuredMessageData is an attachment sent with a structured message.

type StructuredMessageElement

type StructuredMessageElement struct {
	Title         string                     `json:"title"`
	ImageURL      string                     `json:"image_url"`
	ItemURL       string                     `json:"item_url,omitempty"`
	Subtitle      string                     `json:"subtitle"`
	DefaultAction *DefaultAction             `json:"default_action,omitempty"`
	Buttons       *[]StructuredMessageButton `json:"buttons,omitempty"`
	ReceiptMessageElement
}

StructuredMessageElement is a response containing structural elements.

type StructuredMessagePayload

type StructuredMessagePayload struct {
	// TemplateType must be button, generic or receipt
	TemplateType     string                      `json:"template_type,omitempty"`
	TopElementStyle  TopElementStyle             `json:"top_element_style,omitempty"`
	Text             string                      `json:"text,omitempty"`
	ImageAspectRatio ImageAspectRatio            `json:"image_aspect_ratio,omitempty"`
	Sharable         bool                        `json:"sharable,omitempty"`
	Elements         *[]StructuredMessageElement `json:"elements,omitempty"`
	Buttons          *[]StructuredMessageButton  `json:"buttons,omitempty"`
	Url              string                      `json:"url,omitempty"`
	AttachmentID     string                      `json:"attachment_id,omitempty"`
	ReceiptMessagePayload
}

StructuredMessagePayload is the actual payload of an attachment.

type Summary

type Summary struct {
	Subtotal     float32 `json:"subtotal,omitempty"`
	ShippingCost float32 `json:"shipping_cost,omitempty"`
	TotalTax     float32 `json:"total_tax,omitempty"`
	TotalCost    float32 `json:"total_cost,omitempty"`
}

type TopElementStyle

type TopElementStyle string

type UnmarshalError added in v1.2.7

type UnmarshalError struct {
	Content   []byte
	ErrorText string
	Err       error
}

func NewUnmarshalError added in v1.2.7

func NewUnmarshalError(err error) *UnmarshalError

func (*UnmarshalError) Error added in v1.2.7

func (u *UnmarshalError) Error() string

func (*UnmarshalError) Unwrap added in v1.2.7

func (u *UnmarshalError) Unwrap() error

func (*UnmarshalError) WithContent added in v1.2.7

func (u *UnmarshalError) WithContent(content []byte) *UnmarshalError

func (*UnmarshalError) WithErr added in v1.2.7

func (u *UnmarshalError) WithErr(err error) *UnmarshalError

func (*UnmarshalError) WithReader added in v1.2.7

func (u *UnmarshalError) WithReader(reader io.Reader) *UnmarshalError

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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