messenger

package module
v4.0.0-...-0cb6e82 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2016 License: MIT Imports: 10 Imported by: 1

README

Messenger Platform Go SDK

Build Status Coverage Status

A Go SDK for the Facebook Messenger Platform. Note: Work in Progress, not suitable for production environment yet! Be careful!

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",
	PageID: "PAGE_ID/optional",
}
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.
  • PageID is required for setting welcome message. 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 specifies host used for API requests
	GraphAPI = "https://graph.facebook.com"
)

Functions

This section is empty.

Types

type Attachment

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

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 Coordinates

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

type Delivery

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

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   json.Number `json:"id"`
	Time int64       `json:"time"`
}

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"`
}

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,empty"`
		Read     *Read        `json:"read,omitempty"`
	} `json:"messaging"`
}

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"`
}

type MessageQuery

type MessageQuery struct {
	Recipient        Recipient        `json:"recipient"`
	Message          SendMessage      `json:"message"`
	NotificationType NotificationType `json:"notification_type,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) Template

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

func (*MessageQuery) Text

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

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"`
}

type Messenger

type Messenger struct {
	VerifyToken string
	AppSecret   string
	AccessToken string
	PageID      string

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

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) (*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"`
}

type Postback

type Postback struct {
	Payload string `json:"payload"`
}

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 {
	FirstName      string `json:"first_name"`
	LastName       string `json:"last_name"`
	ProfilePicture string `json:"profile_pic,omitempty"`
	Locale         string `json:"locale,omitempty"`
	Timezone       int    `json:"timezone,omitempty"`
	Gender         string `json:"gender,omitempty"`
}

Profile struct holds data associated with Facebook profile

type QuickReply

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

type QuickReplyPayload

type QuickReplyPayload struct {
	Payload string
}

type Read

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

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"`
	IsEcho      bool               `json:"is_echo,omitempty"`
	Metadata    *string            `json:"metadata,omitempty"`
}

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 Resource

type Resource struct {
	URL string `json:"url"`
}

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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