viber

package module
v0.0.0-...-9cba43e Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2020 License: MIT Imports: 13 Imported by: 0

README

Go/Golang package for Viber messaging and chatbot GoDoc

With this package you can use Viber REST API to send and receive messages from Viber platform.

All structs used in package represents the structs identical to Viber REST API. To fully understand Viber messaging platform and this package as well, you should read Viber REST API.

Before using this package you will need Viber public account and your App key which you can find in Edit section of your Viber public account.

Installation

go get github.com/mileusna/viber

Hello World example

package main 

import (
    "fmt"
    "log"

    "github.com/mileusna/viber"
)

func main() {
    v := viber.New("YOUR-APP-KEY-FROM-VIBER", "MyPage", "https://mysite.com/img/avatar.jpg")

    // you really need this only once, remove after you set the webhook
    v.SetWebhook("https://mysite.com/viber/webhook/", nil)

    userID := "Goxxuipn9xKKRqkFOOwKnw==" // fake user ID, use the real one

    // send text message
    token, err := v.SendTextMessage(userID, "Hello, World!")
    if err != nil {
        log.Println("Viber error:", err)
        return
    }
    fmt.Println("Message sent, message token:", token)
}

At the begining you neew to declare your viber struct with you app key. Sender is default sender which will be used as default for sending all messages to the users and public account. But, for each message you can specify different sender if you like.

v := viber.New("YOUR-APP-KEY-FROM-VIBER", "MyPage", "https://mysite.com/img/avatar.jpg")

Read more about SetWebhook in following chapter.

After that, you can send different kind of messages to the user.

Here you can read how to handle message receiving.

Webhook

To be able to receive messages and notifications from Viber you have to specify your webhook. Webhook is the URL where Viber will send you all messages and notification. You only have to do this once in a lifetime. URL of webhook have to be online in moment you call SetWebhook since Viber will send http request to webhook URL expecting HTTP status code 200. For more info visit Viber documentation on Webhooks.

// if eventTypes is nil, all callbacks will be set to webhook
// if eventTypes is empty []string mandatory callbacks will be set
// Mandatory callbacks: "message", "subscribed", "unsubscribed"
// All possible callbacks: "message", "subscribed",  "unsubscribed", "delivered", "seen", "failed", "conversation_started"
v.SetWebhook("https://mysite.com/viber/webhook/", nil)

Messaging

You can send message in different ways. The easiest way is to use shortcut functions like SendTextMessage or SendURLMessage:

v.SendTextMessage(userID, "Hello, World!")

v.SendURLMessage(userID, "Visit my site", "http://mysite.com/")

v.SendPictureMessage(userID, "Take a look at this photo", "http://mysite.com/photo.jpg")

This function will send messages to userID (you will get userID when you receive message from user) using default sender specified in declaration.

You can create individual message, change some settings and then send it using SendMessage

// create message, change the sender for this message and then send id
m := v.NewTextMessage("Hello, world!")
m.Sender = viber.Sender{
    Name:   "SomeOtherName",
    Avatar: "https://mysite.com/img/other_avatar.jpg",
}
v.SendMessage(userID, m)

Documentation coming soon.

Send Messages to Public Account

In previous examples you send messages directly to the user subscribed to your public account. If you want to send message to the Public Account which will be seen by all PA followers, use te SendPublicMessage function.

// adminID is the ID of PA administrator
m := v.NewTextMessage("Hello to everyone")
v.SendPublicMessage(adminID, m)

imgMsg := v.NewImageMessage("Photo for everyone", "http://mysite.com/photo.jpg")
v.SendPublicMessage(adminID, imgMsg)

Account info

In previous example you have to use ID of administrator of Public account. To obtain Public Acount info and the list of administrators, use the AccountInfo function.

a, err := v.AccountInfo()
if err != nil {
    log.Println("AccountInfo Viber error:", err)
    return
}

// print all admministrators
for _, m := range a.Members {
    fmt.Println(m.ID, m.Name, m.Role)
}

User details

When receiving message from user, or when user starts the conversation, you will receive some bacis user info. To obtain full user details use the UserDetails function.

u, err := v.UserDetails(userID)
if err != nil {
    log.Println("User details viber error:", err)
    return
}

fmt.Println("Details:", u.Name, u.Avatar, u.Country, u.Language, u.DeviceType, u.PrimaryDeviceOs)

Receiving messages / Callbacks

To receive messages and other callbacks, you have to run you viber app on webhook URL you specified using SetWebhook. You can easily manage all Viber callbacks (Message, Subscribed, Unsubscribed, Delivered, Seen, Failed) using this package by specifying your own functions which will be called on event.

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/mileusna/viber"
)

func main() {
    v := &viber.Viber{
        AppKey: "YOUR-APP-KEY-FROM-VIBER",
        Sender: viber.Sender{
            Name:   "MyPage",
            Avatar: "https://mysite.com/img/avatar.jpg",
        },
        Message:   myMsgReceivedFunc,  // your function for handling messages
        Delivered: myDeliveredFunc,    // your function for delivery report
    }
    v.Seen = mySeenFunc   // or assign events after declaration
    
    // this have to be your webhook, pass it your viber app as http handler
    http.Handle("/viber/webhook/", v)
    http.ListenAndServe(":80", nil)    
}

// myMsgReceivedFunc will be called everytime when user send us a message
func myMsgReceivedFunc(v *viber.Viber, u viber.User, m viber.Message, token uint64, t time.Time) {
    switch m.(type) {

    case *viber.TextMessage:
        v.SendTextMessage(u.ID, "Thank you for your message")
        txt := m.(*viber.TextMessage).Text
        v.SendTextMessage(u.ID, "This is the text you have sent to me "+txt)

    case *viber.URLMessage:
        url := m.(*viber.URLMessage).Media
        v.SendTextMessage(u.ID, "You have sent me an interesting link "+url)

    case *viber.PictureMessage:
        v.SendTextMessage(u.ID, "Nice pic!")

    }
}

func myDeliveredFunc(v *viber.Viber, userID string, token uint64, t time.Time) {
    log.Println("Message ID", token, "delivered to user ID", userID)
}

func mySeenFunc(v *viber.Viber, userID string, token uint64, t time.Time) {
    log.Println("Message ID", token, "seen by user ID", userID)
}


// All events that you can assign your function, declarations must match
// ConversationStarted func(v *Viber, u User, conversationType, context string, subscribed bool, token uint64, t time.Time) Message
// Message             func(v *Viber, u User, m Message, token uint64, t time.Time)
// Subscribed          func(v *Viber, u User, token uint64, t time.Time)
// Unsubscribed        func(v *Viber, userID string, token uint64, t time.Time)
// Delivered           func(v *Viber, userID string, token uint64, t time.Time)
// Seen                func(v *Viber, userID string, token uint64, t time.Time)
// Failed              func(v *Viber, userID string, token uint64, descr string, t time.Time) 

Documentation

Index

Constants

View Source
const (
	Small   = TextSize("small")
	Medium  = TextSize("medium")
	Large   = TextSize("large")
	Regular = TextSize("regular")
)

TextSize values

View Source
const (
	Reply   = ActionType("reply")
	OpenURL = ActionType("open-url")
	None    = ActionType("none")
)

ActionType values

View Source
const (
	Top    = TextVAlign("top")
	Middle = TextVAlign("middle")
	Bottom = TextVAlign("bottom")
)

TextVAlign values

View Source
const (
	Left   = TextHAlign("left")
	Center = TextHAlign("center")
	Right  = TextHAlign("right")
)

TextHAlign values

View Source
const (
	TypeTextMessage      = MessageType("text")
	TypeURLMessage       = MessageType("url")
	TypePictureMessage   = MessageType("picture")
	TypeVideoMessage     = MessageType("video")
	TypeFileMessage      = MessageType("file")
	TypeLocationMessage  = MessageType("location")
	TypeContactMessage   = MessageType("contact")
	TypeStickerMessage   = MessageType("sticker")
	TypeRichMediaMessage = MessageType("rich_media")
)

Message types

Variables

View Source
var (
	// Log errors, set to logger if you want to log package activities and errors
	Log = log.New(ioutil.Discard, "Viber >>", 0)
)

Functions

func ErrorStatus

func ErrorStatus(e interface{}) int

ErrorStatus code of Viber error, returns -1 if e is not Viber error

Types

type Account

type Account struct {
	Status        int    `json:"status"`
	StatusMessage string `json:"status_message"`
	ID            string `json:"id"`
	Name          string `json:"name"`
	URI           string `json:"uri"`
	Icon          string `json:"icon"`
	Background    string `json:"background"`
	Category      string `json:"category"`
	Subcategory   string `json:"subcategory"`
	Location      struct {
		Lon float64 `json:"lon"`
		Lat float64 `json:"lat"`
	} `json:"location"`
	Country          string   `json:"country"`
	Webhook          string   `json:"webhook"`
	EventTypes       []string `json:"event_types"`
	SubscribersCount int      `json:"subscribers_count"`
	Members          []Member `json:"members"`
}

Account details

type ActionType

type ActionType string

ActionType for carousel buttons viber.Reply viber.OpenURL

type Button

type Button struct {
	Columns             int        `json:"Columns"`
	Rows                int        `json:"Rows"`
	ActionType          ActionType `json:"ActionType"`
	ActionBody          string     `json:"ActionBody"`
	Image               string     `json:"Image,omitempty"`
	Text                string     `json:"Text,omitempty"`
	TextSize            TextSize   `json:"TextSize,omitempty"`
	TextVAlign          TextVAlign `json:"TextVAlign,omitempty"`
	TextHAlign          TextHAlign `json:"TextHAlign,omitempty"`
	TextOpacity         int8       `json:"TextOpacity,omitempty"`
	TextBgGradientColor string     `json:"TextBgGradientColor,omitempty"`
	BgColor             string     `json:"BgColor,omitempty"`
	BgMediaType         string     `json:"BgMediaType,omitempty"`
	BgMedia             string     `json:"BgMedia,omitempty"`
	BgLoop              bool       `json:"BgLoop,omitempty"`
	Silent              bool       `json:"Silent,omitempty"`
}

Button for carousel and keyboards

func (*Button) BgMediaGIF

func (b *Button) BgMediaGIF(gifURL string, loop bool) *Button

BgMediaGIF set BgMedia to GIF with loop param

func (*Button) BgMediaPicture

func (b *Button) BgMediaPicture(picURL string) *Button

BgMediaPicture to set background to PNG or JPG. Use BgMediaGIF for GIF background

func (*Button) SetBgColor

func (b *Button) SetBgColor(hex string) *Button

SetBgColor for button

func (*Button) SetSilent

func (b *Button) SetSilent() *Button

SetSilent response from button

func (*Button) SetTextOpacity

func (b *Button) SetTextOpacity(o int8) *Button

SetTextOpacity 0-100

func (*Button) TextHAlignCenter

func (b *Button) TextHAlignCenter() *Button

TextHAlignCenter horizontaly center text

func (*Button) TextHAlignLeft

func (b *Button) TextHAlignLeft() *Button

TextHAlignLeft horizontaly center text left

func (*Button) TextHAlignRight

func (b *Button) TextHAlignRight() *Button

TextHAlignRight horizontaly align text right

func (*Button) TextSizeLarge

func (b *Button) TextSizeLarge() *Button

TextSizeLarge for button text

func (*Button) TextSizeMedium

func (b *Button) TextSizeMedium() *Button

TextSizeMedium for button text, synonym to Regular

func (*Button) TextSizeRegular

func (b *Button) TextSizeRegular() *Button

TextSizeRegular for button text, synonym to Medium

func (*Button) TextSizeSmall

func (b *Button) TextSizeSmall() *Button

TextSizeSmall for button text

func (*Button) TextVAlignBottom

func (b *Button) TextVAlignBottom() *Button

TextVAlignBottom vertically align text to the bottom

func (*Button) TextVAlignMiddle

func (b *Button) TextVAlignMiddle() *Button

TextVAlignMiddle vertically align text to the middle

func (*Button) TextVAlignTop

func (b *Button) TextVAlignTop() *Button

TextVAlignTop vertically align text to the top

type Contact

type Contact struct {
	Name        string `json:"name"`
	PhoneNumber string `json:"phone_number"`
	Avatar      string `json:"avatar"`
}

type ContactMessage

type ContactMessage struct {
	TextMessage
	Contact Contact `json:"contact"`
}

ContactMessage structure

type Error

type Error struct {
	Status        int
	StatusMessage string
	FailedList    []FailedResponse
}

Error from Viber

func (Error) Error

func (e Error) Error() string

Error interface function

type FailedResponse

type FailedResponse struct {
	Receiver      string `json:"receiver"`
	Status        int    `json:"status"`
	StatusMessage string `json:"status_message"`
}

FailedList from Viber

func ErrorFailedList

func ErrorFailedList(e interface{}) []FailedResponse

type FileMessage

type FileMessage struct {
	TextMessage
	Media    string `json:"media"`
	Size     int    `json:"size"`
	FileName string `json:"file_name"`
}

FileMessage structure

type Keyboard

type Keyboard struct {
	Type          string   `json:"Type"`
	DefaultHeight bool     `json:"DefaultHeight,omitempty"`
	BgColor       string   `json:"BgColor,omitempty"`
	Buttons       []Button `json:"Buttons"`
}

Keyboard struct

func (*Keyboard) AddButton

func (k *Keyboard) AddButton(b *Button)

AddButton to keyboard

type Member

type Member struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Avatar string `json:"avatar"`
	Role   string `json:"role"`
}

Member of account details

type Message

type Message interface {
	SetReceiver(r string)
	SetBroadcastList(bl []string)
	SetFrom(from string)
	SetKeyboard(k *Keyboard)
}

Message interface for all types of viber messages

type MessageType

type MessageType string

MessageType for viber messaging

type PictureMessage

type PictureMessage struct {
	TextMessage
	Media     string `json:"media"`
	Thumbnail string `json:"thumbnail,omitempty"`
}

PictureMessage structure

type RichMedia

type RichMedia struct {
	Type                MessageType `json:"Type"`
	ButtonsGroupColumns int         `json:"ButtonsGroupColumns"`
	ButtonsGroupRows    int         `json:"ButtonsGroupRows"`
	BgColor             string      `json:"BgColor"`
	Buttons             []Button    `json:"Buttons"`
}

RichMedia for carousel

type RichMediaMessage

type RichMediaMessage struct {
	AuthToken     string      `json:"auth_token"`
	Receiver      string      `json:"receiver,omitempty"`
	Type          MessageType `json:"type"`
	MinAPIVersion int         `json:"min_api_version"`
	RichMedia     RichMedia   `json:"rich_media"`
	AltText       string      `json:"alt_text,omitempty"`
	Keyboard      *Keyboard   `json:"keyboard,omitempty"`
	TrackingData  string      `json:"tracking_data,omitempty"`
}

RichMediaMessage / Carousel

func (*RichMediaMessage) AddButton

func (rm *RichMediaMessage) AddButton(b *Button)

AddButton to rich media message

func (*RichMediaMessage) SetFrom

func (rm *RichMediaMessage) SetFrom(from string)

SetFrom to satisfy interface although RichMedia messages can't be sent to publich chat and don't have From

func (*RichMediaMessage) SetKeyboard

func (rm *RichMediaMessage) SetKeyboard(k *Keyboard)

SetKeyboard for text message

func (*RichMediaMessage) SetReceiver

func (rm *RichMediaMessage) SetReceiver(r string)

SetReceiver for RichMedia message

type Sender

type Sender struct {
	Name   string `json:"name"`
	Avatar string `json:"avatar,omitempty"`
}

Sender structure

type TextHAlign

type TextHAlign string

TextHAlign for carousel buttons viber.Left viber.Center (default) viber.Middle

type TextMessage

type TextMessage struct {
	Receiver      string      `json:"receiver,omitempty"`
	BroadcastList []string    `json:"broadcast_list,omitempty"`
	From          string      `json:"from,omitempty"`
	MinAPIVersion uint        `json:"min_api_version,omitempty"`
	Sender        Sender      `json:"sender"`
	Type          MessageType `json:"type"`
	TrackingData  string      `json:"tracking_data,omitempty"`
	Text          string      `json:"text"`
	Keyboars      *Keyboard   `json:"keyboard,omitempty"`
}

TextMessage for Viber

func (*TextMessage) SetBroadcastList

func (m *TextMessage) SetBroadcastList(bl []string)

SetReceiver for text message

func (*TextMessage) SetFrom

func (m *TextMessage) SetFrom(from string)

SetFrom to text message for public account message

func (*TextMessage) SetKeyboard

func (m *TextMessage) SetKeyboard(k *Keyboard)

SetKeyboard for text message

func (*TextMessage) SetReceiver

func (m *TextMessage) SetReceiver(r string)

SetReceiver for text message

type TextSize

type TextSize string

TextSize for carousel buttons viber.Small viber.Medium (synonym to regular) viber.Large viber.Regular (default)

type TextVAlign

type TextVAlign string

TextVAlign for carousel buttons viber.Top viber.Middle (default) viber.Bottom

type Timestamp

type Timestamp struct {
	time.Time
}

Timestamp struct for easily MarshalJSON/UnmarshalJSON unix timestamp to time.Time

func (*Timestamp) MarshalJSON

func (t *Timestamp) MarshalJSON() ([]byte, error)

MarshalJSON converts golang time to unix timestam number

func (*Timestamp) UnmarshalJSON

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

UnmarshalJSON converts unix timestamp to golang time

type URLMessage

type URLMessage struct {
	TextMessage
	Media string `json:"media"`
}

URLMessage structure

type User

type User struct {
	ID              string `json:"id"`
	Name            string `json:"name"`
	Avatar          string `json:"avatar"`
	Country         string `json:"country"`
	Language        string `json:"language"`
	PrimaryDeviceOs string `json:"primary_device_os"`
	APIVersion      int    `json:"api_version"`
	ViberVersion    string `json:"viber_version"`
	Mcc             int    `json:"mcc"`
	Mnc             int    `json:"mnc"`
	DeviceType      string `json:"device_type"`
}

User struct as part of UserDetails

type UserDetails

type UserDetails struct {
	Status        int    `json:"status"`
	StatusMessage string `json:"status_message"`
	MessageToken  int64  `json:"message_token"`
	User          `json:"user"`
}

UserDetails for Viber user

type UserOnline

type UserOnline struct {
	ID                  string `json:"id"`
	OnlineStatus        int    `json:"online_status"`
	OnlineStatusMessage string `json:"online_status_message"`
	LastOnline          int64  `json:"last_online,omitempty"`
}

UserOnline response struct

type Viber

type Viber struct {
	AppKey string
	Sender Sender

	// event methods
	ConversationStarted func(v *Viber, u User, conversationType, context string, subscribed bool, token uint64, t time.Time) Message
	Message             func(v *Viber, u User, m Message, token uint64, t time.Time)
	Subscribed          func(v *Viber, u User, token uint64, t time.Time)
	Unsubscribed        func(v *Viber, userID string, token uint64, t time.Time)
	Delivered           func(v *Viber, userID string, token uint64, t time.Time)
	Seen                func(v *Viber, userID string, token uint64, t time.Time)
	Failed              func(v *Viber, userID string, token uint64, descr string, t time.Time)
	// contains filtered or unexported fields
}

Viber app

func New

func New(appKey, senderName, senderAvatar string) *Viber

New returns Viber app with specified app key and default sender You can also create *VIber{} struct directly

func (*Viber) AccountInfo

func (v *Viber) AccountInfo() (Account, error)

AccountInfo returns Public chat info https://developers.viber.com/docs/api/rest-bot-api/#get-account-info

func (*Viber) NewButton

func (v *Viber) NewButton(cols, rows int, typ ActionType, actionBody string, text, image string) *Button

NewButton helper function for creating button with text and image

func (*Viber) NewFileMessage

func (v *Viber) NewFileMessage(media string, size int, fileName string) *FileMessage

NewFileMessage for viber

func (*Viber) NewImageButton

func (v *Viber) NewImageButton(cols, rows int, typ ActionType, actionBody string, image string) *Button

NewImageButton helper function for creating image button struct with common params

func (*Viber) NewKeyboard

func (v *Viber) NewKeyboard(bgcolor string, defaultHeight bool) *Keyboard

NewKeyboard struct with attribs init

func (*Viber) NewPictureMessage

func (v *Viber) NewPictureMessage(msg string, url string, thumbURL string) *PictureMessage

NewPictureMessage for viber

func (*Viber) NewRichMediaMessage

func (v *Viber) NewRichMediaMessage(cols, rows int, bgColor string) *RichMediaMessage

NewRichMediaMessage creates new empty carousel message

func (*Viber) NewTextButton

func (v *Viber) NewTextButton(cols, rows int, t ActionType, actionBody, text string) *Button

NewTextButton helper function for creating image button struct with common params

func (*Viber) NewTextMessage

func (v *Viber) NewTextMessage(msg string) *TextMessage

NewTextMessage viber

func (*Viber) NewURLMessage

func (v *Viber) NewURLMessage(msg string, url string) *URLMessage

NewURLMessage creates new message with global sender and common params set

func (*Viber) PostData

func (v *Viber) PostData(url string, i interface{}) ([]byte, error)

PostData to viber API

func (*Viber) SendBroadcastMessage

func (v *Viber) SendBroadcastMessage(to []string, m Message) (msgToken uint64, err error)

SendMessage to receiver

func (*Viber) SendMessage

func (v *Viber) SendMessage(to string, m Message) (msgToken uint64, err error)

SendMessage to receiver

func (*Viber) SendPictureMessage

func (v *Viber) SendPictureMessage(receiver string, msg string, url string, thumbURL string) (token uint64, err error)

SendPictureMessage to receiver, returns message token

func (*Viber) SendPublicMessage

func (v *Viber) SendPublicMessage(from string, m Message) (msgToken uint64, err error)

SendPublicMessage from public account

func (*Viber) SendTextMessage

func (v *Viber) SendTextMessage(receiver string, msg string) (msgToken uint64, err error)

SendTextMessage to reciever, returns message token

func (*Viber) SendURLMessage

func (v *Viber) SendURLMessage(receiver string, msg string, url string) (msgToken uint64, err error)

SendURLMessage to easily send url messages as global sender

func (*Viber) SetRequestTimeout

func (v *Viber) SetRequestTimeout(t time.Duration)

SetRequestTimeout for sending messages to viber server

func (*Viber) SetWebhook

func (v *Viber) SetWebhook(url string, eventTypes []string) (WebhookResp, error)

SetWebhook for Viber callbacks if eventTypes is nil, all callbacks will be set to webhook if eventTypes is empty []string mandatory callbacks will be set Mandatory callbacks: "message", "subscribed", "unsubscribed" All possible callbacks: "message", "subscribed", "unsubscribed", "delivered", "seen", "failed", "conversation_started"

func (*Viber) UserDetails

func (v *Viber) UserDetails(id string) (UserDetails, error)

UserDetails of user id

func (*Viber) UserOnline

func (v *Viber) UserOnline(ids []string) ([]UserOnline, error)

UserOnline status

type VideoMessage

type VideoMessage struct {
	TextMessage
	Media     string `json:"media"`
	Thumbnail string `json:"thumbnail,omitempty"`
	Size      uint   `json:"size"`
	Duration  uint   `json:"duration,omitempty"`
}

VideoMessage structure

type WebhookReq

type WebhookReq struct {
	URL        string   `json:"url"`
	EventTypes []string `json:"event_types"`
}

WebhookReq request

type WebhookResp

type WebhookResp struct {
	Status        int      `json:"status"`
	StatusMessage string   `json:"status_message"`
	EventTypes    []string `json:"event_types,omitempty"`
}

WebhookResp response

type WebhookVerify

type WebhookVerify struct {
	Event        string `json:"event"`
	Timestamp    uint64 `json:"timestamp"`
	MessageToken uint64 `json:"message_token"`
}

WebhookVerify response

Jump to

Keyboard shortcuts

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