Documentation ¶
Overview ¶
Package fbmessenger is a library for making requests to and handling callbacks from the Facebook Messenger Platform API.
Key Features
- Fluent API makes building messages to send easy.
- Timeoutable, cancellable requests using `context.Context`.
- Designed for use with one or many subscribed pages.
Quick Start ¶
The primary types in the package are CallbackDispatcher and Client. CallbackDispatcher is used to handle the callbacks Facebook sends to your webhook endpoint. Client is used to send messages and to get user profiles.
CallbackDispatcher Usage
// Unmarshal the json received at your webhook endpoint into an instance of type Callback. cb := &fbmessenger.Callback{} err := json.Unmarshal(requestBytes, cb) // Use type CallbackDispatcher to route each MessagingEntry included in the callback to an // appropriate handler for the type of entry. Note that due to webhook batching, a // handler may be called more than once per callback. dispatcher := &fbmessenger.CallbackDispatcher{ MessageHandler: MessageReceived } err := dispatcher.Dispatch(cb) // Callback handlers should have a signature mathing the MessageEntryHandler type. func MessageReceived(cb *fbmessenger.MessagingEntry) error { //Do stuff }
Client Usage
// Create a `Client` to make requests to the messenger API. client := fbmessenger.Client{} // There are structs for the different types of messages you can send. The easiest way to // create them is with the fluent API. request := fbmessenger.TextMessage("Hello, world!").To("USER_ID") // Then send your request and handle errors in sending, and errors returned from Facebook. response, err := client.Send(request, "YOUR_PAGE_ACCESS_TOKEN") if err != nil { //Got an error. Request never got to Facebook. } else if response.Error != nil { //Request got to Facebook. Facebook returned an error. } else { //Hooray! } // Get a user's profile using their userId. userProfile, err := client.GetUserProfile("USER_ID", "YOUR_PAGE_ACCESS_TOKEN")
Index ¶
- type Action
- type Address
- type Attachment
- type Button
- type ButtonPayload
- type Callback
- type CallbackAttachment
- type CallbackAttachmentPayload
- type CallbackDispatcher
- type CallbackMessage
- type CallbackQuickReply
- type Client
- func (c *Client) GetUserProfile(userId, pageAccessToken string) (*UserProfile, error)
- func (c *Client) GetUserProfileWithContext(ctx context.Context, userId, pageAccessToken string) (*UserProfile, error)
- func (c *Client) Send(sendRequest *SendRequest, pageAccessToken string) (*SendResponse, error)
- func (c *Client) SendWithContext(ctx context.Context, sendRequest *SendRequest, pageAccessToken string) (*SendResponse, error)
- type Coordinates
- type DataPayload
- type Delivery
- type Entry
- type GenericElement
- type GenericPayload
- type Message
- type MessageEntryHandler
- type MessagingEntry
- type OptIn
- type Postback
- type Principal
- type QuickReply
- type ReceiptAdjustment
- type ReceiptElement
- type ReceiptHeader
- type ReceiptPayload
- type ReceiptSummary
- type Recipient
- type ResourcePayload
- type SavedAssetPayload
- type SendError
- type SendRequest
- func ButtonTemplateMessage(text string, buttons ...*Button) *SendRequest
- func GenericTemplateMessage(elements ...*GenericElement) *SendRequest
- func ImageDataMessage(data []byte, contentType string) *SendRequest
- func ImageMessage(url string) *SendRequest
- func ReceiptTemplateMessage(header *ReceiptHeader, summary *ReceiptSummary, elements ...*ReceiptElement) *SendRequest
- func SavedImageMessage(id string) *SendRequest
- func SavedVideoMessage(id string) *SendRequest
- func TextMessage(text string) *SendRequest
- func VideoMessage(url string) *SendRequest
- func WebviewButtonTemplateMessage(text string, buttons ...*WebviewButton) *SendRequest
- func (sr *SendRequest) NoPush() *SendRequest
- func (sr *SendRequest) Regular() *SendRequest
- func (sr *SendRequest) SilentPush() *SendRequest
- func (sr *SendRequest) To(userID string) *SendRequest
- func (sr *SendRequest) ToPhoneNumber(phoneNumber string) *SendRequest
- func (sr *SendRequest) WithQuickReplies(replies ...*QuickReply) *SendRequest
- func (sr *SendRequest) WithReceiptAddress(address *Address) *SendRequest
- func (sr *SendRequest) WithReceiptAdjustments(adjustments ...*ReceiptAdjustment) *SendRequest
- type SendResponse
- type UserProfile
- type WebviewButton
- type WebviewButtonPayload
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Action ¶ added in v1.1.6
type Action struct { Type string `json:"type" binding:"required"` URL string `json:"url,omitempty"` Payload string `json:"payload,omitempty"` }
Action represents a default action for element in a structured message using the generic template.
type Address ¶
type Address struct { Street1 string `json:"street_1" binding:"required"` Street2 string `json:"street_2,omitempty"` City string `json:"city" binding:"required"` PostalCode string `json:"postal_code" binding:"required"` State string `json:"state" binding:"required"` Country string `json:"country" binding:"required"` }
Address represents a physical mailing address
type Attachment ¶
type Attachment struct { Type string `json:"type" binding:"required"` Payload interface{} `json:"payload" binding:"required"` }
Attachment is used to build a message with attached media, or a structured message.
type Button ¶
type Button struct { Type string `json:"type" binding:"required"` Title string `json:"title" binding:"required"` URL string `json:"url,omitempty"` Payload string `json:"payload,omitempty"` }
Button represents a single button in a structured message using the button template.
func PostbackButton ¶
PostbackButton is a fluent helper method for creating a button with type "payload" for use in a message with a button template or generic template attachment.
type ButtonPayload ¶
type ButtonPayload struct { TemplateType string `json:"template_type" binding:"required"` Text string `json:"text" binding:"required"` Buttons []*Button `json:"buttons" binding:"required"` }
ButtonPayload is used to build a structured message using the button template.
See https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template
type Callback ¶
type Callback struct { Object string `json:"object" binding:"required"` Entries []*Entry `json:"entry" binding:"required"` }
Callback is the top level structure that represents a callback received by your webhook endpoint.
See https://developers.facebook.com/docs/messenger-platform/webhook-reference#format
type CallbackAttachment ¶
type CallbackAttachment struct { Title string `json:"title"` URL string `json:"url"` Type string `json:"type" binding:"required"` Payload CallbackAttachmentPayload `json:"payload" binding:"required"` }
CallbackAttachment holds the type and payload of an attachment sent by a user.
type CallbackAttachmentPayload ¶
type CallbackAttachmentPayload struct { URL string `json:"url"` Coordinates *Coordinates `json:"coordinates"` }
CallbackAttachmentPayload holds the URL of a multimedia attachment, or the coordinates of a location attachment sent by the user.
type CallbackDispatcher ¶
type CallbackDispatcher struct { MessageHandler MessageEntryHandler DeliveryHandler MessageEntryHandler PostbackHandler MessageEntryHandler AuthenticationHandler MessageEntryHandler }
CallbackDispatcher routes each MessagingEntry included in a callback to an appropriate handler for the type of entry. Note that due to webhook batching, a handler may be called more than once per callback.
func (*CallbackDispatcher) Dispatch ¶
func (dispatcher *CallbackDispatcher) Dispatch(cb *Callback) error
Dispatch routes each MessagingEntry included in the callback to an appropriate handler for the type of entry.
type CallbackMessage ¶
type CallbackMessage struct { MessageID string `json:"mid" binding:"required"` Sequence int `json:"seq" binding:"required"` Text string `json:"text"` Attachments []*CallbackAttachment `json:"attachments"` QuickReply *CallbackQuickReply `json:"quick_reply"` }
CallbackMessage represents a message a user has sent to your page. Either the Text or Attachments field will be set, but not both.
See https://developers.facebook.com/docs/messenger-platform/webhook-reference/message-received
type CallbackQuickReply ¶ added in v1.1.0
type CallbackQuickReply struct {
Payload string `json:"payload" binding:"required"`
}
CallbackQuickReply holds the developer defined payload of a quick reply sent by the user.
type Client ¶
type Client struct { URL string // contains filtered or unexported fields }
Client is used to send messages and get user profiles. Use the empty value in most cases. The URL field can be overridden to allow for writing integration tests that use a different endpoint (not Facebook).
func (*Client) GetUserProfile ¶
func (c *Client) GetUserProfile(userId, pageAccessToken string) (*UserProfile, error)
GetUserProfile GETs a profile with more information about the user.
func (*Client) GetUserProfileWithContext ¶
func (c *Client) GetUserProfileWithContext(ctx context.Context, userId, pageAccessToken string) (*UserProfile, error)
GetUserProfileWithContext is like GetUserProfile but allows you to timeout or cancel the request using context.Context.
func (*Client) Send ¶
func (c *Client) Send(sendRequest *SendRequest, pageAccessToken string) (*SendResponse, error)
Send POSTs a request to and returns a response from the Send API. A response from Facebook indicating an error does not return an error. Be sure to check for errors in sending, and errors in the response from Facebook.
response, err := client.Send(request, "YOUR_PAGE_ACCESS_TOKEN") if err != nil { //Got an error. Request never got to Facebook. } else if response.Error != nil { //Request got to Facebook. Facebook returned an error. } else { //Hooray! }
func (*Client) SendWithContext ¶
func (c *Client) SendWithContext(ctx context.Context, sendRequest *SendRequest, pageAccessToken string) (*SendResponse, error)
SendWithContext is like Send but allows you to timeout or cancel the request using context.Context.
type Coordinates ¶ added in v1.1.0
type Coordinates struct { Lat float64 `json:"lat" binding:"required"` Long float64 `json:"long" binding:"required"` }
Coordinates holds the latitude and longitude of a location.
type DataPayload ¶
type DataPayload struct { Data []byte `json:"-"` ContentType string `json:"-"` FileName string `json:"-"` }
DataPayload is used to hold the bytes of a resource (image, file, etc.) to upload and attach to a message. All fields are required. FileName will only be visible to the recipient when type of the attachment is "file".
See https://developers.facebook.com/docs/messenger-platform/send-api-reference/image-attachment
type Delivery ¶
type Delivery struct { MessageIds []string `json:"mids"` Watermark int `json:"watermark" binding:"required"` Sequence int `json:"seq" bindging:"required"` }
Delivery holds information about which of the messages that you've sent have been delivered.
See https://developers.facebook.com/docs/messenger-platform/webhook-reference/message-delivered
type Entry ¶
type Entry struct { PageID string `json:"id" binding:"required"` Time int `json:"time" binding:"required"` Messaging []*MessagingEntry `json:"messaging"` }
Entry is part of the common format of callbacks.
type GenericElement ¶
type GenericElement struct { Title string `json:"title" binding:"required"` ImageURL string `json:"image_url" binding:"required"` Subtitle string `json:"subtitle" binding:"required"` DefaultAction *Action `json:"default_action,omitempty"` Buttons []*Button `json:"buttons" binding:"required"` }
GenericElement represents one item in the carousel of a generic template message.
type GenericPayload ¶
type GenericPayload struct { TemplateType string `json:"template_type" binding:"required"` Elements []*GenericElement `json:"elements" binding:"required"` }
GenericPayload is used to build a structured message using the generic template.
See https://developers.facebook.com/docs/messenger-platform/send-api-reference/generic-template
type Message ¶
type Message struct { Text string `json:"text,omitempty"` Attachment *Attachment `json:"attachment,omitempty"` QuickReplies []*QuickReply `json:"quick_replies,omitempty"` }
Message can represent either a text message, or a message with an attachment. Either Text or Attachment must be set, but not both.
type MessageEntryHandler ¶
type MessageEntryHandler func(cb *MessagingEntry) error
MessageEntryHandler functions are for handling individual interactions with a user.
type MessagingEntry ¶
type MessagingEntry struct { Sender Principal `json:"sender" binding:"required"` Recipient Principal `json:"recipient" binding:"required"` Timestamp int `json:"timestamp"` Message *CallbackMessage `json:"message"` Delivery *Delivery `json:"delivery"` Postback *Postback `json:"postback"` OptIn *OptIn `json:"optin"` }
MessagingEntry is an individual interaction a user has with a page. The Sender and Recipient fields are common to all types of callbacks and the other fields only apply to specific types of callbacks.
type OptIn ¶
type OptIn struct {
Ref string `json:"ref" binding:"required"`
}
OptIn holds the data defined for the Send-to-Messenger plugin.
See https://developers.facebook.com/docs/messenger-platform/webhook-reference/authentication
type Postback ¶
type Postback struct {
Payload string `json:"payload" binding:"required"`
}
Postback holds the data defined for buttons the user taps.
See https://developers.facebook.com/docs/messenger-platform/webhook-reference/postback-received
type Principal ¶
type Principal struct {
ID string `json:"id" binding:"required"`
}
Principal holds the Id of a sender or recipient.
type QuickReply ¶ added in v1.1.0
type QuickReply struct { ContentType string `json:"content_type" binding:"required"` Title string `json:"title,omitempty"` Payload string `json:"payload,omitempty"` ImageURL string `json:"image_url,omitempty"` }
QuickReply represents a quick reply to a message.
func LocationReply ¶ added in v1.1.0
func LocationReply() *QuickReply
LocationReply is a fluent helper method for creating a QuickReply with content type "location".
func TextReply ¶ added in v1.1.0
func TextReply(title, payload string) *QuickReply
TextReply is a fluent helper method for creating a QuickReply with content type "text".
func TextReplyWithImage ¶ added in v1.1.0
func TextReplyWithImage(title, payload, imageURL string) *QuickReply
TextReplyWithImage is a fluent helper method for creating a QuickReply with content type "text" and an attached image.
type ReceiptAdjustment ¶
type ReceiptAdjustment struct { Name string `json:"name,omitempty"` Amount json.Number `json:"amount"` }
ReceiptAdjustment represents discounts applied to a receipt.
type ReceiptElement ¶
type ReceiptElement struct { Title string `json:"title" binding:"required"` Subtitle string `json:"subtitle,omitempty"` Quantity int `json:"quantity,omitempty"` Price json.Number `json:"price" binding:"required"` Currency string `json:"currency,omitempty"` ImageURL string `json:"image_url,omitempty"` }
ReceiptElement represents a line item for one purchased item (not tax or shipping) on a receipt.
type ReceiptHeader ¶
type ReceiptHeader struct { RecipientName string OrderNumber string Currency string PaymentMethod string OrderURL string Timestamp string }
ReceiptHeader holds just the top level fields for a ReceiptPayload. For use with the ReceiptTemplateMessage fluent helper method.
type ReceiptPayload ¶
type ReceiptPayload struct { TemplateType string `json:"template_type" binding:"required"` RecipientName string `json:"recipient_name" binding:"required"` OrderNumber string `json:"order_number" binding:"required"` Currency string `json:"currency" binding:"required"` PaymentMethod string `json:"payment_method" binding:"required"` Timestamp string `json:"timestamp,omitempty"` OrderURL string `json:"order_url,omitempty"` Elements []*ReceiptElement `json:"elements" binding:"required"` Address *Address `json:"address,omitempty"` Summary *ReceiptSummary `json:"summary" binding:"required"` Adjustments []*ReceiptAdjustment `json:"adjustments,omitempty"` }
ReceiptPayload is used to build a structured message using the receipt template.
See https://developers.facebook.com/docs/messenger-platform/send-api-reference/receipt-template
type ReceiptSummary ¶
type ReceiptSummary struct { Subtotal json.Number `json:"subtotal,omitempty"` ShippingCost json.Number `json:"shipping_cost,omitempty"` TotalTax json.Number `json:"total_tax,omitempty"` TotalCost json.Number `json:"total_cost" binding:"required"` }
ReceiptSummary represents the line items for totals and additional costs (tax and shipping) on a receipt.
type Recipient ¶
type Recipient struct { ID string `json:"id,omitempty"` PhoneNumber string `json:"phone_number,omitempty"` }
Recipient identifies the user to send to. Either Id or PhoneNumber must be set, but not both.
type ResourcePayload ¶
type ResourcePayload struct { URL string `json:"url" binding:"required"` Reusable bool `json:"is_reusable" binding:"required"` }
ResourcePayload is used to hold the URL of a resource (image, file, etc.) to attach to a message.
See https://developers.facebook.com/docs/messenger-platform/send-api-reference/image-attachment
type SavedAssetPayload ¶ added in v1.1.6
type SavedAssetPayload struct {
AttachmentID string `json:"attachment_id" binding:"required"`
}
SavedAssetPayload is used to hold the identifier of an already saved asset (image, file, etc.) to attach to a message.
See https://developers.facebook.com/docs/messenger-platform/send-messages#attachment_reuse
type SendError ¶
type SendError struct { Message string `json:"message" binding:"required"` Type string `json:"type" binding:"required"` Code int `json:"code" binding:"required"` ErrorData string `json:"error_data" binding:"required"` FBTraceID string `json:"fbtrace_id" binding:"required"` }
SendError indicates an error returned from Facebook.
See https://developers.facebook.com/docs/messenger-platform/send-api-reference#errors
type SendRequest ¶
type SendRequest struct { Recipient Recipient `json:"recipient" binding:"required"` Message Message `json:"message" binding:"required"` NotificationType string `json:"notification_type,omitempty"` }
SendRequest is the top level structure for representing any type of message to send.
See https://developers.facebook.com/docs/messenger-platform/send-api-reference#request
func ButtonTemplateMessage ¶
func ButtonTemplateMessage(text string, buttons ...*Button) *SendRequest
ButtonTemplateMessage is a fluent helper method for creating a SendRequest containing text and buttons to request input from the user.
See https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template
func GenericTemplateMessage ¶
func GenericTemplateMessage(elements ...*GenericElement) *SendRequest
GenericTemplateMessage is a fluent helper method for creating a SendRequest containing a carousel of elements, each composed of an image attachment, short description and buttons to request input from the user.
See https://developers.facebook.com/docs/messenger-platform/send-api-reference/generic-template
func ImageDataMessage ¶
func ImageDataMessage(data []byte, contentType string) *SendRequest
ImageDataMessage is a fluent helper method for creating a SendRequest containing a message with an image attached by uploading the bytes of the image.
imageBytes, _ := ioutil.ReadFile("./cool-pic.png") request := ImageDataMessage(imageBytes, "image/png").To("USER_ID")
Detecting the content type of a file dynamically, or converting to one of the image formats supported by Facebook is the responsibility of the user.
See https://developers.facebook.com/docs/messenger-platform/send-api-reference/image-attachment
func ImageMessage ¶
func ImageMessage(url string) *SendRequest
ImageMessage is a fluent helper method for creating a SendRequest containing a message with an image attached using the URL of the image.
See https://developers.facebook.com/docs/messenger-platform/send-messages#sending_attachments
func ReceiptTemplateMessage ¶
func ReceiptTemplateMessage(header *ReceiptHeader, summary *ReceiptSummary, elements ...*ReceiptElement) *SendRequest
ReceiptTemplateMessage is a fluent helper method for creating a SendRequest containing a detailed order confirmation.
https://developers.facebook.com/docs/messenger-platform/send-api-reference/receipt-template
func SavedImageMessage ¶ added in v1.1.6
func SavedImageMessage(id string) *SendRequest
SavedImageMessage is a fluent helper method for creating a SendRequest containing a message with an image attached using the identifier of the image asset.
See https://developers.facebook.com/docs/messenger-platform/send-messages#attachment_reuse
func SavedVideoMessage ¶ added in v1.1.6
func SavedVideoMessage(id string) *SendRequest
SavedVideoMessage is a fluent helper method for creating a SendRequest containing a message with an video attached using the identifier of the video asset.
See https://developers.facebook.com/docs/messenger-platform/send-messages#attachment_reuse
func TextMessage ¶
func TextMessage(text string) *SendRequest
TextMessage is a fluent helper method for creating a SendRequest containing a text message.
func VideoMessage ¶ added in v1.1.6
func VideoMessage(url string) *SendRequest
VideoMessage is a fluent helper method for creating a SendRequest containing a message with an video attached using the URL of the video.
See https://developers.facebook.com/docs/messenger-platform/send-messages#sending_attachments
func WebviewButtonTemplateMessage ¶ added in v1.1.6
func WebviewButtonTemplateMessage(text string, buttons ...*WebviewButton) *SendRequest
WebviewButtonTemplateMessage is a fluent helper method for creating a SendRequest containing text and webview buttons to request input from the user.
See https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template
func (*SendRequest) NoPush ¶
func (sr *SendRequest) NoPush() *SendRequest
NoPush is a fluent helper method for setting NotificationType. It is a mutator and returns the same SendRequest on which it is called to support method chaining.
func (*SendRequest) Regular ¶
func (sr *SendRequest) Regular() *SendRequest
Regular is a fluent helper method for setting NotificationType. It is a mutator and returns the same SendRequest on which it is called to support method chaining.
func (*SendRequest) SilentPush ¶
func (sr *SendRequest) SilentPush() *SendRequest
SilentPush is a fluent helper method for setting NotificationType. It is a mutator and returns the same SendRequest on which it is called to support method chaining.
func (*SendRequest) To ¶
func (sr *SendRequest) To(userID string) *SendRequest
To is a fluent helper method for setting Recipient. It is a mutator and returns the same SendRequest on which it is called to support method chaining.
func (*SendRequest) ToPhoneNumber ¶
func (sr *SendRequest) ToPhoneNumber(phoneNumber string) *SendRequest
ToPhoneNumber is a fluent helper method for setting Recipient. It is a mutator and returns the same SendRequest on which it is called to support method chaining.
func (*SendRequest) WithQuickReplies ¶ added in v1.1.0
func (sr *SendRequest) WithQuickReplies(replies ...*QuickReply) *SendRequest
WithQuickReplies is a fluent helper method for setting the quick replies to a message. It is not additive, it replaces any existing quick replies.
func (*SendRequest) WithReceiptAddress ¶
func (sr *SendRequest) WithReceiptAddress(address *Address) *SendRequest
WithReceiptAddress is a fluent helper method for setting the Address of a ReceiptPayload for the message. It is a mutator and returns the same SendRequest on which it is called to support method chaining.
func (*SendRequest) WithReceiptAdjustments ¶
func (sr *SendRequest) WithReceiptAdjustments(adjustments ...*ReceiptAdjustment) *SendRequest
WithReceiptAdjustments is a fluent helper method for setting the Adjustments of a ReceiptPayload for the message. It is a mutator and returns the same SendRequest on which it is called to support method chaining.
type SendResponse ¶
type SendResponse struct { RecipientID string `json:"recipient_id" binding:"required"` MessageID string `json:"message_id" binding:"required"` AttachmentID string `json:"attachment_id,omitempty"` Error *SendError `json:"error"` }
SendResponse is returned when sending a SendRequest.
See https://developers.facebook.com/docs/messenger-platform/send-api-reference#response
type UserProfile ¶
type UserProfile struct { FirstName string `json:"first_name"` LastName string `json:"last_name"` ProfilePhotoURL string `json:"profile_pic"` Locale string `json:"locale"` Timezone int `json:"timezone"` Gender string `json:"gender"` }
UserProfile represents additional information about the user.
See https://developers.facebook.com/docs/messenger-platform/user-profile
type WebviewButton ¶ added in v1.1.6
type WebviewButton struct { Type string `json:"type" binding:"required"` Title string `json:"title" binding:"required"` URL string `json:"url,omitempty"` Payload string `json:"payload,omitempty"` HeightRatio string `json:"webview_height_ratio,omitempty"` Extension bool `json:"messenger_extensions,omitempty"` }
WebviewButton represents a single webview button in a structured message using the button template.
func WebviewURLButton ¶ added in v1.1.6
func WebviewURLButton(title, url string) *WebviewButton
WebviewURLButton is a fluent helper method for creating a webview button with type "web_url" for use in a message with a button template or generic template attachment.
type WebviewButtonPayload ¶ added in v1.1.6
type WebviewButtonPayload struct { TemplateType string `json:"template_type" binding:"required"` Text string `json:"text" binding:"required"` WebviewButtons []*WebviewButton `json:"buttons" binding:"required"` }
WebviewButtonPayload is used to build a structured message using the button template.
See https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template