v1

package
v1.3.15 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2024 License: MIT Imports: 18 Imported by: 4

Documentation

Overview

Package v1 provides Go API Client implementation for MessageGateway Transport API.

You can use v1.New or v1.NewWithClient to initialize API client. The package github.com/retailcrm/mg-transport-api-client-go/examples contains some examples on how to use this library properly.

Basic usage example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")
getReplyDeadline := func(after time.Duration) *time.Time {
	deadline := time.Now().Add(after)
	return &deadline
}
resp, status, err := client.Messages(SendData{
	Message: Message{
		ExternalID: "uid_1",
		Type:       MsgTypeText,
		Text:       "Hello customer!",
		PageLink:   "https://example.com",
	},
	Originator: OriginatorCustomer,
	Customer: Customer{
		ExternalID: "client_id_1",
		Nickname:   "customer",
		Firstname:  "Tester",
		Lastname:   "Tester",
		Avatar:     "https://example.com/image.png",
		ProfileURL: "https://example.com/user/client_id_1",
		Language:   "en",
		Utm: &Utm{
			Source:   "myspace.com",
			Medium:   "social",
			Campaign: "something",
			Term:     "fedora",
			Content:  "autumn_collection",
		},
	},
	Channel:        305,
	ExternalChatID: "chat_id_1",
	ReplyDeadline:  getReplyDeadline(24 * time.Hour),
})
if err != nil {
	if clientErr := AsClientError(err); clientErr != nil {
		if clientErr.BaseError != nil {
			log.Fatalf("cannot perform the request: %s", clientErr.BaseError)
		}
		if clientErr.ErrorMsg != "" {
			log.Fatalf("MG error: %s", clientErr.ErrorMsg)
		}
	}

	log.Fatalf("general error: %s (%d)", err, status)
}

log.Printf("status: %d, message ID: %d", status, resp.MessageID)

Index

Constants

View Source
const (
	// TemplateItemTypeText is a type for text chunk in template.
	TemplateItemTypeText uint8 = iota
	// TemplateItemTypeVar is a type for variable in template.
	TemplateItemTypeVar
)
View Source
const (
	// TemplateVarCustom is a custom variable type.
	TemplateVarCustom = "custom"
	// TemplateVarName is a name variable type.
	TemplateVarName = "name"
	// TemplateVarFirstName is a first name variable type.
	TemplateVarFirstName = "first_name"
	// TemplateVarLastName is a last name variable type.
	TemplateVarLastName = "last_name"
)
View Source
const (
	// ChannelFeatureNone channel can not implement feature.
	ChannelFeatureNone string = "none"
	// ChannelFeatureReceive channel implement feature on receive.
	ChannelFeatureReceive string = "receive"
	// ChannelFeatureSend channel implement feature on send.
	ChannelFeatureSend string = "send"
	// ChannelFeatureBoth channel implement feature on both directions.
	ChannelFeatureBoth string = "both"
	// ChannelFeatureAny channel implement feature on any.
	ChannelFeatureAny string = "any"
	// ChannelFeatureSendingPolicyNo channel can not implement feature.
	ChannelFeatureSendingPolicyNo string = "no"
	// ChannelFeatureSendingPolicyTemplate channel can implement template.
	ChannelFeatureSendingPolicyTemplate string = "template"
	// ChannelFeatureCustomerExternalIDPhone customer externalId is phone.
	ChannelFeatureCustomerExternalIDPhone string = "phone"

	// MsgTypeText text message.
	MsgTypeText string = "text"
	// MsgTypeSystem system message.
	MsgTypeSystem string = "system"
	// MsgTypeCommand command (for bots).
	MsgTypeCommand string = "command"
	// MsgTypeOrder order card.
	MsgTypeOrder string = "order"
	// MsgTypeProduct product card.
	MsgTypeProduct string = "product"
	// MsgTypeFile file card.
	MsgTypeFile string = "file"
	// MsgTypeImage image card.
	MsgTypeImage string = "image"
	// MsgTypeAudio audio.
	MsgTypeAudio string = "audio"

	// MsgOrderStatusCodeNew order status group new.
	MsgOrderStatusCodeNew = "new"
	// MsgOrderStatusCodeApproval order status group approval.
	MsgOrderStatusCodeApproval = "approval"
	// MsgOrderStatusCodeAssembling order status group assembling.
	MsgOrderStatusCodeAssembling = "assembling"
	// MsgOrderStatusCodeDelivery order status group delivery.
	MsgOrderStatusCodeDelivery = "delivery"
	// MsgOrderStatusCodeComplete order status group complete.
	MsgOrderStatusCodeComplete = "complete"
	// MsgOrderStatusCodeCancel order status group cancel.
	MsgOrderStatusCodeCancel = "cancel"

	FileSizeLimit = 20 * 1024 * 1024
)

noinspection ALL.

View Source
const LimitResponse = 25 * MB
View Source
const MB = 1 << 20
View Source
const MaxRPS = 100

Variables

View Source
var ErrInvalidOriginator = errors.New("invalid originator")
View Source
var ErrUnknownTypeValue = errors.New("unknown TemplateType")
View Source
var TypeMap = [][]byte{
	TemplateTypeText:  []byte("text"),
	TemplateTypeMedia: []byte("media"),
}

Functions

func BoolPtr added in v1.2.2

func BoolPtr(v bool) *bool

BoolPtr returns provided boolean as pointer. Can be used while editing the integration module activity.

func MakeTimestamp added in v1.1.1

func MakeTimestamp() int64

MakeTimestamp returns current unix timestamp in milliseconds.

Example:

fmt.Printf("UNIX timestamp in milliseconds: %d", MakeTimestamp())

func NewAPIClientError added in v1.2.0

func NewAPIClientError(responseBody []byte) error

NewAPIClientError wraps MG error.

func NewCriticalHTTPError added in v1.2.0

func NewCriticalHTTPError(err error) error

NewCriticalHTTPError wraps *http.Client error.

func NewServerError added in v1.2.0

func NewServerError(response *http.Response) error

NewServerError wraps an unexpected API error (e.g. 5xx).

func OriginatorMarshalJSONInvalid added in v1.1.35

func OriginatorMarshalJSONInvalid(t *testing.T)

func TimePtr added in v1.2.2

func TimePtr(v time.Time) *time.Time

TimePtr returns provided time.Time's pointer.

Types

type AckMessageRequest added in v1.1.41

type AckMessageRequest struct {
	ExternalMessageID  string            `json:"external_message_id"`
	TransportMessageID string            `json:"transport_message_id,omitempty"`
	Channel            uint64            `json:"channel"`
	Error              *MessageSentError `json:"error,omitempty"`
}

AckMessageRequest type.

type ActivateResponse

type ActivateResponse struct {
	ChannelID   uint64    `json:"id"`
	ExternalID  string    `json:"external_id"`
	ActivatedAt time.Time `json:"activated_at"`
}

ActivateResponse channel activation response.

type ActivateTemplateRequest added in v1.1.35

type ActivateTemplateRequest struct {
	UpdateTemplateRequest

	Code string       `json:"code"`
	Type TemplateType `json:"type"`
}

type Attachments added in v1.1.40

type Attachments struct {
	Suggestions []Suggestion `json:"suggestions,omitempty"`
}

type BasicLogger added in v1.1.45

type BasicLogger interface {
	Printf(string, ...interface{})
}

BasicLogger provides basic functionality for logging.

func DebugLoggerAdapter added in v1.1.45

func DebugLoggerAdapter(logger DebugLogger) BasicLogger

DebugLoggerAdapter returns BasicLogger that calls underlying DebugLogger.Debugf.

type Button added in v1.3.5

type Button interface {
	ButtonType() ButtonType
}

type ButtonParam added in v1.2.7

type ButtonParam struct {
	ButtonType   ButtonType `json:"type"`
	Text         string     `json:"text,omitempty"`
	URLParameter string     `json:"urlParameter,omitempty"`
}

type ButtonType added in v1.2.7

type ButtonType string
const (
	ButtonTypePlain ButtonType = "plain"
	ButtonTypePhone ButtonType = "phone"
	ButtonTypeURL   ButtonType = "url"
)

type Channel

type Channel struct {
	ID         uint64          `json:"id,omitempty"`
	ExternalID string          `json:"external_id,omitempty"`
	Type       string          `json:"type,omitempty"`
	Name       string          `json:"name,omitempty"`
	AvatarUrl  string          `json:"avatar_url,omitempty"`
	Settings   ChannelSettings `json:"settings,omitempty"`
}

Channel type.

type ChannelListItem added in v1.1.12

type ChannelListItem struct {
	ID            uint64          `json:"id"`
	ExternalID    string          `json:"external_id"`
	Type          string          `json:"type"`
	Name          *string         `json:"name"`
	Settings      ChannelSettings `json:"settings"`
	CreatedAt     string          `json:"created_at"`
	UpdatedAt     *string         `json:"updated_at"`
	ActivatedAt   string          `json:"activated_at"`
	DeactivatedAt *string         `json:"deactivated_at"`
	IsActive      bool            `json:"is_active"`
}

ChannelListItem response struct.

type ChannelSettings added in v1.1.1

type ChannelSettings struct {
	Status             Status                     `json:"status"`
	Text               ChannelSettingsText        `json:"text"`
	Product            Product                    `json:"product"`
	Order              Order                      `json:"order"`
	File               ChannelSettingsFilesBase   `json:"file"`
	Image              ChannelSettingsFilesBase   `json:"image"`
	CustomerExternalID string                     `json:"customer_external_id,omitempty"`
	SendingPolicy      SendingPolicy              `json:"sending_policy,omitempty"`
	Suggestions        ChannelSettingsSuggestions `json:"suggestions,omitempty"`
	Audio              ChannelSettingsAudio       `json:"audio"`
	Template           ChannelSettingsTemplate    `json:"template"`
	WhatsApp           *WhatsAppChannelProperties `json:"whatsapp,omitempty"` // for WhatsApp channels only.
}

ChannelSettings struct.

type ChannelSettingsAudio added in v1.1.47

type ChannelSettingsAudio struct {
	Creating      string  `json:"creating,omitempty"`
	Quoting       string  `json:"quoting,omitempty"`
	Deleting      string  `json:"deleting,omitempty"`
	MaxItemsCount uint64  `json:"max_items_count,omitempty"`
	MaxItemSize   *uint64 `json:"max_item_size,omitempty"`
}

ChannelSettingsAudio struct.

type ChannelSettingsFilesBase added in v1.1.15

type ChannelSettingsFilesBase struct {
	Creating          string  `json:"creating,omitempty"`
	Editing           string  `json:"editing,omitempty"`
	Quoting           string  `json:"quoting,omitempty"`
	Deleting          string  `json:"deleting,omitempty"`
	Max               uint64  `json:"max_items_count,omitempty"`
	NoteMaxCharsCount *uint16 `json:"note_max_chars_count,omitempty"`
	MaxItemSize       *uint64 `json:"max_item_size,omitempty"`
}

ChannelSettingsFilesBase struct.

type ChannelSettingsSuggestions added in v1.1.40

type ChannelSettingsSuggestions struct {
	Text  string `json:"text,omitempty"`
	Phone string `json:"phone,omitempty"`
	Email string `json:"email,omitempty"`
	URL   string `json:"url,omitempty"`
}

type ChannelSettingsTemplate added in v1.3.2

type ChannelSettingsTemplate struct {
	Creation bool `json:"creation,omitempty"`
}

type ChannelSettingsText added in v1.1.2

type ChannelSettingsText struct {
	Creating      string `json:"creating,omitempty"`
	Editing       string `json:"editing,omitempty"`
	Quoting       string `json:"quoting,omitempty"`
	Deleting      string `json:"deleting,omitempty"`
	MaxCharsCount uint16 `json:"max_chars_count,omitempty"`
}

ChannelSettingsText struct.

type Channels added in v1.1.12

type Channels struct {
	ID          int       `url:"id,omitempty" json:"id,omitempty"`
	Types       []string  `url:"types,omitempty" json:"types,omitempty"`
	Active      bool      `url:"active,omitempty" json:"active,omitempty"`
	Since       time.Time `url:"since,omitempty" json:"since,omitempty"`
	Until       time.Time `url:"until,omitempty" json:"until,omitempty"`
	TransportID uint64    `url:"transport_id,omitempty" json:"transport_id,omitempty"`
	Sort        string    `url:"sort,omitempty" json:"sort,omitempty"`
	Limit       int       `url:"limit,omitempty" json:"limit,omitempty"`
}

Channels request type.

type Customer added in v1.1.28

type Customer struct {
	ExternalID string `json:"external_id"`
	Nickname   string `json:"nickname"`
	Firstname  string `json:"first_name,omitempty"`
	Lastname   string `json:"last_name,omitempty"`
	Avatar     string `json:"avatar,omitempty"`
	ProfileURL string `json:"profile_url,omitempty"`
	Country    string `json:"country,omitempty"`
	Language   string `json:"language,omitempty"`
	Phone      string `json:"phone,omitempty"`
	Email      string `json:"email,omitempty"`
	Utm        *Utm   `json:"utm,omitempty"`
}

Customer struct.

type DebugLogger added in v1.1.45

type DebugLogger interface {
	Debugf(string, ...interface{})
}

DebugLogger can be used to easily wrap any logger with Debugf method into the BasicLogger instance.

type DeleteData added in v1.0.1

type DeleteData struct {
	Message Message `json:"message"`
	Channel uint64  `json:"channel"`
}

DeleteData struct.

type DeleteResponse

type DeleteResponse struct {
	ChannelID     uint64    `json:"id"`
	DeactivatedAt time.Time `json:"deactivated_at"`
}

DeleteResponse channel deactivation response.

type EditMessageRequest added in v1.1.13

type EditMessageRequest struct {
	Message EditMessageRequestMessage `json:"message"`
	Channel uint64                    `json:"channel"`
}

EditMessageRequest type.

type EditMessageRequestMessage added in v1.1.13

type EditMessageRequestMessage struct {
	ExternalID string `json:"external_id"`
	Text       string `json:"text"`
	EditedAt   int64  `json:"edited_at"`
	PageLink   string `json:"page_link,omitempty"`
}

EditMessageRequestMessage type.

type ErrorType added in v1.1.41

type ErrorType string
const (
	GeneralError           ErrorType = "general"
	CustomerNotExistsError ErrorType = "customer_not_exists"
	ReplyTimedOutError     ErrorType = "reply_timed_out"
	SpamSuspicionError     ErrorType = "spam_suspicion"
	AccessRestrictedError  ErrorType = "access_restricted"
)

type FileItem added in v1.1.15

type FileItem struct {
	ID      string `json:"id"`
	Size    int    `json:"size"`
	Caption string `json:"caption"`
	Height  *int   `json:"height,omitempty"`
	Width   *int   `json:"width,omitempty"`
}

FileItem struct.

type FileMeta added in v1.1.15

type FileMeta struct {
	Width  *int `json:"width,omitempty"`
	Height *int `json:"height,omitempty"`
}

FileMeta file metadata.

type FullFileResponse added in v1.1.15

type FullFileResponse struct {
	ID       string `json:"id,omitempty"`
	Type     string `json:"type,omitempty"`
	Size     int    `json:"size,omitempty"`
	Url      string `json:"url,omitempty"` //nolint:golint
	MimeType string `json:"mime_type,omitempty"`
}

FullFileResponse uploaded file data.

type HTTPClientError added in v1.2.0

type HTTPClientError struct {
	ErrorMsg  string
	BaseError error
	Response  io.Reader
}

HTTPClientError is a common error type used in the client.

func AsClientError added in v1.3.9

func AsClientError(err error) *HTTPClientError

func (*HTTPClientError) Error added in v1.2.0

func (err *HTTPClientError) Error() string

Error message will contain either an error from MG or underlying error message.

func (*HTTPClientError) Unwrap added in v1.2.0

func (err *HTTPClientError) Unwrap() error

Unwrap returns underlying error. Its presence usually indicates a problem with the network.

type HeaderContent added in v1.3.5

type HeaderContent interface {
	HeaderContentType() HeaderContentType
}

type HeaderContentDocument added in v1.3.5

type HeaderContentDocument struct{}

func (HeaderContentDocument) HeaderContentType added in v1.3.5

func (HeaderContentDocument) HeaderContentType() HeaderContentType

type HeaderContentImage added in v1.3.5

type HeaderContentImage struct{}

func (HeaderContentImage) HeaderContentType added in v1.3.5

func (HeaderContentImage) HeaderContentType() HeaderContentType

type HeaderContentText added in v1.3.5

type HeaderContentText struct {
	Body string `json:"body"`
}

func (HeaderContentText) HeaderContentType added in v1.3.5

func (HeaderContentText) HeaderContentType() HeaderContentType

type HeaderContentType added in v1.3.5

type HeaderContentType string
const (
	HeaderContentTypeText     HeaderContentType = "text"
	HeaderContentTypeDocument HeaderContentType = "document"
	HeaderContentTypeImage    HeaderContentType = "image"
	HeaderContentTypeVideo    HeaderContentType = "video"
)

type HeaderContentVideo added in v1.3.5

type HeaderContentVideo struct{}

func (HeaderContentVideo) HeaderContentType added in v1.3.5

func (HeaderContentVideo) HeaderContentType() HeaderContentType

type HeaderParams added in v1.2.7

type HeaderParams struct {
	TextVars    []string `json:"textVars,omitempty"`
	ImageURL    string   `json:"imageUrl,omitempty"`
	VideoURL    string   `json:"videoUrl,omitempty"`
	DocumentURL string   `json:"documentUrl,omitempty"`
}

type Item added in v1.1.15

type Item struct {
	ID      string `json:"id"`
	Caption string `json:"caption"`
}

Item struct.

type Limiter added in v1.3.15

type Limiter interface {
	// Obtain the right to send a request. Should lock the execution if current goroutine needs to wait.
	Obtain(string)
}

Limiter implements some form of rate limiting.

var NoopLimiter Limiter = &noopLimiter{}

NoopLimiter implements Limiter but doesn't limit anything.

func NewTokensBucket added in v1.3.12

func NewTokensBucket(maxRPS uint32, unusedTokenTime, checkTokenTime time.Duration) Limiter

NewTokensBucket constructs TokensBucket with provided parameters.

type MGErrors added in v1.2.0

type MGErrors struct {
	Errors []string
}

MGErrors contains a list of errors as sent by MessageGateway.

type MarkMessageReadRequest added in v1.1.13

type MarkMessageReadRequest struct {
	Message   MarkMessageReadRequestMessage `json:"message"`
	ChannelID uint64                        `json:"channel_id"`
}

MarkMessageReadRequest type.

type MarkMessageReadRequestMessage added in v1.1.13

type MarkMessageReadRequestMessage struct {
	ExternalID string `json:"external_id"`
}

MarkMessageReadRequestMessage type.

type MarkMessageReadResponse added in v1.1.13

type MarkMessageReadResponse struct{}

MarkMessageReadResponse type.

type MarkMessagesReadUntilRequest added in v1.2.1

type MarkMessagesReadUntilRequest struct {
	CustomerExternalID string    `json:"customer_external_id"`
	ChannelID          uint64    `json:"channel_id"`
	Until              time.Time `json:"until"`
}

MarkMessagesReadUntilRequest type.

type MarkMessagesReadUntilResponse added in v1.2.1

type MarkMessagesReadUntilResponse struct {
	IDs []int64 `json:"ids"`
}

MarkMessagesReadUntilResponse type.

type Message

type Message struct {
	ExternalID string `json:"external_id"`
	Type       string `json:"type,omitempty"`
	Text       string `json:"text,omitempty"`
	Note       string `json:"note,omitempty"`
	Items      []Item `json:"items,omitempty"`
	PageLink   string `json:"page_link,omitempty"`
}

Message struct.

type MessageDataBot added in v1.1.3

type MessageDataBot struct {
	Name   string `json:"name"`
	Avatar string `json:"avatar"`
}

MessageDataBot bot data from webhook.

type MessageDataOrder added in v1.1.6

type MessageDataOrder struct {
	Number   string                    `json:"number"`
	Url      string                    `json:"url,omitempty"`
	Date     string                    `json:"date,omitempty"`
	Cost     *MessageDataOrderCost     `json:"cost,omitempty"`
	Discount *MessageDataOrderCost     `json:"discount,omitempty"`
	Status   *MessageDataOrderStatus   `json:"status,omitempty"`
	Delivery *MessageDataOrderDelivery `json:"delivery"`
	Payments []MessageDataOrderPayment `json:"payments"`
	Items    []MessageDataOrderItem    `json:"items,omitempty"`
}

MessageDataOrder order data from webhook.

type MessageDataOrderCost added in v1.1.6

type MessageDataOrderCost struct {
	Value    float32 `json:"value,omitempty"`
	Currency string  `json:"currency"`
}

MessageDataOrderCost type.

type MessageDataOrderDelivery added in v1.1.10

type MessageDataOrderDelivery struct {
	Name    string                `json:"name"`
	Price   *MessageDataOrderCost `json:"price"`
	Address string                `json:"address"`
	Comment string                `json:"comment,omitempty"`
}

MessageDataOrderDelivery type.

type MessageDataOrderItem added in v1.1.6

type MessageDataOrderItem struct {
	Name     string                    `json:"name,omitempty"`
	Url      string                    `json:"url,omitempty"`
	Img      string                    `json:"img,omitempty"`
	Quantity *MessageDataOrderQuantity `json:"quantity,omitempty"`
	Price    *MessageDataOrderCost     `json:"price,omitempty"`
}

MessageDataOrderItem type.

type MessageDataOrderPayment added in v1.1.10

type MessageDataOrderPayment struct {
	Name   string                         `json:"name"`
	Status *MessageDataOrderPaymentStatus `json:"status"`
	Amount *MessageDataOrderCost          `json:"amount"`
}

MessageDataOrderPayment type.

type MessageDataOrderPaymentStatus added in v1.1.10

type MessageDataOrderPaymentStatus struct {
	Name string `json:"name"`
	Paid bool   `json:"paid"`
}

MessageDataOrderPaymentStatus type.

type MessageDataOrderQuantity added in v1.1.6

type MessageDataOrderQuantity struct {
	Value float32 `json:"value"`
	Unit  string  `json:"unit"`
}

MessageDataOrderQuantity type.

type MessageDataOrderStatus added in v1.1.6

type MessageDataOrderStatus struct {
	Code string `json:"code,omitempty"`
	Name string `json:"name,omitempty"`
}

MessageDataOrderStatus type.

type MessageDataProduct added in v1.1.6

type MessageDataProduct struct {
	ID      uint64                `json:"id"`
	Name    string                `json:"name"`
	Article string                `json:"article,omitempty"`
	Url     string                `json:"url,omitempty"`
	Img     string                `json:"img,omitempty"`
	Cost    *MessageDataOrderCost `json:"cost,omitempty"`
	Unit    string                `json:"unit,omitempty"`
	// Deprecated: now you need to use Unit instead of this field
	Quantity *MessageDataOrderQuantity `json:"quantity,omitempty"`
}

MessageDataProduct product data from webhook.

type MessageDataUser added in v1.1.3

type MessageDataUser struct {
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	Avatar    string `json:"avatar"`
}

MessageDataUser user data from webhook.

type MessageSentError added in v1.1.41

type MessageSentError struct {
	Code    ErrorType `json:"code"`
	Message string    `json:"message"`
}

MessageSentError type.

type MessageWebhookData added in v1.3.0

type MessageWebhookData struct {
	ExternalUserID    string              `json:"external_user_id"`
	ExternalMessageID string              `json:"external_message_id,omitempty"`
	ExternalChatID    string              `json:"external_chat_id"`
	ChannelID         uint64              `json:"channel_id"`
	Content           string              `json:"content"`
	QuoteExternalID   string              `json:"quote_external_id,omitempty"`
	QuoteContent      string              `json:"quote_content,omitempty"`
	Type              string              `json:"type"`
	User              *MessageDataUser    `json:"user,omitempty"`
	Bot               *MessageDataBot     `json:"bot,omitempty"`
	Product           *MessageDataProduct `json:"product,omitempty"`
	Order             *MessageDataOrder   `json:"order,omitempty"`
	Items             *[]FileItem         `json:"items,omitempty"`
	Template          *TemplateInfo       `json:"template,omitempty"`
	Attachments       *Attachments        `json:"attachments,omitempty"`
	InAppID           int32               `json:"in_app_id,omitempty"`
}

MessageWebhookData request data.

type MessagesResponse

type MessagesResponse struct {
	MessageID int       `json:"message_id,omitempty"`
	Time      time.Time `json:"time,omitempty"`
	Warnings  []string  `json:"warnings"`
}

MessagesResponse message event response.

type MgClient

type MgClient struct {
	URL   string `json:"url"`
	Token string `json:"token"`
	Debug bool   `json:"debug"`
	// contains filtered or unexported fields
}

MgClient type.

func New

func New(url string, token string) *MgClient

New initializes the MgClient.

func NewWithClient added in v1.1.33

func NewWithClient(url string, token string, client *http.Client) *MgClient

NewWithClient initializes the MgClient with specified *http.Client.

func (*MgClient) AckMessage added in v1.1.41

func (c *MgClient) AckMessage(request AckMessageRequest) (int, error)

AckMessage sets success status for message or appends an error to message.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

status, err := client.AckMessage(AckMessageRequest{
	ExternalMessageID: "message_id_1",
	Channel: 305,
})
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d", status)

func (*MgClient) ActivateTemplate added in v1.1.35

func (c *MgClient) ActivateTemplate(channelID uint64, request ActivateTemplateRequest) (int, error)

ActivateTemplate activates template with provided structure.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

status, err := client.ActivateTemplate(1, ActivateTemplateRequest{
	UpdateTemplateRequest: UpdateTemplateRequest{
		Name:     "New Template",
		Body:     "Hello, {{1}}! Welcome to our store!",
		Lang:     "en",
		Category: "marketing",
		Example: &TemplateExample{
			Header: []string{"https://example.com/image.png"},
			Body:   []string{"John"},
		},
		VerificationStatus: TemplateStatusApproved,
		Header: &TemplateHeader{
			Content: HeaderContentImage{},
		},
	},
	Code: "new_template",
	Type: TemplateTypeMedia,
})
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d", status)

func (*MgClient) ActivateTransportChannel

func (c *MgClient) ActivateTransportChannel(request Channel) (ActivateResponse, int, error)

ActivateTransportChannel activates the channel with provided settings.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")
uint16Ptr := func(val uint16) *uint16 {
	return &val
}
mbToBytes := func(val uint64) *uint64 {
	val = val * 1024 * 1024
	return &val
}

resp, status, err := client.ActivateTransportChannel(Channel{
	Type: "telegram",
	Name: "@my_shopping_bot",
	Settings: ChannelSettings{
		Status: Status{
			Delivered: ChannelFeatureNone,
			Read:      ChannelFeatureReceive,
		},
		Text: ChannelSettingsText{
			Creating:      ChannelFeatureBoth,
			Editing:       ChannelFeatureBoth,
			Quoting:       ChannelFeatureReceive,
			Deleting:      ChannelFeatureSend,
			MaxCharsCount: 2000,
		},
		Product: Product{
			Creating: ChannelFeatureSend,
			Editing:  ChannelFeatureNone,
			Deleting: ChannelFeatureSend,
		},
		Order: Order{
			Creating: ChannelFeatureBoth,
			Editing:  ChannelFeatureNone,
			Deleting: ChannelFeatureSend,
		},
		File: ChannelSettingsFilesBase{
			Creating:          ChannelFeatureBoth,
			Editing:           ChannelFeatureBoth,
			Quoting:           ChannelFeatureBoth,
			Deleting:          ChannelFeatureBoth,
			Max:               10,
			NoteMaxCharsCount: uint16Ptr(256),
			MaxItemSize:       mbToBytes(50),
		},
		Image: ChannelSettingsFilesBase{
			Creating:          ChannelFeatureBoth,
			Editing:           ChannelFeatureBoth,
			Quoting:           ChannelFeatureBoth,
			Deleting:          ChannelFeatureBoth,
			Max:               10,
			NoteMaxCharsCount: uint16Ptr(256),
			MaxItemSize:       mbToBytes(10),
		},
		Suggestions: ChannelSettingsSuggestions{
			Text:  ChannelFeatureBoth,
			Phone: ChannelFeatureBoth,
			Email: ChannelFeatureBoth,
		},
		Audio: ChannelSettingsAudio{
			Creating:    ChannelFeatureBoth,
			Quoting:     ChannelFeatureBoth,
			Deleting:    ChannelFeatureBoth,
			MaxItemSize: mbToBytes(10),
		},
	},
})
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d, channel external_id: %s", status, resp.ExternalID)

func (*MgClient) DeactivateTemplate added in v1.1.35

func (c *MgClient) DeactivateTemplate(channelID uint64, templateCode string) (int, error)

DeactivateTemplate deactivates the template by its code.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

status, err := client.DeactivateTemplate(1, "new_template")
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d", status)

func (*MgClient) DeactivateTransportChannel

func (c *MgClient) DeactivateTransportChannel(id uint64) (DeleteResponse, int, error)

DeactivateTransportChannel deactivates the channel by its ID.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

resp, status, err := client.DeactivateTransportChannel(305)
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d, deactivated at: %s", status, resp.DeactivatedAt)

func (*MgClient) DeleteMessage

func (c *MgClient) DeleteMessage(request DeleteData) (*MessagesResponse, int, error)

DeleteMessage removes the message.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

resp, status, err := client.DeleteMessage(DeleteData{
	Message: Message{
		ExternalID: "message_id_1",
	},
	Channel: 305,
})
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d, message ID: %d", status, resp.MessageID)

func (*MgClient) DeleteRequest

func (c *MgClient) DeleteRequest(url string, parameters []byte) ([]byte, int, error)

DeleteRequest performs DELETE request to the provided route.

func (*MgClient) GetFile added in v1.1.15

func (c *MgClient) GetFile(request string) (FullFileResponse, int, error)

GetFile returns file information by its ID.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

resp, status, err := client.GetFile("file_id")
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d, file URL: %s", status, resp.Url)

func (*MgClient) GetRequest

func (c *MgClient) GetRequest(url string, parameters []byte) ([]byte, int, error)

GetRequest performs GET request to the provided route.

func (*MgClient) MarkMessageRead added in v1.1.13

func (c *MgClient) MarkMessageRead(request MarkMessageReadRequest) (MarkMessageReadResponse, int, error)

MarkMessageRead send message read event to MG.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

_, status, err := client.MarkMessageRead(MarkMessageReadRequest{
	Message: MarkMessageReadRequestMessage{
		ExternalID: "message_id_1",
	},
	ChannelID: 305,
})
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d", status)

func (*MgClient) Messages

func (c *MgClient) Messages(request SendData) (MessagesResponse, int, error)

Messages sends new message.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")
getReplyDeadline := func(after time.Duration) *time.Time {
	deadline := time.Now().Add(after)
	return &deadline
}

resp, status, err := client.Messages(SendData{
	Message: Message{
		ExternalID: "uid_1",
		Type:       MsgTypeText,
		Text:       "Hello customer!",
		PageLink:   "https://example.com",
	},
	Originator: OriginatorCustomer,
	Customer: Customer{
		ExternalID: "client_id_1",
		Nickname:   "customer",
		Firstname:  "Tester",
		Lastname:   "Tester",
		Avatar:     "https://example.com/image.png",
		ProfileURL: "https://example.com/user/client_id_1",
		Language:   "en",
		Utm: &Utm{
			Source:   "myspace.com",
			Medium:   "social",
			Campaign: "something",
			Term:     "fedora",
			Content:  "autumn_collection",
		},
	},
	Channel:        305,
	ExternalChatID: "chat_id_1",
	ReplyDeadline: getReplyDeadline(24 * time.Hour),
})
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d, message ID: %d", status, resp.MessageID)

func (*MgClient) MessagesHistory added in v1.2.2

func (c *MgClient) MessagesHistory(request SendHistoryMessageRequest) (MessagesResponse, int, error)

MessagesHistory sends history message.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")
getModifiedNow := func(after time.Duration) *time.Time {
	deadline := time.Now().Add(after)
	return &deadline
}

resp, status, err := client.MessagesHistory(SendHistoryMessageRequest{
	Message: SendMessageRequestMessage{
		ExternalID: "uid_1",
		Type:       MsgTypeText,
		Text:       "Hello customer!",
		CreatedAt:  getModifiedNow(-time.Hour),
	},
	Originator: OriginatorCustomer,
	Customer: &Customer{
		ExternalID: "client_id_1",
		Nickname:   "customer",
		Firstname:  "Tester",
		Lastname:   "Tester",
		Avatar:     "https://example.com/image.png",
		ProfileURL: "https://example.com/user/client_id_1",
		Language:   "en",
		Utm: &Utm{
			Source:   "myspace.com",
			Medium:   "social",
			Campaign: "something",
			Term:     "fedora",
			Content:  "autumn_collection",
		},
	},
	ChannelID:      305,
	ExternalChatID: "chat_id_1",
	ReplyDeadline:  getModifiedNow(24 * time.Hour),
})
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d, message ID: %d", status, resp.MessageID)

func (*MgClient) PostRequest

func (c *MgClient) PostRequest(url string, parameters io.Reader) ([]byte, int, error)

PostRequest performs POST request to the provided route.

func (*MgClient) PutRequest

func (c *MgClient) PutRequest(url string, parameters []byte) ([]byte, int, error)

PutRequest performs PUT request to the provided route.

func (*MgClient) ReadUntil added in v1.2.1

ReadUntil will mark all messages from specified timestamp as read.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

resp, status, err := client.ReadUntil(MarkMessagesReadUntilRequest{
	CustomerExternalID: "customer_id_1",
	ChannelID: 305,
	Until: time.Now().Add(-time.Hour),
})
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d, marked messages: %+v", status, resp.IDs)

func (*MgClient) TransportChannels added in v1.1.12

func (c *MgClient) TransportChannels(request Channels) ([]ChannelListItem, int, error)

TransportChannels returns channels for current transport.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

resp, status, err := client.TransportChannels(Channels{
	Active: true,
})
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d, channels: %#v", status, resp)

func (*MgClient) TransportTemplates added in v1.1.35

func (c *MgClient) TransportTemplates() ([]Template, int, error)

TransportTemplates returns templates list.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

data, status, err := client.TransportTemplates()
if err != nil {
    log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d, response: %#v", status, data)

func (*MgClient) UpdateMessages

func (c *MgClient) UpdateMessages(request EditMessageRequest) (MessagesResponse, int, error)

UpdateMessages edits existing message. Only text messages are supported.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

resp, status, err := client.UpdateMessages(EditMessageRequest{
	Message: EditMessageRequestMessage{
		ExternalID: "message_id_1",
		Text:       "This is a new text!",
	},
	Channel: 305,
})
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d, message ID: %d", status, resp.MessageID)

func (*MgClient) UpdateTemplate added in v1.1.35

func (c *MgClient) UpdateTemplate(channelID uint64, code string, request UpdateTemplateRequest) (int, error)

UpdateTemplate updates existing template by its code.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

status, err := client.UpdateTemplate(1, "new_template", UpdateTemplateRequest{
	Name:     "New Template",
	Body:     "Hello, {{1}}! Welcome to our store!",
	Lang:     "en",
	Category: "marketing",
	Example: &TemplateExample{
		Header: []string{"https://example.com/image.png"},
		Body:   []string{"John"},
	},
	VerificationStatus: TemplateStatusApproved,
	Header: &TemplateHeader{
		Content: HeaderContentImage{},
	},
})
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d", status)

func (*MgClient) UpdateTransportChannel

func (c *MgClient) UpdateTransportChannel(request Channel) (UpdateResponse, int, error)

UpdateTransportChannel updates an existing channel with provided settings.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")
uint16Ptr := func(val uint16) *uint16 {
	return &val
}
mbToBytes := func(val uint64) *uint64 {
	val = val * 1024 * 1024
	return &val
}

resp, status, err := client.UpdateTransportChannel(Channel{
	ID:   305,
	Type: "telegram",
	Name: "@my_shopping_bot",
	Settings: ChannelSettings{
		Status: Status{
			Delivered: ChannelFeatureNone,
			Read:      ChannelFeatureReceive,
		},
		Text: ChannelSettingsText{
			Creating:      ChannelFeatureBoth,
			Editing:       ChannelFeatureBoth,
			Quoting:       ChannelFeatureReceive,
			Deleting:      ChannelFeatureSend,
			MaxCharsCount: 2000,
		},
		Product: Product{
			Creating: ChannelFeatureSend,
			Editing:  ChannelFeatureNone,
			Deleting: ChannelFeatureSend,
		},
		Order: Order{
			Creating: ChannelFeatureBoth,
			Editing:  ChannelFeatureNone,
			Deleting: ChannelFeatureSend,
		},
		File: ChannelSettingsFilesBase{
			Creating:          ChannelFeatureBoth,
			Editing:           ChannelFeatureBoth,
			Quoting:           ChannelFeatureBoth,
			Deleting:          ChannelFeatureBoth,
			Max:               10,
			NoteMaxCharsCount: uint16Ptr(256),
			MaxItemSize:       mbToBytes(50),
		},
		Image: ChannelSettingsFilesBase{
			Creating:          ChannelFeatureBoth,
			Editing:           ChannelFeatureBoth,
			Quoting:           ChannelFeatureBoth,
			Deleting:          ChannelFeatureBoth,
			Max:               10,
			NoteMaxCharsCount: uint16Ptr(256),
			MaxItemSize:       mbToBytes(10),
		},
		Suggestions: ChannelSettingsSuggestions{
			Text:  ChannelFeatureBoth,
			Phone: ChannelFeatureBoth,
			Email: ChannelFeatureBoth,
		},
		Audio: ChannelSettingsAudio{
			Creating:    ChannelFeatureBoth,
			Quoting:     ChannelFeatureBoth,
			Deleting:    ChannelFeatureBoth,
			MaxItemSize: mbToBytes(10),
		},
	},
})
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d, channel_id: %d", status, resp.ChannelID)

func (*MgClient) UploadFile added in v1.1.15

func (c *MgClient) UploadFile(request io.Reader) (UploadFileResponse, int, error)

UploadFile uploads a file.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

file, err := os.Open("/tmp/file.png")
if err != nil {
	log.Fatalf("cannot open file for reading: %s", err)
}
defer func() { _ = file.Close() }()

data, err := io.ReadAll(file)
if err != nil {
	log.Fatalf("cannot read file data: %s", err)
}

resp, status, err := client.UploadFile(bytes.NewReader(data))
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d, file ID: %s", status, resp.ID)

func (*MgClient) UploadFileByURL added in v1.1.15

func (c *MgClient) UploadFileByURL(request UploadFileByUrlRequest) (UploadFileResponse, int, error)

UploadFileByURL uploads a file from provided URL.

Example:

client := New("https://message-gateway.url", "cb8ccf05e38a47543ad8477d4999be73bff503ea6")

resp, status, err := client.UploadFileByURL(UploadFileByUrlRequest{
	Url: "https://example.com/file.png",
})
if err != nil {
	log.Fatalf("request error: %s (%d)", err, status)
}

log.Printf("status: %d, file ID: %s", status, resp.ID)

func (*MgClient) WaitForRateLimit added in v1.3.12

func (c *MgClient) WaitForRateLimit()

func (*MgClient) WithLimiter added in v1.3.12

func (c *MgClient) WithLimiter(limiter Limiter) *MgClient

WithLimiter sets the provided limiter instance into the Client.

func (*MgClient) WithLogger added in v1.1.45

func (c *MgClient) WithLogger(logger BasicLogger) *MgClient

WithLogger sets the provided logger instance into the Client.

type Order added in v1.1.8

type Order struct {
	Creating string `json:"creating,omitempty"`
	Editing  string `json:"editing,omitempty"`
	Deleting string `json:"deleting,omitempty"`
}

Order type.

type Originator added in v1.1.28

type Originator byte

Originator of message.

const (
	// OriginatorCustomer means message was created by customer.
	OriginatorCustomer Originator = iota + 1
	// OriginatorChannel means message was created by channel, for example via messenger mobile application.
	OriginatorChannel
)

func (Originator) MarshalText added in v1.1.28

func (o Originator) MarshalText() ([]byte, error)

MarshalText marshals originator to text.

func (*Originator) UnmarshalText added in v1.1.46

func (o *Originator) UnmarshalText(text []byte) error

UnmarshalText unmarshals originator from text to the value.

type PhoneButton added in v1.3.5

type PhoneButton struct {
	Label string `json:"label"`
	Phone string `json:"phone"`
}

func (PhoneButton) ButtonType added in v1.3.5

func (PhoneButton) ButtonType() ButtonType

type PlainButton added in v1.3.5

type PlainButton struct {
	Label string `json:"label"`
}

func (PlainButton) ButtonType added in v1.3.5

func (PlainButton) ButtonType() ButtonType

type Product added in v1.1.8

type Product struct {
	Creating string `json:"creating,omitempty"`
	Editing  string `json:"editing,omitempty"`
	Deleting string `json:"deleting,omitempty"`
}

Product type.

type SendData

type SendData struct {
	Message        Message                  `json:"message"`
	Originator     Originator               `json:"originator,omitempty"`
	Customer       Customer                 `json:"customer"`
	Channel        uint64                   `json:"channel"`
	ExternalChatID string                   `json:"external_chat_id"`
	Quote          *SendMessageRequestQuote `json:"quote,omitempty"`
	ReplyDeadline  *time.Time               `json:"reply_deadline,omitempty"`
}

SendData struct.

type SendHistoryMessageRequest added in v1.2.2

type SendHistoryMessageRequest struct {
	Message        SendMessageRequestMessage `json:"message"`
	ChannelID      uint64                    `json:"channel_id"`
	ExternalChatID string                    `json:"external_chat_id"`
	Customer       *Customer                 `json:"customer"`
	Quote          *SendMessageRequestQuote  `json:"quote,omitempty"`
	Originator     Originator                `json:"originator,omitempty"`
	ReplyDeadline  *time.Time                `json:"reply_deadline,omitempty"`
}

type SendMessage

type SendMessage struct {
	Message
	SentAt time.Time `json:"sent_at,omitempty"`
}

SendMessage struct.

type SendMessageRequestMessage added in v1.2.2

type SendMessageRequestMessage struct {
	Type       string     `json:"type"`
	ExternalID string     `json:"external_id,omitempty"`
	CreatedAt  *time.Time `json:"created_at,omitempty"`
	IsComment  bool       `json:"is_comment,omitempty"`
	Text       string     `json:"text"`
	Items      []Item     `json:"items"`
	Note       string     `json:"note,omitempty"`
}

type SendMessageRequestQuote added in v1.1.0

type SendMessageRequestQuote struct {
	ExternalID string `json:"external_id"`
}

SendMessageRequestQuote type.

type SendingPolicy added in v1.1.38

type SendingPolicy struct {
	NewCustomer       string `json:"new_customer,omitempty"`
	AfterReplyTimeout string `json:"after_reply_timeout,omitempty"`
	Outgoing          string `json:"outgoing,omitempty"`
}

type Status added in v1.1.2

type Status struct {
	Delivered string `json:"delivered,omitempty"`
	Read      string `json:"read,omitempty"`
}

Status struct.

type Suggestion added in v1.1.40

type Suggestion struct {
	Type    SuggestionType `json:"type"`
	Title   string         `json:"title,omitempty"`   // required for type=text and optional for others
	Payload string         `json:"payload,omitempty"` // ignored for type=text
}

type SuggestionType added in v1.1.40

type SuggestionType string
const (
	SuggestionTypeText  SuggestionType = "text"
	SuggestionTypeEmail SuggestionType = "email"
	SuggestionTypePhone SuggestionType = "phone"
	SuggestionTypeURL   SuggestionType = "url"
)

type Template added in v1.1.35

type Template struct {
	ID                 int64                      `json:"id,omitempty"`
	Code               string                     `json:"code,omitempty"`
	ChannelID          uint64                     `json:"channel_id"`
	Name               string                     `json:"name"`
	Enabled            bool                       `json:"enabled"`
	Type               TemplateType               `json:"type"`
	Template           []TemplateItem             `json:"template"`
	Body               string                     `json:"body"`
	Lang               string                     `json:"lang,omitempty"`
	Category           string                     `json:"category,omitempty"`
	Example            *TemplateExample           `json:"example,omitempty"`
	VerificationStatus TemplateVerificationStatus `json:"verification_status"`
	Quality            *TemplateQuality           `json:"quality,omitempty"`
	RejectionReason    TemplateRejectionReason    `json:"rejection_reason,omitempty"`
	Header             *TemplateHeader            `json:"header,omitempty"`
	Footer             string                     `json:"footer,omitempty"`
	Buttons            *TemplateButtons           `json:"buttons,omitempty"`
}

Template struct.

type TemplateArguments added in v1.3.8

type TemplateArguments struct {
	Header  *TemplateHeaderArguments  `json:"header,omitempty"`
	Body    TemplateBodyArguments     `json:"body"`
	Buttons []TemplateButtonArguments `json:"buttons,omitempty"`
}

type TemplateAttachment added in v1.3.7

type TemplateAttachment struct {
	ID      string `json:"id"`
	Caption string `json:"caption"`
}

type TemplateBodyArguments added in v1.3.8

type TemplateBodyArguments struct {
	Args []string `json:"args"`
}

type TemplateButtonArguments added in v1.3.8

type TemplateButtonArguments struct {
	Type  string   `json:"type"`
	Title string   `json:"title"`
	Args  []string `json:"args,omitempty"`
}

type TemplateButtons added in v1.3.5

type TemplateButtons struct {
	Items []Button `json:"items"`
}

func (TemplateButtons) MarshalJSON added in v1.3.5

func (b TemplateButtons) MarshalJSON() ([]byte, error)

func (*TemplateButtons) UnmarshalJSON added in v1.3.5

func (b *TemplateButtons) UnmarshalJSON(value []byte) error

type TemplateContent added in v1.3.0

type TemplateContent struct {
	Name     string           `json:"name"`
	Lang     string           `json:"lang"`
	Category string           `json:"category"`
	Body     string           `json:"body"`
	Header   *TemplateHeader  `json:"header,omitempty"`
	Footer   string           `json:"footer,omitempty"`
	Buttons  *TemplateButtons `json:"buttons,omitempty"`
	Example  *TemplateExample `json:"example,omitempty"`
}

type TemplateCreateWebhookData added in v1.3.0

type TemplateCreateWebhookData struct {
	TemplateContent
	ChannelID int64 `json:"channel_id"`
}

type TemplateCreateWebhookResponse added in v1.3.0

type TemplateCreateWebhookResponse struct {
	Code               string                     `json:"code" binding:"required"`
	VerificationStatus TemplateVerificationStatus `json:"verification_status" binding:"required"`
}

type TemplateDeleteWebhookData added in v1.3.0

type TemplateDeleteWebhookData struct {
	ChannelID int64  `json:"channel_id"`
	Code      string `json:"code"`
	Lang      string `json:"lang"`
}

type TemplateExample added in v1.3.5

type TemplateExample struct {
	Body        []string                    `json:"body,omitempty"`
	Header      []string                    `json:"header,omitempty"`
	Buttons     [][]string                  `json:"buttons,omitempty"`
	Attachments []TemplateExampleAttachment `json:"attachments,omitempty"`
}

type TemplateExampleAttachment added in v1.3.7

type TemplateExampleAttachment struct {
	ID      string `json:"id"`
	Caption string `json:"caption"`
}

type TemplateHeader added in v1.3.5

type TemplateHeader struct {
	Content HeaderContent `json:"content"`
}

func (*TemplateHeader) DocumentContent added in v1.3.5

func (h *TemplateHeader) DocumentContent() *HeaderContentDocument

func (*TemplateHeader) ImageContent added in v1.3.5

func (h *TemplateHeader) ImageContent() *HeaderContentImage

func (TemplateHeader) MarshalJSON added in v1.3.5

func (h TemplateHeader) MarshalJSON() ([]byte, error)

func (*TemplateHeader) TextContent added in v1.3.5

func (h *TemplateHeader) TextContent() *HeaderContentText

func (*TemplateHeader) UnmarshalJSON added in v1.3.5

func (h *TemplateHeader) UnmarshalJSON(value []byte) error

func (*TemplateHeader) VideoContent added in v1.3.5

func (h *TemplateHeader) VideoContent() *HeaderContentVideo

type TemplateHeaderArguments added in v1.3.8

type TemplateHeaderArguments struct {
	Type        string               `json:"type"`
	Args        []string             `json:"args,omitempty"`        // for type="text" only
	Attachments []TemplateAttachment `json:"attachments,omitempty"` // for media templates only
}

type TemplateInfo added in v1.1.37

type TemplateInfo struct {
	Code      string            `json:"code"`
	Variables TemplateArguments `json:"variables,omitempty"`
}

type TemplateItem added in v1.1.35

type TemplateItem struct {
	Type    uint8
	Text    string
	VarType string
}

TemplateItem is a part of template.

func (TemplateItem) MarshalJSON added in v1.1.35

func (t TemplateItem) MarshalJSON() ([]byte, error)

MarshalJSON controls how TemplateItem will be marshaled into JSON.

func (*TemplateItem) UnmarshalJSON added in v1.1.35

func (t *TemplateItem) UnmarshalJSON(b []byte) error

UnmarshalJSON will correctly unmarshal TemplateItem.

type TemplateQuality added in v1.3.11

type TemplateQuality string
const (
	TemplateQualityPending TemplateQuality = "pending"
	TemplateQualityHigh    TemplateQuality = "high"
	TemplateQualityMedium  TemplateQuality = "medium"
	TemplateQualityLow     TemplateQuality = "low"
)

type TemplateRejectionReason added in v1.3.5

type TemplateRejectionReason string
const (
	ReasonAbusiveContent    TemplateRejectionReason = "abusive_content"
	ReasonIncorrectCategory TemplateRejectionReason = "incorrect_category"
	ReasonInvalidFormat     TemplateRejectionReason = "invalid_format"
	ReasonScam              TemplateRejectionReason = "scam"
)

type TemplateType added in v1.3.5

type TemplateType uint8
const (
	TemplateTypeText TemplateType = iota + 1
	TemplateTypeMedia
)

func (TemplateType) MarshalText added in v1.3.5

func (e TemplateType) MarshalText() (text []byte, err error)

func (TemplateType) String added in v1.3.5

func (e TemplateType) String() string

func (*TemplateType) UnmarshalText added in v1.3.5

func (e *TemplateType) UnmarshalText(text []byte) error

type TemplateUpdateWebhookData added in v1.3.0

type TemplateUpdateWebhookData struct {
	TemplateContent
	ChannelID int64  `json:"channel_id"`
	Code      string `json:"code"`
}

type TemplateVerificationStatus added in v1.3.0

type TemplateVerificationStatus string
const (
	TemplateStatusApproved TemplateVerificationStatus = "approved"
	TemplateStatusPending  TemplateVerificationStatus = "pending"
	TemplateStatusRejected TemplateVerificationStatus = "rejected"
	TemplateStatusNew      TemplateVerificationStatus = "new"
	TemplateStatusPaused   TemplateVerificationStatus = "paused"
	TemplateStatusDisabled TemplateVerificationStatus = "disabled"
)

type TokensBucket added in v1.3.12

type TokensBucket struct {
	// contains filtered or unexported fields
}

TokensBucket implements basic Limiter with fixed window and fixed amount of tokens per window.

func (*TokensBucket) Obtain added in v1.3.12

func (m *TokensBucket) Obtain(id string)

type TransportError added in v1.1.42

type TransportError struct {
	Code    TransportErrorCode `json:"code"`
	Message string             `json:"message,omitempty"`
}

type TransportErrorCode added in v1.1.42

type TransportErrorCode string
const (
	MessageErrorGeneral           TransportErrorCode = "general"
	MessageErrorCustomerNotExists TransportErrorCode = "customer_not_exists"
	MessageErrorReplyTimedOut     TransportErrorCode = "reply_timed_out"
	MessageErrorSpamSuspicion     TransportErrorCode = "spam_suspicion"
	MessageErrorAccessRestricted  TransportErrorCode = "access_restricted"
)

func (TransportErrorCode) MarshalJSON added in v1.1.42

func (t TransportErrorCode) MarshalJSON() ([]byte, error)

type TransportRequestMeta added in v1.1.0

type TransportRequestMeta struct {
	ID        uint64 `json:"id"`
	Timestamp int64  `json:"timestamp"`
}

TransportRequestMeta request metadata.

type TransportResponse added in v1.1.42

type TransportResponse struct {
	ExternalMessageID string          `json:"external_message_id,omitempty"`
	Error             *TransportError `json:"error,omitempty"`
}

func NewSentMessageResponse added in v1.1.42

func NewSentMessageResponse(externalMessageID string) TransportResponse

func NewTransportErrorResponse added in v1.1.42

func NewTransportErrorResponse(code TransportErrorCode, message string) TransportResponse

type URLButton added in v1.2.7

type URLButton struct {
	Label string `json:"label"`
	URL   string `json:"url"`
}

func (URLButton) ButtonType added in v1.3.5

func (URLButton) ButtonType() ButtonType

type UpdateResponse

type UpdateResponse struct {
	ChannelID  uint64    `json:"id"`
	ExternalID string    `json:"external_id"`
	UpdatedAt  time.Time `json:"updated_at"`
}

UpdateResponse channel update response.

type UpdateTemplateRequest added in v1.3.5

type UpdateTemplateRequest struct {
	Name               string                     `json:"name"`
	Template           []TemplateItem             `json:"template,omitempty"`
	Body               string                     `json:"body"`
	Lang               string                     `json:"lang,omitempty"`
	Category           string                     `json:"category,omitempty"`
	Example            *TemplateExample           `json:"example,omitempty"`
	VerificationStatus TemplateVerificationStatus `json:"verification_status"`
	Quality            *TemplateQuality           `json:"quality,omitempty"`
	RejectionReason    TemplateRejectionReason    `json:"rejection_reason,omitempty"`
	Header             *TemplateHeader            `json:"header,omitempty"`
	Footer             string                     `json:"footer,omitempty"`
	Buttons            *TemplateButtons           `json:"buttons,omitempty"`
}

type UploadFileByUrlRequest added in v1.1.15

type UploadFileByUrlRequest struct {
	Url string `json:"url"`
}

UploadFileByUrlRequest file url to upload.

type UploadFileResponse added in v1.1.15

type UploadFileResponse struct {
	ID        string    `json:"id"`
	Hash      string    `json:"hash"`
	Type      string    `json:"type"`
	Meta      FileMeta  `json:"meta"`
	MimeType  string    `json:"mime_type"`
	Size      int       `json:"size"`
	Url       *string   `json:"source_url"`
	CreatedAt time.Time `json:"created_at"`
}

UploadFileResponse uploaded file data.

type Utm added in v1.2.3

type Utm struct {
	Source   string `json:"source,omitempty"`
	Medium   string `json:"medium,omitempty"`
	Campaign string `json:"campaign,omitempty"`
	Term     string `json:"term,omitempty"`
	Content  string `json:"content,omitempty"`
}

type WebhookMessageSentResponse added in v1.1.41

type WebhookMessageSentResponse struct {
	ExternalMessageID string            `json:"external_message_id"`
	Error             *MessageSentError `json:"error,omitempty"`
	Async             bool              `json:"async"`
}

WebhookMessageSentResponse type Consider using this structure while processing webhook request.

type WebhookRequest added in v1.1.0

type WebhookRequest struct {
	Type WebhookType          `json:"type"`
	Meta TransportRequestMeta `json:"meta"`
	Data json.RawMessage      `json:"data"`
}

WebhookRequest type.

func (WebhookRequest) IsMessageWebhook added in v1.3.0

func (w WebhookRequest) IsMessageWebhook() bool

IsMessageWebhook returns true if current webhook contains data related to chat messages.

func (WebhookRequest) IsTemplateWebhook added in v1.3.0

func (w WebhookRequest) IsTemplateWebhook() bool

IsTemplateWebhook returns true if current webhook contains data related to the templates changes.

func (WebhookRequest) MessageWebhookData added in v1.3.0

func (w WebhookRequest) MessageWebhookData() (wd MessageWebhookData)

MessageWebhookData returns the message data from webhook contents.

Note: this call will not fail even if underlying data is not related to the messages. Use IsMessageWebhook to mitigate this.

func (WebhookRequest) TemplateCreateWebhookData added in v1.3.0

func (w WebhookRequest) TemplateCreateWebhookData() (wd TemplateCreateWebhookData)

TemplateCreateWebhookData returns new template data from webhook contents. This method is used if current webhook was initiated because user created a template.

Note: this call will not fail even if underlying data is not related to the templates. Use IsTemplateWebhook or direct Type comparison (Type == TemplateCreateWebhookType) to mitigate this.

func (WebhookRequest) TemplateDeleteWebhookData added in v1.3.0

func (w WebhookRequest) TemplateDeleteWebhookData() (wd TemplateDeleteWebhookData)

TemplateDeleteWebhookData returns existing template data from webhook contents. This method is used if current webhook was initiated because user deleted a template.

Note: this call will not fail even if underlying data is not related to the templates. Use IsTemplateWebhook or direct Type comparison (Type == TemplateDeleteWebhookType) to mitigate this.

func (WebhookRequest) TemplateUpdateWebhookData added in v1.3.0

func (w WebhookRequest) TemplateUpdateWebhookData() (wd TemplateUpdateWebhookData)

TemplateUpdateWebhookData returns existing template data from webhook contents. This method is used if current webhook was initiated because user updated a template.

Note: this call will not fail even if underlying data is not related to the templates. Use IsTemplateWebhook or direct Type comparison (Type == TemplateUpdateWebhookData) to mitigate this.

type WebhookType added in v1.3.0

type WebhookType string
const (
	MessageSendWebhookType    WebhookType = "message_sent"
	MessageUpdateWebhookType  WebhookType = "message_updated"
	MessageDeleteWebhookType  WebhookType = "message_deleted"
	MessageReadWebhookType    WebhookType = "message_read"
	TemplateCreateWebhookType WebhookType = "template_create"
	TemplateUpdateWebhookType WebhookType = "template_update"
	TemplateDeleteWebhookType WebhookType = "template_delete"
)

type WhatsAppChannelProperties added in v1.3.14

type WhatsAppChannelProperties struct {
	Tier           *int                    `json:"tier"`
	ChannelQuality *WhatsAppChannelQuality `json:"channel_quality"`
	ChannelStatus  *WhatsAppChannelStatus  `json:"channel_status"`
}

WhatsAppChannelProperties WhatsApp-specific channel characteristics

type WhatsAppChannelQuality added in v1.3.14

type WhatsAppChannelQuality string
var (
	WhatsAppChannelQualityHigh   WhatsAppChannelQuality = "high"
	WhatsAppChannelQualityMedium WhatsAppChannelQuality = "medium"
	WhatsAppChannelQualityLow    WhatsAppChannelQuality = "low"
)

type WhatsAppChannelStatus added in v1.3.14

type WhatsAppChannelStatus string
var (
	WhatsAppChannelStatusConnected  WhatsAppChannelStatus = "connected"
	WhatsAppChannelStatusFlagged    WhatsAppChannelStatus = "flagged"
	WhatsAppChannelStatusOffline    WhatsAppChannelStatus = "offline"
	WhatsAppChannelStatusPending    WhatsAppChannelStatus = "pending"
	WhatsAppChannelStatusRestricted WhatsAppChannelStatus = "restricted"
)

Jump to

Keyboard shortcuts

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