messenger

package module
v0.0.0-...-7d3c142 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2022 License: MIT Imports: 10 Imported by: 0

README

Messenger Platform Go SDK

Build Status Coverage Status

A Go SDK for the Facebook Messenger Platform.

Installation

go get gopkg.in/maciekmm/messenger-platform-go-sdk.v4

Usage

The main package has been named messenger for convenience.

Your first step is to create Messenger instance.

import "gopkg.in/maciekmm/messenger-platform-go-sdk.v4"

//...

messenger := &messenger.Messenger {
	VerifyToken: "VERIFY_TOKEN/optional",
	AppSecret: "APP_SECRET/optional",
	AccessToken: "PAGE_ACCESS_TOKEN",
	Debug: messenger.DebugAll, //All,Info,Warning
}
Parameters
  • VerifyToken is the token needed for a verification process facebook performs. It's only required once. Optional.
  • AppSecret is the Application Secret token. It's used for message integrity check. Optional.
  • AccessToken is required to send messages. You can find this token in your app developer dashboard under Messenger tab.
  • Debug is used for setting debug mode type as described on https://developers.facebook.com/docs/graph-api/using-graph-api#debugging. Optional.

The next step is to hook up the handler to your HTTP server.

//hook up
http.HandleFunc("/webhook", messenger.Handler)
//start the server
http.ListenAndServe(":5646", nil)

The next step is to subscribe to an event, to do that you have to hook up your own handler.

messenger.MessageReceived = MessageReceived

//...

func MessageReceived(event messenger.Event, opts messenger.MessageOpts, msg messenger.ReceivedMessage) {
//do stuff
}
Sending messages

Example

Check more examples in examples folder.

var mess = &messenger.Messenger{
	AccessToken: "ACCESS_TOKEN",
}

func main() {
	mess.MessageReceived = MessageReceived
	http.HandleFunc("/webhook", mess.Handler)
	log.Fatal(http.ListenAndServe(":5646", nil))
}

func MessageReceived(event messenger.Event, opts messenger.MessageOpts, msg messenger.ReceivedMessage) {
	profile, err := mess.GetProfile(opts.Sender.ID)
	if err != nil {
		fmt.Println(err)
		return
	}
	resp, err := mess.SendSimpleMessage(opts.Sender.ID, fmt.Sprintf("Hello, %s %s, %s", profile.FirstName, profile.LastName, msg.Text))
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("%+v", resp)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var GraphAPI = "https://graph.facebook.com"

GraphAPI specifies host used for API requests

Functions

This section is empty.

Types

type Attachment

type Attachment struct {
	Type    AttachmentType `json:"type"`
	Payload interface{}    `json:"payload,omitempty"`
}

func (*Attachment) UnmarshalJSON

func (a *Attachment) UnmarshalJSON(b []byte) error

type AttachmentType

type AttachmentType string
const (
	AttachmentTypeTemplate AttachmentType = "template"
	AttachmentTypeImage    AttachmentType = "image"
	AttachmentTypeVideo    AttachmentType = "video"
	AttachmentTypeAudio    AttachmentType = "audio"
	AttachmentTypeLocation AttachmentType = "location"
)

type AuthenticationHandler

type AuthenticationHandler func(Event, MessageOpts, *Optin)

AuthenticationHandler is called when a new user joins/authenticates

type ContentType

type ContentType string
const (
	ContentTypeText     ContentType = "text"
	ContentTypeLocation ContentType = "location"
)

type Coordinates

type Coordinates struct {
	Latitude  float64 `json:"lat"`
	Longitude float64 `json:"long"`
}

type DebugType

type DebugType string

DebugType describes available debug type options as documented on https://developers.facebook.com/docs/graph-api/using-graph-api#debugging

const (
	// DebugAll returns all available debug messages
	DebugAll DebugType = "all"
	// DebugInfo returns debug messages with type info or warning
	DebugInfo DebugType = "info"
	// DebugWarning returns debug messages with type warning
	DebugWarning DebugType = "warning"
)

type Delivery

type Delivery struct {
	MessageIDS []string `json:"mids"`
	Watermark  int64    `json:"watermark"`
	Seq        int      `json:"seq"`
}

Delivery contains information specific to a message delivered callback. https://developers.facebook.com/docs/messenger-platform/webhook-reference/message-delivered

type Error

type Error struct {
	Message   string `json:"message"`
	Type      string `json:"type"`
	Code      int    `json:"code"`
	ErrorData string `json:"error_data"`
	TraceID   string `json:"fbtrace_id"`
}

func (Error) Error

func (e Error) Error() string

type Event

type Event struct {
	ID      string        `json:"id"`
	Time    int64         `json:"time"`
	Request *http.Request `json:"-"`
}

Event represents a Webhook postback event. https://developers.facebook.com/docs/messenger-platform/webhook-reference#format

type Location

type Location struct {
	Coordinates Coordinates `json:"coordinates"`
}

type MessageDeliveredHandler

type MessageDeliveredHandler func(Event, MessageOpts, Delivery)

MessageDeliveredHandler is called when a message sent has been successfully delivered

type MessageEcho

type MessageEcho struct {
	ReceivedMessage
	AppID int64 `json:"app_id,omitempty"`
}

MessageEcho contains information specific to an echo callback. https://developers.facebook.com/docs/messenger-platform/webhook-reference/message-echo

type MessageEchoHandler

type MessageEchoHandler func(Event, MessageOpts, MessageEcho)

MessageEchoHandler is called when a message is sent by your page

type MessageEvent

type MessageEvent struct {
	Event
	Messaging []struct {
		MessageOpts
		Message           *MessageEcho       `json:"message,omitempty"`
		Delivery          *Delivery          `json:"delivery,omitempty"`
		Postback          *Postback          `json:"postback,omitempty"`
		Optin             *Optin             `json:"optin,omitempty"`
		Read              *Read              `json:"read,omitempty"`
		Referral          *Referral          `json:"referral,omitempty"`
		PassThreadControl *PassThreadControl `json:"pass_thread_control,omitempty"`
		TakeThreadControl *TakeThreadControl `json:"take_thread_control,omitempty"`
	} `json:"messaging"`
}

MessageEvent encapsulates common info plus the specific type of callback being received. https://developers.facebook.com/docs/messenger-platform/webhook-reference#format

type MessageOpts

type MessageOpts struct {
	Sender struct {
		ID string `json:"id"`
	} `json:"sender"`
	Recipient struct {
		ID string `json:"id"`
	} `json:"recipient"`
	Timestamp int64 `json:"timestamp"`
}

MessageOpts contains information common to all message events. https://developers.facebook.com/docs/messenger-platform/webhook-reference#format

type MessageQuery

type MessageQuery struct {
	Recipient        Recipient        `json:"recipient"`
	Message          SendMessage      `json:"message"`
	NotificationType NotificationType `json:"notification_type,omitempty"`
	MessagingType    MessagingType    `json:"messaging_type,omitempty"`
	MessageTag       MessageTag       `json:"tag,omitempty"`
}

func (*MessageQuery) Audio

func (mq *MessageQuery) Audio(url string) error

func (*MessageQuery) Image

func (mq *MessageQuery) Image(url string) error

func (*MessageQuery) Metadata

func (mq *MessageQuery) Metadata(metadata string) error

func (*MessageQuery) Notification

func (mq *MessageQuery) Notification(notification NotificationType) *MessageQuery

func (*MessageQuery) RecipientID

func (mq *MessageQuery) RecipientID(recipientID string) error

func (*MessageQuery) RecipientPhoneNumber

func (mq *MessageQuery) RecipientPhoneNumber(phoneNumber string) error

func (*MessageQuery) Tag

func (mq *MessageQuery) Tag(tag MessageTag) *MessageQuery

func (*MessageQuery) Template

func (mq *MessageQuery) Template(tpl template.Template) error

func (*MessageQuery) Text

func (mq *MessageQuery) Text(text string) error

func (*MessageQuery) Type

func (mq *MessageQuery) Type(messagingType MessagingType) *MessageQuery

func (*MessageQuery) Video

func (mq *MessageQuery) Video(url string) error

type MessageReadHandler

type MessageReadHandler func(Event, MessageOpts, Read)

MessageReadHandler is called when a message has been read by recipient

type MessageReceivedHandler

type MessageReceivedHandler func(Event, MessageOpts, ReceivedMessage)

MessageReceivedHandler is called when a new message is received

type MessageResponse

type MessageResponse struct {
	RecipientID  string `json:"recipient_id"`
	MessageID    string `json:"message_id"`
	AttachmentID string `json:"attachment_id,omitempty"`
}

type MessageTag

type MessageTag string

MessageTag identifies the messaging type of the message being sent

const (
	// MessageTagCommunityAlert notifies the message recipient of emergency or utility alerts, or issue a safety check in your community.
	MessageTagCommunityAlert MessageTag = "COMMUNITY_ALERT"
	// MessageTagEventReminder sends the message recipient reminders of a scheduled event which a person is going to attend.
	MessageTagEventReminder MessageTag = "CONFIRMED_EVENT_REMINDER"
	// MessageTagNonPromotionalSubscription sends non-promotional messages under the News, Productivity, and Personal Trackers, ...
	MessageTagNonPromotionalSubscription MessageTag = "NON_PROMOTIONAL_SUBSCRIPTION"
	// MessageTagPairingUpdate notifies the message recipient that a pairing has been identified based on a prior request.
	MessageTagPairingUpdate MessageTag = "PAIRING_UPDATE"
	// MessageTagApplicationUpdate notifies the message recipient of an update on the status of their application.
	MessageTagApplicationUpdate MessageTag = "APPLICATION_UPDATE"
	// MessageTagAccountUpdate notifies the message recipient of a change to their account settings.
	MessageTagAccountUpdate MessageTag = "ACCOUNT_UPDATE"
	// MessageTagPaymentUpdate notifies the message recipient of a payment update for an existing transaction.
	MessageTagPaymentUpdate MessageTag = "PAYMENT_UPDATE"
	// MessageTagPersonalFinanceUpdate confirms a message recipient's financial activity.
	MessageTagPersonalFinanceUpdate MessageTag = "PERSONAL_FINANCE_UPDATE"
	// MessageTagShippingUpdate notifies the message recipient of a change in shipping status for a product that has already been purchased.
	MessageTagShippingUpdate MessageTag = "SHIPPING_UPDATE"
	// MessageTagReservationUpdate notifies the message recipient of updates to an existing reservation.
	MessageTagReservationUpdate MessageTag = "RESERVATION_UPDATE"
	// MessageTagIssueResolution notifies the message recipient of an update to a customer service issue that was initiated in a Messenger conversation.
	MessageTagIssueResolution MessageTag = "ISSUE_RESOLUTION"
	// MessageTagAppointmentUpdate notifies the message recipient of a change to an existing appointment.
	MessageTagAppointmentUpdate MessageTag = "APPOINTMENT_UPDATE"
	// MessageTagGameEvent notifies the message recipient of a change in in-game user progression, global events, or a live sporting event.
	MessageTagGameEvent MessageTag = "GAME_EVENT"
	// MessageTagTransportationUpdate notifies the message recipient of updates to an existing transportation reservation.
	MessageTagTransportationUpdate MessageTag = "TRANSPORTATION_UPDATE"
	// MessageTagFeatureFuntionalityUpdate notifies the message recipient of new features or functionality that become available in your bot.
	MessageTagFeatureFuntionalityUpdate MessageTag = "FEATURE_FUNCTIONALITY_UPDATE"
	// MessageTagFeatureTickerUpdate send the message recipient updates or reminders for an event for which a person already has a ticket.
	MessageTagFeatureTickerUpdate MessageTag = "TICKET_UPDATE"
	// MessageTagHumanAgent allows human agents to respond to user inquiries. Messages can be sent within 7 days after a user message.
	MessageTagHumanAgent MessageTag = "HUMAN_AGENT"
)

type MessagingType

type MessagingType string

MessagingType identifies the messaging type of the message being sent

const (
	// MessagingTypeRegular is in response to a received message
	MessagingTypeRegular MessagingType = "RESPONSE"
	// MessagingTypeUpdate is being sent proactively and is not in response to a received message
	MessagingTypeUpdate MessagingType = "UPDATE"
	// MessagingTypeTag is non-promotional and is being sent outside the 24-hour standard messaging window
	MessagingTypeTag MessagingType = "MESSAGE_TAG"
)

type Messenger

type Messenger struct {
	VerifyToken string
	AppSecret   string
	AccessToken string
	Debug       DebugType

	MessageReceived  MessageReceivedHandler
	MessageDelivered MessageDeliveredHandler
	Postback         PostbackHandler
	Authentication   AuthenticationHandler
	MessageRead      MessageReadHandler
	MessageEcho      MessageEchoHandler

	Client *http.Client
}

Messenger is the main service which handles all callbacks from facebook Events are delivered to handlers if they are specified

func (*Messenger) DeleteGetStartedButton

func (m *Messenger) DeleteGetStartedButton() error

DeleteGetStartedButton delets a button set by SetGetStartedButton

func (*Messenger) DeletePersistentMenu

func (m *Messenger) DeletePersistentMenu() error

DeletePersistentMenu deletes a menu set by SetPersistentMenu

func (*Messenger) GetPSID

func (m *Messenger) GetPSID(token string) (*string, error)

GetPSID fetches user's page scoped id during authentication flow one must supply a valid and not expired authentication token provided by facebook https://developers.facebook.com/docs/messenger-platform/account-linking/authentication

func (*Messenger) GetProfile

func (m *Messenger) GetProfile(userID string, scope string) (*Profile, error)

GetProfile fetches the recipient's profile from facebook platform Non empty UserID has to be specified in order to receive the information

func (*Messenger) Handler

func (m *Messenger) Handler(rw http.ResponseWriter, req *http.Request)

Handler is the main HTTP handler for the Messenger service. It MUST be attached to some web server in order to receive messages

func (*Messenger) SendAction

func (m *Messenger) SendAction(recipient Recipient, action SenderAction) error

func (*Messenger) SendMessage

func (m *Messenger) SendMessage(mq MessageQuery) (*MessageResponse, error)

func (*Messenger) SendSimpleMessage

func (m *Messenger) SendSimpleMessage(recipient string, message string) (*MessageResponse, error)

func (*Messenger) SetGetStartedButton

func (m *Messenger) SetGetStartedButton(payload string) error

SetGetStartedButton sets a button which is shown at the bottom of the window ans is only rendered the first time the user interacts with the Page on Messenger When this button is tapped, we will trigger the postback received callback and deliver the person's page-scoped ID (PSID). You can then present a personalized message to greet the user or present buttons to prompt him or her to take an action. https://developers.facebook.com/docs/messenger-platform/thread-settings/get-started-button

func (*Messenger) SetGreetingText

func (m *Messenger) SetGreetingText(text string) error

SetGreetingText sets a greeting text which is only rendered the first time user interacts with the Page on Messenger https://developers.facebook.com/docs/messenger-platform/thread-settings/greeting-text text must be UTF-8 and have a 160 character limit

func (*Messenger) SetPersistentMenu

func (m *Messenger) SetPersistentMenu(buttons []template.Button) error

SetPersistentMenu sets a Persistent Menu is a persistent menu that is always available to the user. This menu should contain top-level actions that users can enact at any point. Having a persistent menu easily communicates the basic capabilities of your bot for first-time and returning users. The menu will automatically appear in a thread if the person has been away for a certain period of time and return.. https://developers.facebook.com/docs/messenger-platform/thread-settings/persistent-menu

type NotificationType

type NotificationType string

NotificationType describes the behavior phone will execute after receiving the message

const (
	// NotificationTypeRegular will emit a sound/vibration and a phone notification
	NotificationTypeRegular NotificationType = "REGULAR"
	// NotificationTypeSilentPush will just emit a phone notification
	NotificationTypeSilentPush NotificationType = "SILENT_PUSH"
	// NotificationTypeNoPush will not emit sound/vibration nor a phone notification
	NotificationTypeNoPush NotificationType = "NO_PUSH"
)

type Optin

type Optin struct {
	Ref string `json:"ref"`
}

Optin contains information specific to Opt-In callbacks. https://developers.facebook.com/docs/messenger-platform/webhook-reference/optins

type PassThreadControl

type PassThreadControl struct {
	NewOwnerAppID int64  `json:"new_owner_app_id,omitempty"`
	Metadata      string `json:"metadata,omitempty"`
}

The Pass Thread Control API of the handover protocol is used to pass control of a conversation from one app to another. https://developers.facebook.com/docs/messenger-platform/handover-protocol/take-thread-control

type Postback

type Postback struct {
	Title    string    `json:"title,omitempty"`
	Payload  string    `json:"payload,omitempty"`
	Referral *Referral `json:"referral,omitempty"`
}

Postback contains content specific to a postback. https://developers.facebook.com/docs/messenger-platform/webhook-reference/message

type PostbackHandler

type PostbackHandler func(Event, MessageOpts, Postback)

PostbackHandler is called when the postback button has been pressed by recipient

type Profile

type Profile struct {
	Name           string  `json:"name,omitempty"`     // Instagram Fallback
	UserName       string  `json:"username,omitempty"` // Instagram username
	FirstName      string  `json:"first_name"`
	LastName       string  `json:"last_name"`
	ProfilePicture string  `json:"profile_pic,omitempty"`
	Locale         string  `json:"locale,omitempty"`
	Timezone       float64 `json:"timezone,omitempty"`
	Gender         string  `json:"gender,omitempty"`
}

Profile struct holds data associated with Facebook profile

type QuickReply

type QuickReply struct {
	ContentType ContentType `json:"content_type"`
	Title       string      `json:"title,omitempty"`
	Payload     string      `json:"payload,omitempty"`
	ImageURL    string      `json:"image_url,omitempty"`
}

type QuickReplyPayload

type QuickReplyPayload struct {
	Payload string
}

QuickReplyPayload contains content specific to a quick reply. https://developers.facebook.com/docs/messenger-platform/webhook-reference/message

type Read

type Read struct {
	Watermark int64 `json:"watermark"`
	Seq       int   `json:"seq"`
}

Read contains data specific to message read callbacks. https://developers.facebook.com/docs/messenger-platform/webhook-reference/message-read

type ReceivedMessage

type ReceivedMessage struct {
	ID          string             `json:"mid"`
	Text        string             `json:"text,omitempty"`
	Attachments []*Attachment      `json:"attachments,omitempty"`
	Seq         int                `json:"seq"`
	QuickReply  *QuickReplyPayload `json:"quick_reply,omitempty"`
	ReplyTo     *ReplyTo           `json:"reply_to,omitempty"`
	IsEcho      bool               `json:"is_echo,omitempty"`
	Metadata    *string            `json:"metadata,omitempty"`
}

ReceivedMessage contains message specific information included with an echo callback. https://developers.facebook.com/docs/messenger-platform/webhook-reference/message-echo

type Recipient

type Recipient struct {
	ID          string `json:"id,omitempty"`
	PhoneNumber string `json:"phone_number,omitempty"`
}

Recipient describes the person who will receive the message Either ID or PhoneNumber has to be set

type Referral

type Referral struct {
	Ref    string `json:"ref,omitempty"`
	Source string `json:"source,omitempty"`
	Type   string `json:"type,omitempty"`
}

Referral contains content specific to a referal. https://developers.facebook.com/docs/messenger-platform/webhook-reference/referal

type ReplyTo

type ReplyTo struct {
	Story *struct {
		URL string `json:"url,omitempty"`
		ID  string `json:"id,omitempty"`
	} `json:"story,omitempty"`
}

type Resource

type Resource struct {
	URL      string `json:"url"`
	Reusable bool   `json:"is_reusable,omitempty"`
}

type ReusableAttachment

type ReusableAttachment struct {
	AttachmentID string `json:"attachment_id"`
}

type SendMessage

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

type SenderAction

type SenderAction string
const (
	SenderActionMarkSeen SenderAction = "mark_seen"
	//SenderActionTypingOn indicator is automatically turned off after 20 seconds
	SenderActionTypingOn  SenderAction = "typing_on"
	SenderActionTypingOff SenderAction = "typing_off"
)

type TakeThreadControl

type TakeThreadControl struct {
	PreviousOwnerAppID int64  `json:"previous_owner_app_id,omitempty"`
	Metadata           string `json:"metadata,omitempty"`
}

Take Thread Control API allows the app with the Primary Receiver role to take control of the conversation https://developers.facebook.com/docs/messenger-platform/handover-protocol/pass-thread-control

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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