mbotapi

package module
v0.0.0-...-40ea7e0 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2019 License: MIT Imports: 16 Imported by: 0

README

Golang bindings for the Messenger Bot API

The scope of this project is just to provide a wrapper around the API without any additional features.

Example

This is a very simple bot that just displays any gotten updates, then replies it to it.

package main

import (
	"log"
    "net/http"
	"github.com/abhinavdahiya/go-messenger-bot"
)

func main() {
	bot := mbotapi.NewBotAPI("ACCESS_TOKEN", "VERIFY_TOKEN")

	callbacks, mux := bot.SetWebhook("/webhook")
	go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", mux)

    for callback := range callbacks {
        log.Printf("[%#v] %s", callback.Sender, callback.Message.Text)

        msg := mbotapi.NewMessage(callback.Message.Text)
        bot.Send(callback.Sender, msg, mbotapi.RegularNotif)
    }
}

Facebook messenger webhook needs a certificate certified by known CA, Now that Let's Encrypt has entered public beta, you may wish to generate your free TLS certificate there.

Inspiration

Messenger takes design cues from:

Documentation

Index

Constants

View Source
const (
	RegularNotif = "REGULAR"
	SilentNotif  = "SILENT_PUSH"
	NoNotif      = "NO_PUSH"
	TypingON     = "typing_on"
	TypingOFF    = "typing_off"
	MarkSeen     = "mark_seen"
)
View Source
const (
	APIEndpoint = "https://graph.facebook.com/v2.6/me/messages?access_token=%s"
)
View Source
const (
	SettingsEndpoint = "https://graph.facebook.com/v2.6/me/thread_settings?access_token=%s"
)

Variables

View Source
var (
	ErrTitleTooLong         = errors.New("Template Title exceeds the 25 character limit")
	ErrSubtitleTooLong      = errors.New("Template Subtitle exceeds the 80 character limit")
	ErrButtonsLimitExceeded = errors.New("Max 3 buttons allowed on GenericTemplate")
	ErrBubblesLimitExceeded = errors.New("Max 10 bubbles allowed on GenericTemplate")
)

Functions

This section is empty.

Types

type APIResponse

type APIResponse struct {
	RID   int64         `json:"recipient_id,string"`
	MID   string        `json:"message_id"`
	Error ErrorResponse `json:"error"`
}

type Action

type Action string

func NewAction

func NewAction(ac Action) Action

Create a sender action takes const TypingON/TypingOFF/MarkSeen

type Attachment

type Attachment struct {
	Type    string            `json:"type"`
	Payload AttachmentPayload `json:"payload"`
}

type AttachmentPayload

type AttachmentPayload interface{}

type BotAPI

type BotAPI struct {
	Token       string
	VerifyToken string
	AppSecret   string
	Debug       bool
	Client      *http.Client
}

This defines a bot Set Debug to true for debugging

func NewBotAPI

func NewBotAPI(token string, vtoken string, secret string) *BotAPI

This helps create a BotAPI instance with token, verify_token By default Debug is set to false

func (*BotAPI) MakeRequest

func (bot *BotAPI) MakeRequest(b *bytes.Buffer) (APIResponse, error)

This helps send request (send messages to users) It takes Request struct encoded into a buffer of json bytes The APIResponse contains the error from FB if any Should NOT be directly used, Use Send / SendFile

func (*BotAPI) MakeRequestMultipart

func (bot *BotAPI) MakeRequestMultipart(contentType string, body io.Reader) (APIResponse, error)

func (*BotAPI) Send

func (bot *BotAPI) Send(u User, c interface{}, notif string) (APIResponse, error)

This function helps send messages to users It takes Message / GenericTemplate / ButtonTemplate / ReceiptTemplate and sends it to the user

func (*BotAPI) SendFile

func (bot *BotAPI) SendFile(u User, path string) (APIResponse, error)

This helps to send local images (currently) to users TODO: not tested yet!

func (*BotAPI) SendStream

func (bot *BotAPI) SendStream(u User, filename, contentType string, r io.Reader) (APIResponse, error)

func (*BotAPI) SetGStarted

func (bot *BotAPI) SetGStarted(text string) error

func (*BotAPI) SetGreeting

func (bot *BotAPI) SetGreeting(text string) error

func (*BotAPI) SetMenu

func (bot *BotAPI) SetMenu(bts []Button) error

func (*BotAPI) SetSettings

func (bot *BotAPI) SetSettings(b *bytes.Buffer) error

func (*BotAPI) SetWebhook

func (bot *BotAPI) SetWebhook(pattern string) (<-chan Callback, *http.ServeMux)

This function registers the handlers for - webhook verification - all callbacks made on the webhhoks It loops over all entries in the callback and pushes to the Callback channel This also return a *http.ServeMux which can be used to listenAndServe

type Button

type Button struct {
	Type    string `json:"type"`
	Title   string `json:"title,omitempty"`
	URL     string `json:"url,omitempty"`
	Payload string `json:"payload,omitempty"`
}

func NewPhoneButton

func NewPhoneButton(title, pn string) Button

Creates a new Button of type `phone_number`

func NewPostbackButton

func NewPostbackButton(title, postback string) Button

Creates a new Button of type `postback`

func NewURLButton

func NewURLButton(title, url string) Button

Creates a new Button of type `web_url`

type ButtonTemplate

type ButtonTemplate struct {
	TemplateBase
	Text    string   `json:"text,omitempty"`
	Buttons []Button `json:"buttons,omitempty"`
}

Used as payload for type template(button)

func NewButtonTemplate

func NewButtonTemplate(text string) ButtonTemplate

Creates an empty Button Template

func (*ButtonTemplate) AddButton

func (b *ButtonTemplate) AddButton(bt ...Button)

type Callback

type Callback struct {
	Sender    User          `json:"sender"`
	Recipient Page          `json:"recipient"`
	Timestamp int64         `json:"timestamp"`
	Optin     InputOptin    `json:"optin"`
	Message   InputMessage  `json:"message,omitempty"`
	Postback  InputPostback `json:"postback,omitempty"`
	Delivery  InputDelivery `json:"delivery,omitempty"`
}

This represents the content of the message sent by the user Various kinds of callbacks from user are - OptinCallback MessageCallback PostbackCallback DeliveryCallback

TODO: Create a way to identify the type of callback

func (Callback) IsDelivery

func (c Callback) IsDelivery() bool

func (Callback) IsMessage

func (c Callback) IsMessage() bool

func (Callback) IsOptin

func (c Callback) IsOptin() bool

func (Callback) IsPostback

func (c Callback) IsPostback() bool

type Element

type Element struct {
	Title    string   `json:"title"`
	URL      string   `json:"item_url,omitempty"`
	ImageURL string   `json:"image_url,omitempty"`
	Subtitle string   `json:"subtitle,omitempty"`
	Buttons  []Button `json:"buttons,omitempty"`
}

func NewElement

func NewElement(title string) Element

Creates a new Element (info card) to be sent as part of the generic template

func (*Element) AddButton

func (e *Element) AddButton(b ...Button)

type Entry

type Entry struct {
	PageID    string     `json:"id"`
	Time      int64      `json:"time"`
	Messaging []Callback `json:"messaging"`
}

This defines an Entry in the payload by webhook

type ErrorResponse

type ErrorResponse struct {
	Message    string `json:"message"`
	Type       string `json:"type"`
	Code       int    `json:"code"`
	ErrorData  string `json:"error_data"`
	FBstraceID string `json:"fbstrace_id"`
}

type FilePayload

type FilePayload struct {
	URL string `json:"url,omitempty"`
}

Used as payload for type image/audio/video/file

type GStarted

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

type GenericTemplate

type GenericTemplate struct {
	TemplateBase
	Elements []Element `json:"elements"`
}

Used as payload for type template(generic)

func NewGenericTemplate

func NewGenericTemplate() GenericTemplate

Creates an empty generic template

func (*GenericTemplate) AddElement

func (g *GenericTemplate) AddElement(e ...Element)

func (GenericTemplate) Validate

func (g GenericTemplate) Validate() error

type Greeting

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

type InputAttachPayload

type InputAttachPayload struct {
	URL    string      `json:"url,omitempty"`
	Coords InputCoords `json:"coordinates,omitempty"`
}

type InputAttachment

type InputAttachment struct {
	Type    string             `json:"type"`
	Payload InputAttachPayload `json:"payload"`
}

Represents an attachement The types are image/audio/video/location

type InputCoords

type InputCoords struct {
	Lat  float64 `json:"lat"`
	Long float64 `json:"long"`
}

type InputDelivery

type InputDelivery struct {
	MIDs      []string `json:"mids"`
	Watermark int64    `json:"watermark"`
	Seq       int64    `json:"seq"`
}

This contains delivery reports for batch of messages(mids)

type InputMessage

type InputMessage struct {
	MID         string            `json:"mid"`
	Seq         int64             `json:"seq"`
	Text        string            `json:"text"`
	Attachments []InputAttachment `json:"attachments,omitempty"`
	QuickReply  InputQRPayload    `json:"quick_reply,omitempty"`
}

This represents a Message from user If text message only Text field exists If media message Attachments fields contains an array of attachmensts sent

type InputOptin

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

Ref contains the `data-ref` set for message optin for the bot

type InputPostback

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

Represents a postback sent by clicking on Postback Button

type InputQRPayload

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

Represents a quick reply payload

type ListTemplate

type ListTemplate struct {
	GenericTemplate
	TopElementStyle string `json:"top_element_style"` // compact or large(default)
}

func NewListTemplate

func NewListTemplate() ListTemplate

Creates an empty list template

type Message

type Message struct {
	Text       string      `json:"text,omitempty"`
	Attachment *Attachment `json:"attachment,omitempty"`
	QuickReply []QR        `json:"quick_replies,omitempty"`
}

func NewAudioFromURL

func NewAudioFromURL(url string) Message

Creates a Message with audio attachment to be sent by bot

func NewFileFromURL

func NewFileFromURL(url string) Message

Creates a Message with file attachment to be sent by bot

func NewImageFromURL

func NewImageFromURL(url string) Message

Creates a Message with image attachment to be sent by bot

func NewMessage

func NewMessage(text string) Message

Creates a Message with given text to be sent by bot

func NewVideoFromURL

func NewVideoFromURL(url string) Message

Creates a Message with video attachment to be sent by bot

func (*Message) AddQR

func (m *Message) AddQR(q ...QR)

type OrderAddress

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

type OrderAdjustment

type OrderAdjustment struct {
	Name   string `json:"name"`
	Amount int    `json:"amount"`
}

type OrderItem

type OrderItem struct {
	Title    string `json:"title"`
	Subtitle string `json:"subtitle,omitempty"`
	Quantity int    `json:"quantity,omitempty"`
	Price    int    `json:"price,omitempty"`
	Currency string `json:"currency,omitempty"`
	ImageURL string `json:"image_url,omiempty"`
}

type OrderSummary

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

type Page

type Page struct {
	ID string `json:"id"`
}

type QR

type QR struct {
	Type    string `json:"content_type"`
	Title   string `json:"title"`
	Payload string `json:"payload"`
}

func NewQuickReply

func NewQuickReply(title string, pst string) QR

Creates a quick reply Takes two parameters: - title(string) - postback_payload(string)

type ReceiptTemplate

type ReceiptTemplate struct {
	TemplateBase
	RecipientName string            `json:"recipient_name"`
	ID            string            `json:"order_number"`
	Currency      string            `json:"currency"`
	PaymentMethod string            `json:"payment_method"`
	Timestamp     int64             `json:"timestamp,omitempty"`
	URL           string            `json:"order_url,omitempty"`
	Items         []OrderItem       `json:"elements"`
	Address       *OrderAddress     `json:"address,omitempty"`
	Summary       OrderSummary      `json:"summary"`
	Adjustments   []OrderAdjustment `json:"adjustments,omitempty"`
}

Used as payload for type template(receipt)

func NewReceiptTemplate

func NewReceiptTemplate(rname string) ReceiptTemplate

Creates an empty Receipt Template

type Request

type Request struct {
	Recipient     User    `json:"recipient"`
	Message       Message `json:"message,omitempty"`
	Action        Action  `json:"sender_action,omitempty"`
	NotifType     string  `json:"notification_type"`
	MessagingType string  `json:"messaging_type,omitempty"`
}

type Response

type Response struct {
	Object  string  `json:"object"`
	Entries []Entry `json:"entry"`
}

Payload received by the webhook The Object field is always set to `page` Contains bacthed entries

type TemplateBase

type TemplateBase struct {
	Type string `json:"template_type"`
}

type ThreadSetting

type ThreadSetting struct {
	Type     string      `json:"setting_type"`
	State    string      `json:"thread_state,omitempty"`
	Action   interface{} `json:"call_to_actions,omitempty"`
	Greeting *Greeting   `json:"greeting,omitempty"`
}

type User

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

This defines an user One of the fields will be set to identify the user

func NewUserFromID

func NewUserFromID(id string) User

Creates a User from ID(int64)

func NewUserFromPhone

func NewUserFromPhone(p string) User

Creates a User from phone no(string)

Jump to

Keyboard shortcuts

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