chatbase

package module
v2.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Dec 25, 2018 License: MIT Imports: 10 Imported by: 1

README

go-chatbase

Build Status godoc

Golang client for interacting with the chatbase.com bot analytics API

Installation

Use go get:

$ go get github.com/m90/go-chatbase

Example

Send a single message to Chatbase:

// a client is a wrapper around an chatbase API key
client := chatbase.New("MY-API-KEY")

// calling Message requires passing of all required values
message := client.Message(chatbase.MessageTypeAgent, "USER-ID", chatbase.PlatformTelegram)

// optional values are added after creation
message.SetMessage("I didn't understand that, sorry")

// this can also be chained
message.SetIntent("fallback").SetNotHandled(true)

// calling Submit will send the data to chatbase
response, err := message.Submit()
if err != nil {
	// an error submitting the data occurred
	fmt.Println(err)
} else if !response.Status.OK() {
	// the data was submitted to ChatBase, but
	// the response contained an error code
	fmt.Println(response.Reason)
}

Supported APIs

Generic message API

The generic message API allows handling of Message, Messages and Update types.

Message
message := client.Message(chatbase.UserType, "USER-ID", "messenger")
message.SetMessage("How are you today?")
response, err := message.Submit()
if err != nil {
	// an error submitting the data occurred
	fmt.Println(err)
} else if !response.Status.OK() {
	// the data was submitted to ChatBase, but
	// the response contained an error code
	fmt.Println(response.Reason)
}
Messages
messages := chatbase.Messages{}
for i := 1; i < 4; i++ {
	message := client.AgentMessage("USER-ID", "messenger")
	message.SetMessage(fmt.Sprintf("Counting: %d", i))
	messages.Append(message)
}
response, err := messages.Submit()
if err != nil {
	// an error submitting the data occurred
	fmt.Println(err)
} else if !response.Status.OK() {
	// the data was submitted to ChatBase, but
	// the response contained an error code
	fmt.Println(response.Reason)
}
Update
update := client.Update("ID-OF-MESSAGE-TO-UPDATE")
update.SetIntent("this-changed")
response, err := update.Submit()
if err != nil {
	// an error submitting the data occurred
	fmt.Println(err)
} else if !response.Status.OK() {
	// the data was submitted to ChatBase, but
	// the response contained an error code
	fmt.Println(response.Reason)
}
Facebook Message API

The Facebook Message API allows handling of FacebookMessage, FacebookMessages, FacebookRequestResponse and FacebookRequestResponses types.

FacebookMessage
message := client.FacebookMessage(facebookPayload)
message.SetIntent("test-messenger")
response, err := message.Submit()
if err != nil {
	// an error submitting the data occurred
	fmt.Println(err)
} else if !response.Status.OK() {
	// the data was submitted to ChatBase, but
	// the response contained an error code
	fmt.Println(response.Reason)
}
FacebookMessages
messages := chatbase.FacebookMessages{}
for _, msg := range listOfFacebookMessages {
	message := client.FacebookMessage(msg).SetVersion("0.0.1-beta")
	messages.Append(message)
}

response, err := messages.Submit()
if err != nil {
	// an error submitting the data occurred
	fmt.Println(err)
} else if !response.Status.OK() {
	// the data was submitted to ChatBase, but
	// the response contained an error code
	fmt.Println(response.Reason)
}
FacebookRequestResponse
pair := client.FacebookRequestResponse(incomingMessage, respondingMessage)
pair.SetIntent("test-messenger")
response, err := pair.Submit()
if err != nil {
	// an error submitting the data occurred
	fmt.Println(err)
} else if !response.Status.OK() {
	// the data was submitted to ChatBase, but
	// the response contained an error code
	fmt.Println(response.Reason)
}
FacebookRequestResponses
pairs := chatbase.FacebookRequestResponses{}
for _, msg := range listOfFacebookMessages {
	pair := client.FacebookRequestResponse(msg.request, msg.response).SetVersion("0.0.1-beta")
	pairs.Append(pair)
}

response, err := pairs.Submit()
if err != nil {
	// an error submitting the data occurred
	fmt.Println(err)
} else if !response.Status.OK() {
	// the data was submitted to ChatBase, but
	// the response contained an error code
	fmt.Println(response.Reason)
}
Events API

The Events API allows handling of Event and Events types.

Event
event := client.Event("USER-ID", "intent-name")
event.SetPlatform("line").SetVersion("2.2.1")
event.AddProperty("success", true)
if err != nil {
	// an error submitting the data occurred
	fmt.Println(err)
} else if !response.Status.OK() {
	// the data was submitted to ChatBase, but
	// the response contained an error code
	fmt.Println(response.Reason)
}
Events
events := chatbase.Events{}
for i := 0; i < 99; i ++ {
	event := client.Event("USER-ID", "counting-intent")
	event.AddProperty("is-even", i%2 == 0)
	events.Append(event)
}
if err := events.Submit(); err != nil {
	// handle error
}

The link tracking allows handling of Link types.

link := client.Link("https://golang.org/", chatbase.PlatformLine)
trackableHREF, err := link.Encode()
response, err := link.Submit()
if err != nil {
	// an error submitting the data occurred
	fmt.Println(err)
} else if !response.Status.OK() {
	// the data was submitted to ChatBase, but
	// the response contained an error code
	fmt.Println(response.Reason)
}
License

MIT © Frederik Ring

Documentation

Overview

Package chatbase provides a client and types for interacting with the Chatbase bot analytics platform - https://chatbase.com

The primary entrypoint for interacting with Chatbase is a `Client` instance:

// a client is a wrapper around an chatbase API key
client := chatbase.New("MY_CHATBASE_API_KEY")

// calling Message requires passing of all required values
message := client.Message(chatbase.MessageTypeAgent, "USER-ID", chatbase.PlatformTelegram)

// optional values are added after creation
message.SetMessage("I didn't understand that, sorry")

// this can also be chained
message.SetIntent("fallback").SetNotHandled(true)

// calling Submit will send the data to chatbase
response, err := message.Submit()
if err != nil {
	// an error submitting the data occurred
	fmt.Println(err)
} else if !response.Status.OK() {
	// the data was submitted to ChatBase, but
	// the response contained an error code
	fmt.Println(response.Reason)
}

For further usage instructions refer to the README.

Index

Constants

View Source
const (
	PlatformFacebook = "Facebook"
	PlatformSMS      = "SMS"
	PlatformWeb      = "Web"
	PlatformAndroid  = "Android"
	PlatformIOS      = "iOS"
	PlatformActions  = "Actions"
	PlatformAlexa    = "Alexa"
	PlatformCortana  = "Cortana"
	PlatformKik      = "Kik"
	PlatformSkype    = "Skype"
	PlatformTwitter  = "Twitter"
	PlatformViber    = "Viber"
	PlatformTelegram = "Telegram"
	PlatformSlack    = "Slack"
	PlatformWhatsApp = "WhatsApp"
	PlatformWeChat   = "WeChat"
	PlatformLine     = "Line"
	PlatformKakao    = "Kakao"
)

A set of strings that can be used for specifying a message's platform. These platforms will be recognized by Chatbase, but any other non-zero custom string value like "Workplace" can be used as well

Variables

View Source
var TimeStamp = func() int64 {
	return time.Now().UnixNano() / 1e6
}

TimeStamp returns the current time in UNIX milliseconds

Functions

func SetAPITimeout

func SetAPITimeout(t time.Duration)

SetAPITimeout allows setting a timeout value for the http.Client that is being used for handling Chatbase API calls

func SetAPITransport

func SetAPITransport(t http.RoundTripper)

SetAPITransport allows setting a transport for the http.Client that is being used for handling Chatbase API calls

Types

type Client

type Client string

Client wraps a Chatbase API Key and can be used to generate messages, events and link

func New

func New(apiKey string) *Client

New returns a new Client using the given Chatbase API Key

func (*Client) AgentMessage

func (c *Client) AgentMessage(userID, platform string) *Message

AgentMessage is a convenience method for creating an agent created message

func (*Client) Event

func (c *Client) Event(userID, intent string) *Event

Event creates a new Event using the client's API Key

func (*Client) FacebookMessage

func (c *Client) FacebookMessage(payload interface{}) *FacebookMessage

FacebookMessage creates a new native Facebook message

func (*Client) FacebookRequestResponse

func (c *Client) FacebookRequestResponse(request, response interface{}) *FacebookRequestResponse

FacebookRequestResponse creates a new wrapper around a request and response

func (c *Client) Link(url, platform string) *Link

Link returns a trackable link to the given URL

func (*Client) Message

func (c *Client) Message(typ MessageType, userID, platform string) *Message

Message returns a new Message using the client's key and the current time as its "TimeStamp" value

func (*Client) String

func (c *Client) String() string

func (*Client) Update

func (c *Client) Update(messageID string) *Update

Update creates a new Update using the client's API key

func (*Client) UserMessage

func (c *Client) UserMessage(userID, platform string) *Message

UserMessage is a convenience method for creating a user created message

type Event

type Event struct {
	APIKey     string          `json:"api_key"`
	UserID     string          `json:"user_id"`
	Intent     string          `json:"intent"`
	TimeStamp  int64           `json:"timestamp_millis,omitempty"`
	Platform   string          `json:"platform,omitempty"`
	Version    string          `json:"version,omitempty"`
	Properties []EventProperty `json:"properties"`
}

Event contains data about an event

func (*Event) AddProperty

func (e *Event) AddProperty(name string, v interface{}) error

AddProperty adds a new property to the event using the given name and value. The passed value needs to be one of `int`, `string`, `bool` or `float64`

func (*Event) SetPlatform

func (e *Event) SetPlatform(p string) *Event

SetPlatform adds an optional "platform" value to the event

func (*Event) SetTimeStamp

func (e *Event) SetTimeStamp(t int64) *Event

SetTimeStamp adds an optional "timestamp" value to the event

func (*Event) SetVersion

func (e *Event) SetVersion(v string) *Event

SetVersion adds an optional "version" value to the event

func (*Event) Submit

func (e *Event) Submit() error

Submit tries to deliver the event to Chatbase

func (*Event) SubmitWithContext

func (e *Event) SubmitWithContext(ctx context.Context) error

SubmitWithContext tries to deliver the event to Chatbase while considering the given context's deadline

type EventProperty

type EventProperty struct {
	Name         string  `json:"property_name"`
	StringValue  string  `json:"string_value,omitempty"`
	IntegerValue int     `json:"integer_value,omitempty"`
	FloatValue   float64 `json:"float_value,omitempty"`
	BoolValue    bool    `json:"bool_value,omitempty"`
}

EventProperty is a property that is attached to an event

func NewEventProperty

func NewEventProperty(name string, value interface{}) (EventProperty, error)

NewEventProperty generates an EventProperty containing the correctly typed field for the passed value. The passed value needs to be one of `int`, `string`, `bool` or `float64`

type Events

type Events []Event

Events is a collection of Event

func (*Events) Append

func (e *Events) Append(addition ...*Event) *Events

Append adds events to the the collection. The collection should not contain events using different API keys

func (Events) MarshalJSON

func (e Events) MarshalJSON() ([]byte, error)

MarshalJSON ensure the collection is correctly wrapped into an object and added the api_key value

func (*Events) Submit

func (e *Events) Submit() error

Submit tries to deliver the set of events to Chatbase

func (*Events) SubmitWithContext

func (e *Events) SubmitWithContext(ctx context.Context) error

SubmitWithContext tries to deliver the set of events to Chatbase while considering the context's deadline

type FacebookFields

type FacebookFields struct {
	Intent     string `json:"intent"`
	NotHandled bool   `json:"not_handled"`
	Feedback   bool   `json:"feedback,omitempty"`
	Version    string `json:"version,omitempty"`
}

FacebookFields contains metadata about a native Facebook message

type FacebookMessage

type FacebookMessage struct {
	Fields  *FacebookFields
	Payload interface{}
	APIKey  string
}

FacebookMessage is a single native Facebook message

func (FacebookMessage) MarshalJSON

func (f FacebookMessage) MarshalJSON() ([]byte, error)

MarshalJSON ensures the message is merged with the metadata in the way that Chatbase expects it to be

func (*FacebookMessage) SetFeedback

func (f *FacebookMessage) SetFeedback(n bool) *FacebookMessage

SetFeedback adds an optional "feedback" value to the message

func (*FacebookMessage) SetIntent

func (f *FacebookMessage) SetIntent(i string) *FacebookMessage

SetIntent adds an optional "intent" value to the message

func (*FacebookMessage) SetNotHandled

func (f *FacebookMessage) SetNotHandled(n bool) *FacebookMessage

SetNotHandled adds an optional "not handled" value to the message

func (*FacebookMessage) SetVersion

func (f *FacebookMessage) SetVersion(v string) *FacebookMessage

SetVersion adds an optional "version" value to the message

func (*FacebookMessage) Submit

func (f *FacebookMessage) Submit() (*MessageResponse, error)

Submit tries to deliver a single Facebook message to chatbase

func (*FacebookMessage) SubmitWithContext

func (f *FacebookMessage) SubmitWithContext(ctx context.Context) (*MessageResponse, error)

SubmitWithContext tries to deliver a single Facebook message to chatbase considering the given context's deadline

type FacebookMessages

type FacebookMessages []FacebookMessage

FacebookMessages is a collection of FacecbookMessage

func (*FacebookMessages) Append

func (f *FacebookMessages) Append(addition ...*FacebookMessage) *FacebookMessages

Append adds additional messages to the collection. The collection should not contain messages using different API keys

func (FacebookMessages) MarshalJSON

func (f FacebookMessages) MarshalJSON() ([]byte, error)

MarshalJSON ensures the messages are wrapped in a top-level object before being serialized into the payload

func (*FacebookMessages) Submit

func (f *FacebookMessages) Submit() (*MessagesResponse, error)

Submit tries to deliver the set of messages to Chatbase. The collection cannot contain messages using different API keys

func (*FacebookMessages) SubmitWithContext

func (f *FacebookMessages) SubmitWithContext(ctx context.Context) (*MessagesResponse, error)

SubmitWithContext tries to deliver a single Facebook message to chatbase considering the given context's deadline

type FacebookRequestResponse

type FacebookRequestResponse struct {
	APIKey   string          `json:"-"`
	Request  interface{}     `json:"request_body"`
	Response interface{}     `json:"response_body"`
	Fields   *FacebookFields `json:"chatbase_fields"`
}

FacebookRequestResponse is a payload that contains both request and response data

func (*FacebookRequestResponse) SetFeedback

SetFeedback adds an optional "feedback" value to the pair

func (*FacebookRequestResponse) SetIntent

SetIntent adds an optional "intent" value to the pair

func (*FacebookRequestResponse) SetNotHandled

SetNotHandled adds an optional "not handled" value to the pair

func (*FacebookRequestResponse) SetVersion

SetVersion adds an optional "version" value to the pair

func (*FacebookRequestResponse) Submit

Submit tries to deliver the pair to Chatbase

func (*FacebookRequestResponse) SubmitWithContext

func (f *FacebookRequestResponse) SubmitWithContext(ctx context.Context) (*MessageResponse, error)

SubmitWithContext tries to deliver the pair to Chatbase considering the given context's deadline

type FacebookRequestResponses

type FacebookRequestResponses []FacebookRequestResponse

FacebookRequestResponses is a collection of FacebookRequestResponse

func (*FacebookRequestResponses) Append

Append adds additional messages to the collection. The collection should not contain messages using different API keys

func (FacebookRequestResponses) MarshalJSON

func (f FacebookRequestResponses) MarshalJSON() ([]byte, error)

MarshalJSON ensures the messages are wrapped in a top-level object before being serialized into the payload

func (*FacebookRequestResponses) Submit

Submit tries to send the collection of request/response pairs to Chatbase. The collection should not contain messages using different API keys

func (*FacebookRequestResponses) SubmitWithContext

func (f *FacebookRequestResponses) SubmitWithContext(ctx context.Context) (*MessagesResponse, error)

SubmitWithContext tries to send the collection of request/response pairs to Chatbase considering the given context's deadline

type Link struct {
	APIKey   string `json:"api_key"`
	URL      string `json:"url"`
	Platform string `json:"platform"`
	Version  string `json:"version,omitempty"`
}

Link describes a hyperlink to be tracked using Chatbase

func (*Link) Encode

func (l *Link) Encode() (string, error)

Encode turns the link object into a URL

func (*Link) SetVersion

func (l *Link) SetVersion(v string) *Link

SetVersion adds an optional "version" parameter to a link

func (*Link) Submit

func (l *Link) Submit() (*LinkResponse, error)

Submit tries to send the link to Chatbase

func (*Link) SubmitWithContext

func (l *Link) SubmitWithContext(ctx context.Context) (*LinkResponse, error)

SubmitWithContext tries to send the link to Chatbase while considering the given context's deadline

type LinkResponse

type LinkResponse struct {
	Status Status `json:"status"`
	Reason string `json:"reason,omitempty"`
}

LinkResponse contains the response to submitting a link

type Message

type Message struct {
	APIKey     string      `json:"api_key"`
	Type       MessageType `json:"type"`
	UserID     string      `json:"user_id"`
	TimeStamp  int64       `json:"time_stamp"`
	Platform   string      `json:"platform"`
	Message    string      `json:"message,omitempty"`
	Intent     string      `json:"intent,omitempty"`
	NotHandled bool        `json:"not_handled,omitempty"`
	Feedback   bool        `json:"feedback,omitempty"`
	Version    string      `json:"version,omitempty"`
}

Message contains data about a generic chat message

func (*Message) SetFeedback

func (m *Message) SetFeedback(f bool) *Message

SetFeedback adds an optional "feedback" value to a message

func (*Message) SetIntent

func (m *Message) SetIntent(i string) *Message

SetIntent adds an optional "intent" value to a message

func (*Message) SetMessage

func (m *Message) SetMessage(msg string) *Message

SetMessage adds an optional "message" value to a message

func (*Message) SetNotHandled

func (m *Message) SetNotHandled(n bool) *Message

SetNotHandled adds an optional "not handled" value to a message

func (*Message) SetTimeStamp

func (m *Message) SetTimeStamp(t int64) *Message

SetTimeStamp overrides the message's "timestamp" value

func (*Message) SetVersion

func (m *Message) SetVersion(v string) *Message

SetVersion adds an optional "version" value to a message

func (*Message) Submit

func (m *Message) Submit() (*MessageResponse, error)

Submit tries to deliver the message to Chatbase

func (*Message) SubmitWithContext

func (m *Message) SubmitWithContext(ctx context.Context) (*MessageResponse, error)

SubmitWithContext tries to deliver the message to Chatbase while considering the given context's deadline

type MessageID

type MessageID string

MessageID is a named string type that normalizes the IDs sent by Chatbase

func (*MessageID) Int64

func (m *MessageID) Int64() (int64, error)

Int64 returns the ID's int64 representation

func (*MessageID) String

func (m *MessageID) String() string

func (*MessageID) UnmarshalJSON

func (m *MessageID) UnmarshalJSON(b []byte) error

UnmarshalJSON distinguishes ints and strings and normalizes both values into a string representation

type MessageResponse

type MessageResponse struct {
	MessageID MessageID `json:"message_id"`
	Status    Status    `json:"status"`
	Reason    string    `json:"reason,omitempty"`
}

MessageResponse describes a Chatbase response to the submission of a single message. It is also used to represent the result of an item of a collection of messages that have been submitted.

type MessageType

type MessageType string

MessageType describes the source of a message

const (
	UserType  MessageType = "user"
	AgentType MessageType = "agent"
)

Types of messages used to identify the origin of a message in Chatbase

type Messages

type Messages []Message

Messages is a collection of Message

func (*Messages) Append

func (m *Messages) Append(addition ...*Message) *Messages

Append adds messages to the the collection

func (Messages) MarshalJSON

func (m Messages) MarshalJSON() ([]byte, error)

MarshalJSON ensures the list of messages is wrapped in a top-level object before being serialized into JSON

func (*Messages) Submit

func (m *Messages) Submit() (*MessagesResponse, error)

Submit tries to deliver the set of messages to Chatbase

func (*Messages) SubmitWithContext

func (m *Messages) SubmitWithContext(ctx context.Context) (*MessagesResponse, error)

SubmitWithContext tries to deliver the set of messages to Chatbase while considering the given context's deadline

type MessagesResponse

type MessagesResponse struct {
	AllSucceeded bool              `json:"all_succeeded"`
	Status       Status            `json:"status"`
	Responses    []MessageResponse `json:"responses"`
	Reason       string            `json:"reason,omitempty"`
}

MessagesResponse describes a Chatbase response to submitting a set of messages

type Status

type Status bool

Status describes the success of an operation

func (*Status) OK

func (s *Status) OK() bool

OK returns the boolean representation of Status

func (*Status) UnmarshalJSON

func (s *Status) UnmarshalJSON(b []byte) error

UnmarshalJSON normalizes the int and string values that are being used by Chatbase to represent success or failure. Int values will map to HTTP status codes (200 or 400), otherwise "success" is considered true where "failure" is considered false

type Update

type Update struct {
	APIKey     string    `json:"-"`
	MessageID  MessageID `json:"-"`
	Intent     string    `json:"intent,omitempty"`
	NotHandled string    `json:"not_handled,omitempty"`
	Feedback   string    `json:"feedback,omitempty"`
	Version    string    `json:"version,omitempty"`
}

Update contains data about an existing message that should be updated

func (*Update) SetFeedback

func (u *Update) SetFeedback(f string) *Update

SetFeedback adds an optional "feedback" value to an update

func (*Update) SetIntent

func (u *Update) SetIntent(i string) *Update

SetIntent adds an optional "intent" value to an update

func (*Update) SetNotHandled

func (u *Update) SetNotHandled(n bool) *Update

SetNotHandled adds an optional "not handled" value to an update

func (*Update) SetVersion

func (u *Update) SetVersion(v string) *Update

SetVersion adds an optional "version" value to an update

func (*Update) Submit

func (u *Update) Submit() (*UpdateResponse, error)

Submit tries to deliver the update to Chatbase

func (*Update) SubmitWithContext

func (u *Update) SubmitWithContext(ctx context.Context) (*UpdateResponse, error)

SubmitWithContext tries to deliver the update to Chatbase while considering the given context's deadline

type UpdateResponse

type UpdateResponse struct {
	Error   []string `json:"error"`
	Updated []string `json:"updated"`
	Status  Status   `json:"status"`
	Reason  string   `json:"string,omitempty"`
}

UpdateResponse describes a Chatbase response to an update submission

Jump to

Keyboard shortcuts

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