Public Account Documentation6.9.0

Docs / All

Viber Java Bot API

Use this library to develop a bot for Viber platform. The library is available on GitHub as well as maven central.

Table of Contents

License

This library is released under the terms of the Apache 2.0 license. See License for more information.

Library Prerequisites

Installation

This library is released on maven central.

Gradle

compile group: 'com.viber', name: 'viber-bot', version: '1.0.11'

Maven

<dependency>
    <groupId>com.viber</groupId>
    <artifactId>viber-bot</artifactId>
    <version>1.0.11</version>
</dependency>

Documentation

JavaDocs

All public APIs are documented with JavaDocs which can be found in the GitHub repository.

Sample projects

We’ve created two sample projects to help you get started:

A simple overview

public void botExample() {
    ViberBot bot = new ViberBot(new BotProfile("SampleBot", "http://viber.com/avatar.jpg"), "YOUR_AUTH_TOKEN_HERE");
    bot.onMessageReceived((event, message, response) -> response.send(message));

    // somewhere else in your web server of choice:
    bot.incoming(Request.fromJsonString("..."));
}

You can chose to use any web server or framework you like. All you need to do is call the API with -

bot.incoming(Request.fromJsonString("...")); // or
bot.incoming(Request.fromInputStream(inputStream));

Should I be concerned with synchronizing my web server threads? Is this library thread-safe?

The Viber bot library is thread-safe and highly concurrent. You do not have to worry about synchronizing anything.

All calls to ViberBot#incoming() go through a BlockingQueue, and ordering is retained. All I/O calls are directly executed on the same thread they were initially called on.

Can I make I/O calls asynchronous and still retain thread-safety for my bot?

Yes. You can pass a system property to control the I/O thread pool:

com.viber.bot.executor.strategy=[DIRECT|THREAD] (default is DIRECT)

com.viber.bot.executor.threads=N (default is getRuntime().availableProcessors())

Do you supply a basic router for text messages?

Well funny you ask. Yes we do. But a word of warning - messages sent to your router callback will also be emitted to the ViberBot#onMessageReceived event.

public void botTextRouterExample() {
    bot.onTextMessage("(hi|hello)", (event, message, response) -> response.send("Hi " + event.getSender().getName()));
}

Community

Join the conversation on Gitter.


Viber Node.JS Bot API

Use this library to develop a bot for the Viber platform. The library is available on GitHub as well as a package on npm.

Table of Contents

License

This library is released under the terms of the Apache 2.0 license. See License for more information.

Library Prerequisites

Installation

This library is released on npm.

npm

Install with npm install viber-bot --save

Express

If you are already using express or equivalent, you can do the following:

app.use("/viber/webhook", bot.middleware());

Please revisit app.use() documentation. For more information see ViberBot.middleware().

Let’s get started!

Creating a basic Viber bot is simple:

  1. Import viber-bot library to your project
  2. Create a Public Account and use the API key from https://developers.viber.com
  3. Configure your bot as described in the documentation below
  4. Add the bot as middleware to your server with bot.middleware()
  5. Start your web server
  6. Call setWebhook(url) with your web server url

Creating an echo Bot

Firstly, let’s import and configure our bot:

'use strict';

const ViberBot  = require('viber-bot').Bot;
const BotEvents = require('viber-bot').Events;

const bot    = new ViberBot({
	authToken: YOUR_AUTH_TOKEN_HERE,
	name: "EchoBot",
	avatar: "http://viber.com/avatar.jpg" // It is recommended to be 720x720, and no more than 100kb.
});

// Perfect! Now here's the key part:
bot.on(BotEvents.MESSAGE_RECEIVED, (message, response) => {
	// Echo's back the message to the client. Your bot logic should sit here.
	response.send(message);
});

// Wasn't that easy? Let's create HTTPS server and set the webhook:
const https = require('https');
const port  = process.env.PORT || 8080;

// Viber will push messages sent to this URL. Web server should be internet-facing.
const webhookUrl = process.env.WEBHOOK_URL;

const httpsOptions = { key: ... , cert: ... , ca: ... }; // Trusted SSL certification (not self-signed).
https.createServer(httpsOptions, bot.middleware()).listen(port, () => bot.setWebhook(webhookUrl));

Using Winston logger

We provide an option to use Winston logger with our library. The only requirement is that you use Winston >= 2.0.0.

'use strict';

const ViberBot  = require('viber-bot').Bot;
const winston   = require('winston');
const toYAML    = require('winston-console-formatter'); // makes the output more friendly

function createLogger() {
	const logger = new winston.Logger({ level: "debug" }); // We recommend DEBUG for development
	logger.add(winston.transports.Console, toYAML.config());
	return logger;
}

const logger = createLogger();
const bot    = new ViberBot({
	logger: logger,
	authToken: ...,
	...
});

Do you supply a basic router for text messages?

Well funny you ask. Yes we do. But a word of warning - messages sent to your router callback will also be emitted to the BotEvents.MESSAGE_RECEIVED event.

const TextMessage = require('viber-bot').Message.Text;

// A simple regular expression to answer messages in the form of 'hi' and 'hello'.
bot.onTextMessage(/^hi|hello$/i, (message, response) =>
    response.send(new TextMessage(`Hi there ${response.userProfile.name}. I am ${bot.name}`)));

Have you noticed how we created the TextMessage instance? There’s a all bunch of message types you should get familiar with.

Creating them is easy! Every message object has its own unique constructor corresponding to its API implementation. Click on each type in the list to find out more. Check out the full API documentation for more advanced uses.

API

Viber Bot

require('viber-bot').Bot

An event emitter, emitting events described here.

New ViberBot()

Param Type Description
options.logger object Winston logger
options.authToken string Viber Auth Token
options.name string Your BOT Name
options.avatar string Avatar URL. No more than 100kb.
options.registerToEvents array example: [“message”, “delivered”]

bot.on(handler)

require('viber-bot').Events

Param Type
handler EventHandlerCallback
message Message Object
response Response Object
err Error Object

Subscribe to events:

Example

bot.on(BotEvents.MESSAGE_RECEIVED, (message, response) => ... );
bot.on(BotEvents.MESSAGE_SENT, (message, userProfile) => ... );
bot.on(BotEvents.CONVERSATION_STARTED, (userProfile, isSubscribed, context, onFinish) => ... );
bot.on(BotEvents.ERROR, err => ... );
bot.on(BotEvents.UNSUBSCRIBED, response => ... );
bot.on(BotEvents.SUBSCRIBED, response =>
    response.send(`Thanks for subscribing, ${response.userProfile.name}`));

bot.getBotProfile()

Returns a promise.JSON with the following JSON.

bot.getBotProfile().then(response => console.log(`Public Account Named: ${response.name}`));

bot.getUserDetails(userProfile)

Param Type Description
userProfile UserProfile UserProfile object

The getUserDetails function will fetch the details of a specific Viber user based on his unique user ID. The user ID can be obtained from the callbacks sent to the PA regrading user’s actions. This request can be sent twice during a 12 hours period for each user ID.

Returns a promise.JSON.

bot.onSubscribe(response => bot.getUserDetails(response.userProfile)
        .then(userDetails => console.log(userDetails)));

bot.getOnlineStatus(viberUserIds)

Param Type Description
viberUserIds array of strings Collection of Viber user ids

Returns a promise.JSON.

bot.getOnlineStatus(["a1, "a2"]).then(onlineStatus => console.log(onlineStatus));

bot.setWebhook(url)

Param Type Description
url string Trusted SSL Certificate

Returns a promise.JSON.

bot.setWebhook("https://my.bot/incoming").then(() => yourBot.doSomething()).catch(err => console.log(err));

bot.sendMessage(userProfile, messages, [optionalTrackingData])

Param Type Description
userProfile UserProfile UserProfile object
messages object or array Can be Message object or array of Message objects
[optionalTrackingData] JSON Optional. JSON Object. Returned on every message sent by the client

Note: When passing array of messages to sendMessage, messages will be sent by explicit order (the order which they were given to the sendMessage method). The library will also cancel all custom keyboards except the last one, sending only the last message keyboard.

Returns a promise.ARRAY array of message tokens.

// Single message
const TextMessage = require('viber-bot').Message.Text;
bot.sendMessage(userProfile, new TextMessage("Thanks for shopping with us"));

// Multiple messages
const UrlMessage  = require('viber-bot').Message.Url;
bot.sendMessage(userProfile, [
    new TextMessage("Here's the product you've requested:"),
    new UrlMessage("http://my.ecommerce.site/product1"),
    new TextMessage("Shipping time: 1-3 business days")
]);

bot.postToPublicChat(userProfile, messages)

The Viber post API allows the PA owner to post a message in the Public Account’s public chat.

Param Type Description
userProfile UserProfile UserProfile object
messages object or array Can be Message object or array of Message objects

Note: When passing array of messages to postToPublicChat, messages will be sent by explicit order (the order which they were given to the postToPublicChat method).

Note: This method does not support keyboard attachment.

Returns a promise.ARRAY array of message tokens.

// Single message
const TextMessage = require('viber-bot').Message.Text;
bot.postToPublicChat(userProfile, new TextMessage("Thanks for shopping with us"));

// Multiple messages
const UrlMessage  = require('viber-bot').Message.Url;
bot.postToPublicChat(userProfile, [
    new TextMessage("Here's the product you've requested:"),
    new UrlMessage("http://my.ecommerce.site/product1"),
    new TextMessage("Shipping time: 1-3 business days")
]);

bot.middleware()

Returns a middleware implementation to use with http/https.

const https = require('https');
https.createServer({ key: ... , cert: ... , ca: ... }, bot.middleware()).listen(8080);

bot.onTextMessage(regex, handler)

Param Type
regex regular expression
handler TextMessageHandlerCallback

TextMessageHandlerCallback: function (message, response) {}
bot.onTextMessage(/^hi|hello$/i, (message, response) =>
    response.send(new TextMessage(`Hi there ${response.userProfile.name}. I am ${bot.name}`)));

bot.onError(handler)

Param Type
handler ErrorHandlerCallback

ErrorHandlerCallback: function (err) {}
bot.onError(err => logger.error(err));

bot.onConversationStarted(userProfile, isSubscribed, context, onFinish)

Param Type Description
userProfile UserProfile UserProfile object
isSubscribed boolean Indicates whether a user is already subscribed
context String Any additional parameters added to the deep link used to access the conversation passed as a string
onFinish ConversationStartedOnFinishCallback When called, a Message will be sent to the client

Conversation started event fires when a user opens a conversation with the PA using the “message” button (found on the PA’s info screen) or using a deep link.

This event is not considered a subscribe event and doesn’t allow the PA to send messages to the user; however, it will allow sending one “welcome message” to the user.

ConversationStartedOnFinishCallback: function (responseMessage, optionalTrackingData) {}

The ConversationStartedOnFinishCallback accepts null and MessageObject only. Otherwise, an exception is thrown.

bot.onConversationStarted((userProfile, isSubscribed, context, onFinish) =>
	onFinish(new TextMessage(`Hi, ${userProfile.name}! Nice to meet you.`)));

bot.onConversationStarted((userProfile, isSubscribed, context, onFinish) =>
    onFinish(new TextMessage(`Thanks`), { saidThanks: true }));

bot.onSubscribe(handler)

Param Type
handler SubscribeResponseHandlerCallback

SubscribeResponseHandlerCallback: function (response) {}
bot.onSubscribe(response => console.log(`Subscribed: ${response.userProfile.name}`));

bot.onUnsubscribe(handler)

Param Type
handler UnsubscribeResponseHandlerCallback

UnsubscribeResponseHandlerCallback: function (userId) {}
bot.onUnsubscribe(userId => console.log(`Unsubscribed: ${userId}`));

Response object

Members:

Param Type Notes
userProfile UserProfile

UserProfile object

Members:

Param Type Notes
id string
name string
avatar string Optional Avatar URL
country string currently set in CONVERSATION_STARTED event only
language string currently set in CONVERSATION_STARTED event only

Message Object

const TextMessage     = require('viber-bot').Message.Text;
const UrlMessage      = require('viber-bot').Message.Url;
const ContactMessage  = require('viber-bot').Message.Contact;
const PictureMessage  = require('viber-bot').Message.Picture;
const VideoMessage    = require('viber-bot').Message.Video;
const LocationMessage = require('viber-bot').Message.Location;
const StickerMessage  = require('viber-bot').Message.Sticker;
const RichMediaMessage  = require('viber-bot').Message.RichMedia;
const KeyboardMessage  = require('viber-bot').Message.Keyboard;

Common Members for Message interface:

Param Type Description
timestamp string Epoch time
token string Sequential message token
trackingData JSON JSON Tracking Data from Viber Client

Common Constructor Arguments Message interface:

Param Type Description
optionalKeyboard JSON Writing Custom Keyboards
optionalTrackingData JSON Data to be saved on Viber Client device, and sent back each time message is received

TextMessage object

Member Type
text string
const message = new TextMessage(text, [optionalKeyboard], [optionalTrackingData]);
console.log(message.text);

UrlMessage object

Member Type
url string
const message = new UrlMessage(url, [optionalKeyboard], [optionalTrackingData]);
console.log(message.url);

ContactMessage object

Member Type
contactName string
contactPhoneNumber string
const message = new ContactMessage(contactName, contactPhoneNumber, [optionalAvatar], [optionalKeyboard], [optionalTrackingData]);
console.log(`${message.contactName}, ${message.contactPhoneNumber}`);

PictureMessage object

Member Type
url string
text string
thumbnail string
const message = new PictureMessage(url, [optionalText], [optionalThumbnail], [optionalKeyboard], [optionalTrackingData]);
console.log(`${message.url}, ${message.text}, ${message.thumbnail}`);

VideoMessage object

Member Type
url string
size int
thumbnail string
duration int
const message = new VideoMessage(url, size, [optionalText], [optionalThumbnail], [optionalDuration], [optionalKeyboard], [optionalTrackingData]);
console.log(`${message.url}, ${message.size}, ${message.thumbnail}, ${message.duration}`);

LocationMessage object

Member Type
latitude float
longitude float
const message = new LocationMessage(latitude, longitude, [optionalKeyboard], [optionalTrackingData]);
console.log(`${message.latitude}, ${message.longitude}`);

StickerMessage object

Member Type
stickerId int
const message = new StickerMessage(stickerId, [optionalKeyboard], [optionalTrackingData]);
console.log(message.stickerId);

FileMessage object

Member Type
url string
sizeInBytes int
filename string
const message = new FileMessage(url, sizeInBytes, filename, [optionalKeyboard], [optionalTrackingData]);
console.log(`${message.url}, ${message.sizeInBytes}, ${message.filename}`);

RichMediaMessage object

Member Type
richMedia Object
const SAMPLE_RICH_MEDIA = {
	"ButtonsGroupColumns": 6,
	"ButtonsGroupRows": 2,
	"BgColor": "#FFFFFF",
	"Buttons": [{
		"ActionBody": "http://www.website.com/go_here",
		"ActionType": "open-url",
		"BgMediaType": "picture",
		"Image": "http://www.images.com/img.jpg",
		"BgColor": "#000000",
		"TextOpacity": 60,
		"Rows": 4,
		"Columns": 6
	}, {
		"ActionBody": "http://www.website.com/go_here",
		"ActionType": "open-url",
		"BgColor": "#85bb65",
		"Text": "Buy",
		"TextOpacity": 60,
		"Rows": 1,
		"Columns": 6
	}]
};

const message = new RichMedia(SAMPLE_RICH_MEDIA, [optionalKeyboard], [optionalTrackingData]);

KeyboardMessage object

Member Type
keyboard JSON

const SAMPLE_KEYBOARD = {
	"Type": "keyboard",
	"Revision": 1,
	"Buttons": [
		{
			"Columns": 3,
			"Rows": 2,
			"BgColor": "#e6f5ff",
			"BgMedia": "http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg",
			"BgMediaType": "picture",
			"BgLoop": true,
			"ActionType": "reply",
			"ActionBody": "Yes"
		}
	]
};

const message = new KeyboardMessage(SAMPLE_KEYBOARD, [optionalTrackingData]);

Sample project

We’ve created the Is It Up sample project to help you get started.

Community

Join the conversation on Gitter.


Viber Python Bot API

Use this library to develop a bot for Viber platform. The library is available on GitHub as well as a package on PyPI.

This package can be imported using pip by adding the following to your requirements.txt:

viberbot==1.0.11

Table of Contents

License

This library is released under the terms of the Apache 2.0 license. See License for more information.

Library Prerequisites

Let’s get started!

Installing

Creating a basic Viber bot is simple:

  1. Install the library though pip pip install viberbot
  2. Import viberbot.api library to your project
  3. Create a Public Account and use the API key from https://developers.viber.com
  4. Configure your bot as described in the documentation below
  5. Start your web server
  6. Call set_webhook(url) with your web server url

A simple Echo Bot

Firstly, let’s import and configure our bot

from viberbot import Api
from viberbot.api.bot_configuration import BotConfiguration

bot_configuration = BotConfiguration(
	name='PythonSampleBot',
	avatar='http://viber.com/avatar.jpg',
	auth_token='YOUR_AUTH_TOKEN_HERE'
)
viber = Api(bot_configuration)

Create an HTTPS server

Next thing you should do is starting a https server. and yes, as we said in the prerequisites it has to be https server. Create a server however you like, for example with Flask:

from flask import Flask, request, Response

app = Flask(__name__)

@app.route('/incoming', methods=['POST'])
def incoming():
	logger.debug("received request. post data: {0}".format(request.get_data()))
	# handle the request here
	return Response(status=200)

context = ('server.crt', 'server.key')
app.run(host='0.0.0.0', port=443, debug=True, ssl_context=context)

Setting a webhook

After the server is up and running you can set a webhook. Viber will push messages sent to this URL. web server should be internet-facing.

viber.set_webhook('https://mybotwebserver.com:443/')

Logging

This library uses the standard python logger. If you want to see its logs you can configure the logger:

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

Do you supply a basic types of messages?

Well, funny you ask. Yes we do. All the Message types are located in viberbot.api.messages package. Here’s some examples:

from viberbot.api.messages import (
    TextMessage,
    ContactMessage,
    PictureMessage,
    VideoMessage
)
from viberbot.api.messages.data_types.contact import Contact

# creation of text message
text_message = TextMessage(text="sample text message!")

# creation of contact message
contact = Contact(name="Viber user", phone_number="0123456789")
contact_message = ContactMessage(contact=contact)

# creation of picture message
picture_message = PictureMessage(text="Check this", media="http://site.com/img.jpg")

# creation of video message
video_message = VideoMessage(media="http://mediaserver.com/video.mp4", size=4324)

Have you noticed how we created the TextMessage? There’s a all bunch of message types you should get familiar with.

Creating them is easy! Every message object has it’s own unique constructor corresponding to it’s API implementation, click on them to see it! Check out the full API documentation for more advanced uses.

Let’s add it all up and reply with a message!

from flask import Flask, request, Response
from viberbot import Api
from viberbot.api.bot_configuration import BotConfiguration
from viberbot.api.messages import VideoMessage
from viberbot.api.messages.text_message import TextMessage
import logging

from viberbot.api.viber_requests import ViberConversationStartedRequest
from viberbot.api.viber_requests import ViberFailedRequest
from viberbot.api.viber_requests import ViberMessageRequest
from viberbot.api.viber_requests import ViberSubscribedRequest
from viberbot.api.viber_requests import ViberUnsubscribedRequest

app = Flask(__name__)
viber = Api(BotConfiguration(
    name='PythonSampleBot',
    avatar='http://site.com/avatar.jpg',
    auth_token='445da6az1s345z78-dazcczb2542zv51a-e0vc5fva17480im9'
))


@app.route('/', methods=['POST'])
def incoming():
    logger.debug("received request. post data: {0}".format(request.get_data()))
    # every viber message is signed, you can verify the signature using this method
    if not viber.verify_signature(request.get_data(), request.headers.get('X-Viber-Content-Signature')):
        return Response(status=403)

    # this library supplies a simple way to receive a request object
    viber_request = viber.parse_request(request.get_data())

    if isinstance(viber_request, ViberMessageRequest):
        message = viber_request.message
        # lets echo back
        viber.send_messages(viber_request.sender.id, [
            message
        ])
    elif isinstance(viber_request, ViberSubscribedRequest):
        viber.send_messages(viber_request.get_user.id, [
            TextMessage(text="thanks for subscribing!")
        ])
    elif isinstance(viber_request, ViberFailedRequest):
        logger.warn("client failed receiving message. failure: {0}".format(viber_request))

    return Response(status=200)

if __name__ == "__main__":
    context = ('server.crt', 'server.key')
    app.run(host='0.0.0.0', port=443, debug=True, ssl_context=context)

As you can see there’s a bunch of Request types here’s a list of them.

Viber API

Api class

from viberbot import Api

New Api()

Param Type Description
bot_configuration object BotConfiguration

Api.set_webhook(url)

Param Type Description
url string Your web server url
webhook_events list optional list of subscribed events

Returns List of registered event_types.

event_types = viber.set_webhook('https://example.com/incoming')

Api.unset_webhook()

Returns None.

viber.unset_webhook()

Api.get_account_info()

Returns an object with the following JSON.

account_info = viber.get_account_info()

Api.verify_signature(request_data, signature)

Param Type Description
request_data string the post data from request
signature string sent as header X-Viber-Content-Signature

Returns a boolean suggesting if the signature is valid.

if not viber.verify_signature(request.get_data(), request.headers.get('X-Viber-Content-Signature')):
	return Response(status=403)

Api.parse_request(request_data)

Param Type Description
request_data string the post data from request

Returns a ViberRequest object.

There’s a list of ViberRequest objects

viber_request = viber.parse_request(request.get_data())

Api.send_messages(to, messages)

Param Type Description
to string Viber user id
messages list list of Message objects

Returns list of message tokens of the messages sent.

tokens = viber.send_messages(to=viber_request.get_sender().get_id(),
			     messages=[TextMessage(text="sample message")])

Api.post_messages_to_public_account(to, messages)

Param Type Description
sender string Viber user id
messages list list of Message objects

Returns list of message tokens of the messages sent.

tokens = viber.post_messages_to_public_account(sender=viber_request.get_sender().get_id(),
			     messages=[TextMessage(text="sample message")])

Api.get_online(viber_user_ids)

Param Type Description
viber_user_ids array of strings Array of Viber user ids

Returns a dictionary of users.

users = Api.get_online(["user1id", "user2id"])

Api.get_user_details(viber_user_id)

Param Type Description
viber_user_ids string Viber user id

The get_user_details function will fetch the details of a specific Viber user based on his unique user ID. The user ID can be obtained from the callbacks sent to the PA regrading user’s actions. This request can be sent twice during a 12 hours period for each user ID.

user_data = Api.get_user_details("userId")

Request object

Param Type Notes
event_type string according to EventTypes enum
timestamp long Epoch of request time

ViberConversationStartedRequest object

Inherits from ViberRequest

Conversation started event fires when a user opens a conversation with the PA using the “message” button (found on the PA’s info screen) or using a deep link.

This event is not considered a subscribe event and doesn’t allow the PA to send messages to the user; however, it will allow sending one “welcome message” to the user. See sending a welcome message below for more information.

Param Type Notes
event_type string always equals to the value of EventType.CONVERSATION_STARTED
message_token string Unique ID of the message
type string The specific type of conversation_started event.
context string Any additional parameters added to the deep link used to access the conversation passed as a string
user UserProfile the user started the conversation UserProfile
subscribed boolean Indicates whether a user is already subscribed

ViberDeliveredRequest object

Inherits from ViberRequest

Param Type Notes
event_type string always equals to the value of EventType.DELIVERED
message_token string Unique ID of the message
user_id string Unique Viber user id

ViberFailedRequest object

Inherits from ViberRequest

Param Type Notes
event_type string always equals to the value of EventType.FAILED
message_token string Unique ID of the message
user_id string Unique Viber user id
desc string Failure description

ViberMessageRequest object

Inherits from ViberRequest

Param Type Notes
event_type string always equals to the value of EventType.MESSAGE
message_token string Unique ID of the message
message Message Message object
sender UserProfile the user started the conversation UserProfile

ViberSeenRequest object

Inherits from ViberRequest

Param Type Notes
event_type string always equals to the value of EventType.SEEN
message_token string Unique ID of the message
user_id string Unique Viber user id

ViberSubscribedRequest object

Inherits from ViberRequest

Param Type Notes
event_type string always equals to the value of EventType.SUBSCRIBED
user UserProfile the user started the conversation UserProfile

ViberUnsubscribedRequest object

Inherits from ViberRequest

Param Type Notes
event_type string always equals to the value of EventType.UNSUBSCRIBED
user_id string Unique Viber user id

UserProfile object

Param Type Notes
id string
name string
avatar string Avatar URL
country string currently set in CONVERSATION_STARTED event only
language string currently set in CONVERSATION_STARTED event only

Message Object

Common Members for Message interface:

Param Type Description
timestamp long Epoch time
keyboard JSON keyboard JSON
trackingData JSON JSON Tracking Data from Viber Client

Common Constructor Arguments Message interface:

Param Type Description
optionalKeyboard JSON Writing Custom Keyboards
optionalTrackingData JSON Data to be saved on Viber Client device, and sent back each time message is received

TextMessage object

Member Type
text string
message = TextMessage(text="my text message")

URLMessage object

Member Type Description
media string URL string
message = URLMessage(media="http://my.siteurl.com");

ContactMessage object

Member Type
contact Contact
from viberbot.api.messages.data_types.contact import Contact

contact = Contact(name="Viber user", phone_number="+0015648979", avatar="http://link.to.avatar")
contact_message = ContactMessage(contact=contact)

PictureMessage object

Member Type Description
media string url of the message (jpeg only)
text string  
thumbnail string  
message = PictureMessage(media="http://www.thehindubusinessline.com/multimedia/dynamic/01458/viber_logo_JPG_1458024f.jpg", text="Viber logo")

VideoMessage object

Member Type Description
media string url of the video
size int  
thumbnail string  
duration int  
message = VideoMessage(media="http://site.com/video.mp4", size=21499)

LocationMessage object

Member Type
location Location
from viberbot.api.messages.data_types.location import Location

location = Location(lat=0.0, lon=0.0)
location_message = LocationMessage(location=location)

StickerMessage object

Member Type
sticker_id int
message = StickerMessage(sticker_id=40100);

FileMessage object

Member Type
media string
size long
file_name string
message = FileMessage(media=url, size=sizeInBytes, file_name=file_name)

RichMediaMessage object

Member Type
rich_media string (JSON)
SAMPLE_RICH_MEDIA = """{
  "BgColor": "#69C48A",
  "Buttons": [
    {
      "Columns": 6,
      "Rows": 1,
      "BgColor": "#454545",
      "BgMediaType": "gif",
      "BgMedia": "http://www.url.by/test.gif",
      "BgLoop": true,
      "ActionType": "open-url",
      "Silent": true,
      "ActionBody": "www.tut.by",
      "Image": "www.tut.by/img.jpg",
      "TextVAlign": "middle",
      "TextHAlign": "left",
      "Text": "<b>example</b> button",
      "TextOpacity": 10,
      "TextSize": "regular"
    }
  ]
}"""

SAMPLE_ALT_TEXT = "upgrade now!"

message = RichMediaMessage(rich_media=SAMPLE_RICH_MEDIA, alt_text=SAMPLE_ALT_TEXT);

KeyboardMessage object

Member Type
keyboard JSON
tracking_data JSON
message = KeyboardMessage(tracking_data=tracking_data, keyboard=keyboard)

Sending a welcome message

The Public Accounts API allows sending messages to users only after they subscribe to the PA. However, Viber will allow the PA to send one “welcome message” to a user as the user opens the conversation, before the user subscribes.

The welcome message will be sent as a response to a conversation_started callback, which will be received from Viber once the user opens the conversation with the Public Account. To learn more about this event and when is it triggered see Conversation started in the Callbacks section.

Welcome message flow

Sending a welcome message will be done according to the following flow:

  1. User opens 1-on-1 conversation with PA.
  2. Viber server send “conversation_started” even to PA’s webhook.
  3. PA receives the “conversation_started” and responds with an HTTP response which includes the welcome message as the response body.

The welcome message will be a JSON constructed according to the send_message requests structure, but without the receiver parameter. An example welcome message would look like this:

@app.route('/', methods=['POST'])
def incoming():
	viber_request = viber.parse_request(request.get_data())

	if isinstance(viber_request, ViberConversationStartedRequest) :
		viber.send_messages(viber_request.get_user().get_id(), [
			TextMessage(text="Welcome!")
		])

	return Response(status=200)

Community

Join the conversation on Gitter.


Viber REST API

Table of Contents

Getting Started

In order to implement the API you will need the following:

  1. An Active Viber account on a platform which supports PA (iOS/Android). This account will automatically be set as the PA administrator during the PA creation process.
  2. Active Public Account.
  3. Public Account authentication token - unique account identifier used to validate your account in all API requests. Once your account is created your authentication token will appear in the account’s “edit info” screen (for admins only). Each request posted to Viber by the public account will need to contain the token.
  4. Setup account webhook – this needs to be done once during the account setup process to define your webhook and the type of responses you would like to receive.

Supported platforms

Public accounts are currently supported on iOS and Android devices running Viber version 6.5 and above and on desktop from version 6.5.3.

Send and receive message flow

The following diagram describes the flow of sending and receiving messages by the public account. All API requests and callbacks mentioned in the diagram will be explained later in this document.

Authentication token

The authentication token (also known as application key) is a unique and secret account identifier. It is used to authenticate request in the Public Accounts API and to prevent unauthorized persons from sending requests on behalf of a Public Account. Each API request must include an HTTP Header called X-Viber-Auth-Token containing the account’s authentication token.

HTTP header

X-Viber-Auth-Token: 445da6az1s345z78-dazcczb2542zv51a-e0vc5fva17480im9

The authentication token is generated upon PA creation and can be viewed by the account’s admins in the “edit info” screen of their Public Account.

Note: Failing to send the authentication token in the header will result in an error with the “missing auth_token” message.

Webhooks

Once you have your token you will be able to set your account’s webhook. This webhook will be used for receiving callbacks & user messages from Viber.

Setting the webhook will be done by calling the set_webhook API with a valid & certified URL. For security reasons only URLs with valid and official SSL certificate from a trusted CA will be allowed. This action defines the account’s webhook and the type of events the account wants to be notified about.

Once a set_webhook request is sent Viber will send a callback to the webhook to check its availability and return a response to the user.

Note that once you set your webhook the 1-on-1 conversation with your account will become available. To disable 1-on-1 conversation with your account you’ll need to remove your webhook – see removing your webhook below.

Setting a Webhook

Resource URL

https://chatapi.viber.com/pa/set_webhook

Post data

{  
   "url": "https://my.host.com",  
   "event_types": ["delivered", "seen", "failed", "subscribed", "unsubscribed", "conversation_started"]  
}

Post parameters

Name Description Validation
url required. PA webhook URL to receive callbacks & messages from users Webhook URL must use SSL Note: Viber doesn’t support self signed certificates
event_types optional. Indicates the types of Viber events that the PA owner would like to be notified about. Don’t include this parameter in your request to get all events Possible values: delivered, seen, failed, subscribed, unsubscribed and conversation_started

Set webhook Response

{  
    "status": 0,  
    "status_message": "ok",  
    "event_types": ["delivered", "seen", "failed", "subscribed",  "unsubscribed", "conversation_started"]  
}

Response parameters

Name Description Possible values
status Action result 0 for success. In case of failure – appropriate failure status number. See error codes table for additional information
status_message ok or failure reason Success: ok. Failure: invalidUrl, invalidAuthToken, badData, missingData and failure. See error codes table for additional information
event_types List of event types you will receive a callback for. Should return the same values sent in the request delivered, seen, failed, subscribed, unsubscribed and conversation_started

Event types filtering

The event_types parameter allows Public Accounts to choose which events they would get a callback for.
The following events are mandatory and can’t be filtered out: message, subscribed and unsubscribed.
The following events can be filtered out during the set_webhook request: delivered, seen, failed and conversation_started.
Sending a set_webhook request with no event_types parameter means getting all events.
Sending a set_webhook request with empty event_types list ("event_types": []) means getting only mandatory events. See callbacks section for full callbacks events information.

Set webhook callback

For each set_webhook request Viber will send a callback to the webhook URL to confirm it is available. The expected HTTP response to the callback is 200 OK – any other response will mean the webhook is not available. If the webhook is not available the set_webhook response sent to the user will be status 1: invalidUrl.

Callback data
{  
	"event":"webhook",  
	"timestamp":1457764197627,  
	"message_token":4912661846655238145  
}

Callback parameters

Name Description Possible values
event Callback type – which event triggered the callback webhook
timestamp Time of the event that triggered the callback Epoch time
message_token Unique ID of the message  

Removing your webhook

Once you set a webhook to your PA your 1-on-1 conversation button will appear and users will be able to access it.
At the moment there is no option to disable the 1-on-1 conversation from the PA settings, so to disable this option you’ll need to remove the webhook you set for the account. Removing the webhook is done by Posting a set_webhook request with an empty webhook string.

Resource URL

https://chatapi.viber.com/pa/set_webhook

Post data

{  
   "url": ""  
}

Post parameters

Name Description
url required. PA webhook URL to receive callbacks & messages from users. In this case, use an empty string to remove any previously set webhook

Send Message

The send_message API allows PAs to send messages to Viber users who subscribe to the PA. Sending a message to a user will be possible only after the user has subscribed to the PA by pressing the subscribe button or by sending a message to the PA (see subscribed callback for additional information).

The API supports a variety of message types: text, picture, video, file, location, contact and URL. Specific post data examples and required parameters for each message type are given below.

Validation

Maximum total JSON size of the request is 30kb.

Resource URL

https://chatapi.viber.com/pa/send_message

General send message parameters

The following parameters are available for all message types:

Name Description Validation
receiver Unique Viber user id required, subscribed valid user id
type Message type required. Available message types: text, picture, video, file, location, contact, sticker, carousel content and url
sender.name The sender’s name to display required. Max 28 characters
sender.avatar The sender’s avatar URL optional. Avatar size should be no more than 100 kb. Recommended 720x720
tracking_data Allow PA to track messages and user’s replies. Sent tracking_data value will be passed back with user’s reply optional. max 4000 characters
min_api_version Minimal API version required by clients for this message (default 1) optional. client version support the API version

Message types

Below is a list of all supported message types with post data examples.

Text message

Post data
{
	"receiver": "01234567890A=",
	"min_api_version": 1,
	"sender": {
		"name": "John McClane",
		"avatar": "http://avatar.example.com"
	},
	"tracking_data": "tracking data",
	"type": "text",
	"text": "a message from pa"
}

Post parameters

Name Description Validation
type Message type required. text
text The text of the message required

Picture message

Post data
{
   "receiver": "01234567890A=",
	"min_api_version": 1,
   "sender":
   {
       "name": "John McClane",
       "avatar": "http://avatar.example.com"
   },
   "tracking_data": "tracking data",
    "type": "picture",
   "text": "Photo description",
   "media": "http://www.images.com/img.jpg",
   "thumbnail": "http://www.images.com/thumb.jpg"
}

Post parameters

Name Description Validation
type Message type required. picture
text Description of the photo. Can be an empty string if irrelevant required. Max 120 characters
media URL of the image (JPEG) required. Max size 1 MB. Only JPEG format is supported. Other image formats as well as animated GIFs can be sent as URL messages or file messages
thumbnail URL of a reduced size image (JPEG) optional. Max size 100 kb. Recommended: 400x400. Only JPEG format is supported

Video message

Post data
{
	"receiver": "01234567890A=",
	"min_api_version": 1,
	"sender": {
		"name": "John McClane",
		"avatar": "http://avatar.example.com"
	},
	"tracking_data": "tracking data",
	"type": "video",
	"media": "http://www.images.com/video.mp4",
	"thumbnail": "http://www.images.com/thumb.jpg",
	"size": 10000,
	"duration": 10
}

Post parameters

Name Description Validation
type Message type required. video
media URL of the video (MP4, H264) required. Max size 50 MB. Only MP4 and H264 are supported
size Size of the video in bytes required
duration Video duration in seconds; will be displayed to the receiver optional. Max 180 seconds
thumbnail URL of a reduced size image (JPEG) optional. Max size 100 kb. Recommended: 400x400. Only JPEG format is supported

File message

Post data
{
	"receiver": "01234567890A=",
	"min_api_version": 1,
	"sender": {
		"name": "John McClane",
		"avatar": "http://avatar.example.com"
	},
	"tracking_data": "tracking data",
	"type": "file",
	"media": "http://www.images.com/file.doc",
	"size": 10000,
	"file_name": "name_of_file.doc"
}

Post parameters

Name Description Validation
type Message type required. file
media URL of the file required. Max size 50 MB. See forbidden file formats for unsupported file types
size Size of the file in bytes required
file_name Name of the file required. File name should include extension. Max 256 characters (including file extension). Sending a file without extension or with the wrong extension might cause the client to be unable to open the file

Contact message

Post data
{
	"receiver": "01234567890A=",
	"min_api_version": 1,
	"sender": {
		"name": "John McClane",
		"avatar": "http://avatar.example.com"
	},
	"tracking_data": "tracking data",
	"type": "contact",
	"contact": {
		"name": "Alex",
		"phone_number": "+972511123123"
	}
}

Post parameters

Name Description Validation
type Message type required. contact
contact.name Name of the contact required. Max 28 characters
contact.phone_number Phone number of the contact required. Max 18 characters

Location message

Post data
{
	"receiver": "01234567890A=",
	"min_api_version": 1,
	"sender": {
		"name": "John McClane",
		"avatar": "http://avatar.example.com"
	},
	"tracking_data": "tracking data",
	"type": "location",
	"location": {
		"lat": "37.7898",
		"lon": "-122.3942"
	}
}

Post parameters

Name Description Validation
type Message type required. location
location Location coordinates required. lat & lon within valid ranges - lat: ±90; lon: ±180

URL message

Post data
{
	"receiver": "01234567890A=",
	"min_api_version": 1,
	"sender": {
		"name": "John McClane",
		"avatar": "http://avatar.example.com"
	},
	"tracking_data": "tracking data",
	"type": "url",
	"media": "http://www.website.com/go_here"
}

Post parameters

Name Description Validation
type Message type required. url
media URL required. Max 2,000 characters

Sticker message

Post data
{
	"receiver": "01234567890A=",
	"min_api_version": 1,
	"sender": {
		"name": "John McClane",
		"avatar": "http://avatar.example.com"
	},
	"tracking_data": "tracking data",
	"type": "sticker",
	"sticker_id": 46105
}

Post parameters

Name Description Validation
type Message type required. sticker
sticker_id Unique Viber sticker ID. For examples visit the sticker IDs page  

The Carousel Content Message type allows a user to scroll through a list of items, each composed of an image, description and call to action button.

Note: Carousel Content Message is supported on devices running Viber version 6.7 and above.

Post data
{
  "auth_token": "45768b9c626fa82e-d6232e2bd3dda8c6-33c8014a89a468d5",
  "receiver": "nsId6t9MWy3mq09RAeXiug==",
  "type": "rich_media",
  "min_api_version": 2,
  "rich_media": {
    "Type": "rich_media",
    "ButtonsGroupColumns": 6,
    "ButtonsGroupRows": 7,
    "BgColor": "#FFFFFF",
    "Buttons": [{
      "Columns": 6,
      "Rows": 3,
      "ActionType": "open-url",
      "ActionBody": "https://www.google.com",
      "Image": "http://html-test:8080/myweb/guy/assets/imageRMsmall2.png"
    }, {
      "Columns": 6,
      "Rows": 2,
      "Text": "<font color=#323232><b>Headphones with Microphone, On-ear Wired earphones</b></font><font color=#777777><br>Sound Intone </font><font color=#6fc133>$17.99</font>",
      "ActionType": "open-url",
      "ActionBody": "https://www.google.com",
      "TextSize": "medium",
        "TextVAlign": "middle",
        "TextHAlign": "left"
    }, {
      "Columns": 6,
      "Rows": 1,
      "ActionType": "reply",
      "ActionBody": "https://www.google.com",
      "Text": "<font color=#ffffff>Buy</font>",
      "TextSize": "large",
        "TextVAlign": "middle",
        "TextHAlign": "middle",
      "Image": "https://s14.postimg.org/4mmt4rw1t/Button.png"
    }, {
      "Columns": 6,
      "Rows": 1,
      "ActionType": "reply",
      "ActionBody": "https://www.google.com",
      "Text": "<font color=#8367db>MORE DETAILS</font>",
      "TextSize": "small",
        "TextVAlign": "middle",
        "TextHAlign": "middle"
    }, {
      "Columns": 6,
      "Rows": 3,
      "ActionType": "open-url",
      "ActionBody": "https://www.google.com",
      "Image": "https://s16.postimg.org/wi8jx20wl/image_RMsmall2.png"
    }, {
      "Columns": 6,
      "Rows": 2,
      "Text": "<font color=#323232><b>Hanes Men's Humor Graphic T-Shirt</b></font><font color=#777777><br>Hanes</font><font color=#6fc133>$10.99</font>",
      "ActionType": "open-url",
      "ActionBody": "https://www.google.com",
      "TextSize": "medium",
        "TextVAlign": "middle",
        "TextHAlign": "left"
    }, {
      "Columns": 6,
      "Rows": 1,
      "ActionType": "reply",
      "ActionBody": "https://www.google.com",
      "Text": "<font color=#ffffff>Buy</font>",
      "TextSize": "large",
        "TextVAlign": "middle",
        "TextHAlign": "middle",
      "Image": "https://s14.postimg.org/4mmt4rw1t/Button.png"
    }, {
      "Columns": 6,
      "Rows": 1,
      "ActionType": "reply",
      "ActionBody": "https://www.google.com",
      "Text": "<font color=#8367db>MORE DETAILS</font>",
      "TextSize": "small",
        "TextVAlign": "middle",
        "TextHAlign": "middle"
    }]
  }
}

Post parameters

Name Description Possible values
alt_text Backward compatibility text, limited to 7,000 characters  
rich_media.ButtonsGroupColumns Number of columns per carousel content block. Default 6 columns 1 - 6
rich_media.ButtonsGroupRows Number of rows per carousel content block. Default 7 rows 1 - 7
rich_media.Buttons Array of buttons Max of 6 * ButtonsGroupColumns * ButtonsGroupRows

Button element

Name Description Possible values
Columns Button column span. Default ButtonsGroupColumns 1..ButtonsGroupColumns
Rows Button row span. Default ButtonsGroupRows 1..ButtonsGroupRows

Keyboards

The public accounts API allows sending a custom keyboard using the send_message API, to supply the user with a set of predefined replies or actions. The keyboard can be attached to any message type or sent on it’s on. Once received, the keyboard will appear to the user instead of the device’s native keyboard. The keyboards are fully customizable and can be created and designed specifically for the PA’s needs. The client will always display the last keyboard that was sent to it.

Read the following article to learn more about keyboards.

Validation

Maximum total JSON size of the request is 30kb.

Resource URL

https://chatapi.viber.com/pa/send_message

Post data

Keyboards can be attached to any message type and be sent and displayed together. To attach a keyboard to a message simply add the keyboard’s parameters to the message JSON.
The example below shows a keyboard sent with a text message (note that the keyboard doesn’t contain all optional values).

{
	"receiver": "01234567890A=",
	"type": "text",
	"text": "a message from pa",
	"keyboard": {
		"Type": "keyboard",
		"DefaultHeight": true,
		"Buttons": [{
			"ActionType": "reply",
			"ActionBody": "reply to PA",
			"Text": "Key text",
			"TextSize": "regular"
		}]
	}
}

Get Account Info

The get_account_info request will fetch the public account’s details as registered in Viber. The account admin will be able to edit most of these details from his Viber client.

Resource URL

https://chatapi.viber.com/pa/get_account_info

Post data

{  
}

Response

{  
   "status": 0,  
   "status_message": "ok",  
   "id": "pa:75346594275468546724",  
   "name": "account name",  
   "uri": "accountUri",  
   "icon": "http://example.com",  
   "background": "http://example.com",  
   "category": "category",  
   "subcategory": "sub category",  
   "location": {  
       "lon": 0.1,  
       "lat": 0.2  
   },  
   "country": "UK",  
   "webhook": "https://my.site.com", 
	"event_types": ["delivered", "seen"],
	"subscribers_count": 35, 
   "members": [  
       {  
           "id": "01234567890A=",  
           "name": "my name",  
           "avatar": "http://example.com",  
           "role": "admin"  
       }  
   ]  
}

Response parameters

Name Description Possible values
status Action result 0 for success. In case of failure – appropriate failure status number. See error codes table for additional information
status_message ok or failure reason Success: ok. Failure: invalidUrl, invalidAuthToken, badData, missingData and failure. See error codes table for additional information
id Unique numeric id of the Public account  
name PA name Max 75 characters
uri Unique URI of the Public Account  
icon PA icon URL JPEG, 720x720, size no more than 512 kb
background Conversation background URL JPEG, max 1920x1920, size no more than 512 kb
category PA category  
subcategory PA sub-category  
location PA location (coordinates). Will be used for finding PA near me lat & lon coordinates
country PA country 2 letters country code - ISO ALPHA-2 Code
webhook PA registered webhook webhook URL
event_types PA registered events – as set by set_webhook request delivered, seen, failed and conversation_started
subscribers_count Number of subscribers  
members Members of the PA’s public chat id, name, avatar, role for each PC member (admin/participant)

Get User Details

The get_user_details request will fetch the details of a specific Viber user based on his unique user ID. The user ID can be obtained from the callbacks sent to the PA regrading user’s actions. This request can be sent twice during a 12 hours period for each user ID.

Resource URL

https://chatapi.viber.com/pa/get_user_details

Post data

{
   "id": "01234567890A="
}

Post parameters

Name Description Validation
id Unique Viber user id required. subscribed valid user id

Response

{
	"status": 0,
	"status_message": "ok",
	"message_token": 4912661846655238145,
	"user": {
		"id": "01234567890A=",
		"name": "John McClane",
		"avatar": "http://avatar.example.com",
		"country": "UK",
		"language": "en",
		"primary_device_os": "android 7.1",
		"api_version": 1,
		"viber_version": "6.5.0",
		"mcc": 1,
		"mnc": 1,
		"device_type": "iPhone9,4"
	}
}

Response parameters

Name Description Possible values
status Action result 0 for success. In case of failure – appropriate failure status number. See error codes table for additional information
status_message ok or failure reason Success: ok. Failure: invalidUrl, invalidAuthToken, badData, receiverNoSuitableDevice, missingData and failure. See error codes table for additional information
message_token Unique id of the message  
user.id Unique Viber user id  
user.name User’s Viber name  
user.avatar URL of the user’s avatar  
user.country User’s country code 2 letters country code - ISO ALPHA-2 Code
user.language User’s phone language. Will be returned according to the device language ISO 639-1
user.primary_device_os The operating system type and version of the user’s primary device.  
user.api_version Max API version, matching the most updated user’s device Currently only 1. Additional versions will be added in the future
user.viber_version The Viber version installed on the user’s primary device  
user.mcc Mobile country code  
user.mnc Mobile network code  
user.device_type The user’s device type  

Get Online

The get_online request will fetch the online status of a given subscribed PA members. The API supports up to 100 user id per request and those users must be subscribed to the PA.

Resource URL

https://chatapi.viber.com/pa/get_online

Post data

{
   "ids" : ["01234567890=", "01234567891=", ... "01234567893="]
}

Post parameters

Name Description Validation
ids Unique Viber user id required. 100 ids per request

Response

{
	"status": 0,
	"status_message": "ok",
	"users": [{
		"id": "01234567890=",
		"online_status": 0,
		"online_status_message": "online"
	}, {
		"id": "01234567891=",
		"online_status": 1,
		"online_status_message": "offline",
		"last_online": 1457764197627
	}, {
		"id": "01234567892=",
		"online_status": 2,
		"online_status_message": "undisclosed"
	}, {
		"id": "01234567893=",
		"online_status": 3,
		"online_status_message": "tryLater"
	}, {
		"id": "01234567894=",
		"online_status": 4,
		"online_status_message": "unavailable"
	}]
}

Response parameters

Name Description Possible values  
status Action result 0 for success. In case of failure – appropriate failure status number. See error codes table for additional information  
status_message ok or failure reason Success: ok. Failure: invalidUrl, invalidAuthToken, badData, missingData and failure. See error codes table for additional information  
user[x].id Unique Viber user id    
user[x].online_status Online status code 0 for online, 1 for offline, 2 for undisclosed - user set Viber to hide status, 3 for try later - internal error, 4 for unavailable - not a Viber user / unsubscribed / unregistered  
user[x]. online_status_message Online status message    

Post to Public Chat

The post API allows the PA owner to post a message in the Public Account’s public chat.

Note: The post API is fully supported on Android and iOS versions 6.5.3 and above. Versions 6.5 and below support the post API for text and link messages only. Other message types (picture, video, etc.) will be converted and displayed as a link leading to the message’s media. Support for the post API on Viber’s desktop version is currently in beta phase and may not be fully compatible with all message types.

Validation

Maximum total JSON size of the request is 30kb.

Resource URL

https://chatapi.viber.com/pa/post

Post data

The following example shows a post request of a text message. For other message types see possible message types below.

{
	"from": "01234567890A=",
	"sender": {
		"name": "John McClane",
		"avatar": "http://avatar.example.com"
	},
	"type": "text",
	"text": "a message from pa"
}

Post parameters

Name Description Validation
from Unique Viber user ID of one of the account’s admins. A list of admins and IDs is available in get_account_info response Valid user ID of an account admin
type Message type required. Available message types: text, picture, video, file, location, contact, sticker and url
sender.name The sender’s name to display optional. Max 28 characters
sender.avatar The sender’s avatar URL optional. Avatar size should be no more than 100 kb. Recommended 720x720

Possible message types

The posted messages can be of all types supported by the send_message API: text, picture, video, file, location, contact, sticker and url.

The type of the message will be set by the type parameter and the content of message will be sent according to same parameters and logic as send_message requests (see send message section for more details.

Note: This method does not support keyboard attachment.

Callbacks

Each callback will contain a signature on the JSON passed to the callback. The signature is HMAC with SHA256 that will use the authentication token as the key and the JSON as the value. The result will be passed as HTTP Header X-Viber-Content-Signature so the receiver can determine the origin of the message.

Re-try logic

In case the webhook is offline Viber will re-try to deliver the callback several times for up to an hour until HTTP status code 200 is received.

Input

Key:

auth_token - 4453b6ac12345678-e02c5f12174805f9-daec9cbb5448c51f

Value:

{
	"event": "delivered",
	"timestamp": 1457764197627,
	"message_token": 491266184665523145,
	"user_id": "01234567890A="
}

Output

HTTP header

X-Viber-Content-Signature: 9d3941b33d45c165400d84dba9328ee0b687a5a18b347617091be0a56d  

Subscribed

Before a PA can send messages to a user, the user will need to subscribe to the PA. Subscribing can take place in one of two ways:

  1. User sends message to the PA - when a user sends its first message to a PA the user will be automatically subscribed to the PA. Sending the first message will not trigger a subscribe callback, only a message callback (see receive message from user section).
  2. Subscribed event is sent to the PA - user clicks a subscribe button which triggers the subscribe callback as described below.

Note: A subscribe event will delete any context or tracking_data information related to the conversation. This means that if a user had a conversation with a service and then chose to unsubscribe and subscribe again, a new conversation will be started without any information related to the old conversation.

Callback data

{
	"event": "subscribed",
	"timestamp": 1457764197627,
	"user": {
		"id": "01234567890A=",
		"name": "John McClane",
		"avatar": "http://avatar.example.com",
		"country": "UK",
		"language": "en",
		"api_version": 1
	},
	"message_token": 4912661846655238145
}

Callback parameters

Name Description Possible values
event Callback type - which event triggered the callback subscribed
timestamp Time of the event that triggered the callback Epoch time
user.id Unique Viber user id  
user.name User’s Viber name  
user.avatar URL of user’s avatar  
user.country User’s 2 letter country code ISO ALPHA-2 Code
user.language User’s phone language. Will be returned according to the device language ISO 639-1
user.api_version The maximal Viber version that is supported by all of the user’s devices  
message_token Unique ID of the message  

Unsubscribed

The user will have the option to unsubscribe from the PA. This will trigger an unsubscribed callback.

Callback data

{
	"event": "unsubscribed",
	"timestamp": 1457764197627,
	"user_id": "01234567890A=",
	"message_token": 4912661846655238145
}

Callback parameters

Name Description Possible values
event Callback type - which event triggered the callback unsubscribed
timestamp Time of the event that triggered the callback Epoch time
user_id Unique Viber user id  
message_token Unique ID of the message  

Conversation started

Conversation started event fires when a user opens a conversation with the PA using the “message” button (found on the PA’s info screen) or using a deep link.

This event is not considered a subscribe event and doesn’t allow the PA to send messages to the user; however, it will allow sending one “welcome message” to the user. See sending a welcome message below for more information.

Once a conversation_started callback is received, the service will be able to respond with a JSON containing same parameters as a send_message request. The receiver parameter is not mandatory in this case.

Callback data

{
	"event": "conversation_started",
	"timestamp": 1457764197627,
	"message_token": 4912661846655238145,
	"type": "open",
	"context": "context information",
	"user": {
		"id": "01234567890A=",
		"name": "John McClane",
		"avatar": "http://avatar.example.com",
		"country": "UK",
		"language": "en",
		"api_version": 1
	},
	"subscribed": false
}

Callback parameters

Name Description Possible values
event Callback type - which event triggered the callback conversation_started
timestamp Time of the event that triggered the callback Epoch time
message_token Unique ID of the message  
type The specific type of conversation_started event open. Additional types may be added in the future
context Any additional parameters added to the deep link used to access the conversation passed as a string. See deep link section for additional information  
user.id Unique Viber user id  
user.name User’s Viber name  
user.avatar URL of user’s avatar  
user.country User’s 2 letter country code ISO ALPHA-2 Code
user.language User’s phone language  
user.api_version Max API version, matching the most updated user’s device  
subscribed indicated whether a user is already subscribed true if subscribed and false otherwise

Sending a welcome message

The Public Accounts API allows sending messages to users only after they subscribe to the PA. However, Viber will allow the PA to send one “welcome message” to a user as the user opens the conversation, before the user subscribes.

The welcome message will be sent as a response to a conversation_started callback, which will be received from Viber once the user opens the conversation with the Public Account. To learn more about this event and when is it triggered see Conversation started in the Callbacks section.

Welcome message flow

Sending a welcome message will be done according to the following flow:

  1. User opens 1-on-1 conversation with PA.
  2. Viber server send “conversation_started” even to PA’s webhook.
  3. PA receives the “conversation_started” and responds with an HTTP response which includes the welcome message as the response body.

The welcome message will be a JSON constructed according to the send_message requests structure, but without the receiver parameter. An example welcome message would look like this:

{
	"sender": {
		"name": "John McClane",
		"avatar": "http://avatar.example.com"
	},
	"tracking_data": "tracking data",
	"type": "picture",
	"text": "Welcome to our bot!",
	"media": "http://www.images.com/img.jpg",
	"thumbnail": "http://www.images.com/thumb.jpg"
}

Note: The welcome message should be sent as the body of the HTTP response to the conversation_started event, and not to the send_message endpoint.

Message receipts callbacks

Viber offers message status updates for each message sent, allowing the PA to be notified when the message was delivered to the user’s device (delivered status) and when the conversation containing the message was opened (seen status).
If the message recipient is using their Viber account on multiple devices, each of the devices will return a delivered and a seen status. This means that several callbacks can be received for a single message.
If Viber is unable to deliver the message to the client it will try to deliver it for up to 14 days. If the message wasn’t delivered within the 14 days it will not be delivered and no “delivered” or “seen” callbacks will be received for it.

Callback data

Delivered
{
	"event": "delivered",
	"timestamp": 1457764197627,
	"message_token": 4912661846655238145,
	"user_id": "01234567890A="
}
Seen
{
	"event": "seen",
	"timestamp": 1457764197627,
	"message_token": 4912661846655238145,
	"user_id": "01234567890A="
}

Callback parameters

Name Description Possible values
event Callback type - which event triggered the callback delivered, seen
timestamp Time of the event that triggered the callback Epoch time
message_token Unique ID of the message  
user_id Unique Viber user id  

Failed callback

The “failed” callback will be triggered if a message has reached the client but failed any of the client validations.

Since some of the message validations take place on the server while the others take place on the client, some messages may only fail after reaching the client. In such cases the flow will be as follows:

  1. Message is sent.
  2. Response with status 0 is received to indicate a successful request.
  3. The message reaches the client and fails client validation.
  4. “Failed” callback is sent to the webhook, containing the unique message token and a string explaining the failure.

Such message will not be displayed to the receiver and no “delivered” or “seen” callbacks will be returned for it.

Callback data

{
	"event": "failed",
	"timestamp": 1457764197627,
	"message_token": 4912661846655238145,
	"user_id": "01234567890A=",
	"desc": "failure description."
}

Callback parameters

Name Description Possible values
event Callback type - which event triggered the callback failed
timestamp Time of the event that triggered the callback Epoch time
message_token Unique ID of the message  
user_id Unique Viber user id  
desc A string describing the failure  

Receive message from user

The Chat API allows the user to send messages to the PA. Excluding file type, all message types are supported for sending from PA to user and from user to PA. These include: text, picture, video, contact, URL and location. The following callback data describes the structure of messages sent from user to PA.

Callback data

{
	"event": "message",
	"timestamp": 1457764197627,
	"message_token": 4912661846655238145,
	"sender": {
		"id": "01234567890A=",
		"name": "John McClane",
		"avatar": "http://avatar.example.com",
		"country": "UK",
		"language": "en",
		"api_version": 1
	},
	"message": {
		"type": "text",
		"text": "a message to the service",
		"media": "http://example.com",
		"location": {
			"lat": 50.76891,
			"lon": 6.11499
		},
		"tracking_data": "tracking data"
	}
}

Callback general parameters

Name Description Possible values
event Callback type - which event triggered the callback message
timestamp Time of the event that triggered the callback Epoch time
message_token Unique ID of the message  
sender.id Unique Viber user id of the message sender  
sender.name Sender’s Viber name  
sender.avatar Sender’s avatar URL  
sender.country Sender’s 2 letter country code ISO ALPHA-2 Code
sender.language Sender’s phone language. Will be returned according to the device language ISO 639-1
sender.api_version The maximal Viber version that is supported by all of the user’s devices  
message Detailed in the chart below  

Callback message parameters

The callback message parameters depend on the type of message. For each message type, only the relevant parameters will be received.

Name Description Possible values
type Message type text, picture, video, file, sticker, contact, url and location
text The message text  
media URL of the message media - can be image, video, file and url. Image/Video/File URLs will have a TTL of 1 hour  
location Location coordinates lat & lon within valid ranges
contact name - contact’s username, phone_number - contact’s phone number and avatar as the avatar URL name - max 128 characters. Only one phone_number per contact can be sent
tracking_data Tracking data sent with the last message to the user  
media URL of the message media - can be image, video, file and url. Image/Video/File URLs will have a TTL of 1 hour  
file_name File name Relevant for file type messages
file_size File size in bytes Relevant for file type messages
duration Video length in seconds Relevant for video type messages
sticker_id Viber sticker id Relevant for sticker type messages

Message status

Once a 200 OK response is received from the PA, the message status will change to delivered on the user’s side. “Seen” status is not currently supported for messages sent from user to PA.

Error Codes

The following error codes will be returned with API responses. The status parameter will include the error code value while the status_message parameter will include the error name or a more specific string describing the error.

Value Name Description
0 ok Success
1 invalidUrl The webhook URL is not valid
2 invalidAuthToken The authentication token is not valid
3 badData There is an error in the request itself (missing comma, brackets, etc.)
4 missingData Some mandatory data is missing
5 receiverNotRegistered The receiver is not registered to Viber
6 receiverNotSubscribed The receiver is not subscribed to the PA
7 publicAccountBlocked The public account is blocked
8 publicAccountNotFound The account associated with the token is not a public account.
9 publicAccountSuspended The public account is suspended
10 webhookNotSet No webhook was set for the public account
11 receiverNoSuitableDevice The receiver is using a device or a Viber version that don’t support public accounts
12 tooManyRequests Rate control breach
13 apiVersionNotSupported Maximum supported PA version by all user’s devices is less than the minApiVersion in the message
14 incompatibleWithVersion minApiVersion is not compatible to the message fields
18 noPublicChat Failed to post to public account. The bot is missing a Public Chat interface
other General error General error

Note: Failing to send the authentication token in the header will result in an error with the missing auth_token message.

Forbidden File Formats

Extension Format Operating system(s)
ACTION Automator Action Mac OS
APK Application Android
APP Executable Mac OS
BAT Batch File Windows
BIN Binary Executable Windows, Mac OS, Linux
CMD Command Script Windows
COM Command File Windows
COMMAND Terminal Command Mac OS
CPL Control Panel Extension Windows
CSH C Shell Script Mac OS, Linux
EXE Executable Windows
GADGET Windows Gadget Windows
INF1 Setup Information File Windows
INS Internet Communication Settings Windows
INX InstallShield Compiled Script Windows
IPA Application iOS
ISU InstallShield Uninstaller Script Windows
JOB Windows Task Scheduler Job File Windows
JSE JScript Encoded File Windows
KSH Unix Korn Shell Script Linux
LNK File Shortcut Windows
MSC Microsoft Common Console Document Windows
MSI Windows Installer Package Windows
MSP Windows Installer Patch Windows
MST Windows Installer Setup Transform File Windows
OSX Executable Mac OS
OUT Executable Linux
PAF Portable Application Installer File Windows
PIF Program Information File Windows
PRG Executable GEM
PS1 Windows PowerShell Cmdlet Windows
REG Registry Data File Windows
RGS Registry Script Windows
RUN Executable Linux
SCT Windows Scriptlet Windows
SHB Windows Document Shortcut Windows
SHS Shell Scrap Object Windows
U3P U3 Smart Application Windows
VB VBScript File Windows
VBE VBScript Encoded Script Windows
VBS VBScript File Windows
VBSCRIPT Visual Basic Script Windows
WORKFLOW Automator Workflow Mac OS
WS Windows Script Windows
WSF Windows Script Windows

Developers FAQ

Table of Contents

General

Can I send messages based on users phone numbers?

Sending messages to users is done based on the user ID. The user ID is unique for each user and provided to you with any callback triggered by a user’s action. There is currently no option to send messages based on phone numbers.

Authentication Tokens

How do I get my token?

Your token is generated and provided to you during the Public Account creation process. As a Public Account administrator, you can always find the account token in the “edit info” page.

Can my token expire?

Tokens are permanent and do not expire unless changed by the Viber team.

Can I change my token?

Refreshing your token can only be done by Viber support team. If you believe your authentication token has been compromised please contact Viber support to get a new one.

Webhook

What happens if the webhook is not available?

In case the webhook is offline Viber will re-try to deliver the callback several times for up to an hour until HTTP status code 200 OK is received.

Can my Public Account have more than one webhook?

Only one webhook per Public Account is currently supported.

Can more than one Public Account use the same webhook?

The same webhook can be set for more than one Public Account.

Why am I not getting any callbacks to my webhook?

There are a few steps you can take if you’re not getting callbacks to your token:

Supported webhook certificates

The endpoint certificate authority should be on the Sun Java trusted root certificates list.

Account Subscribers

How do I get the user ID?

The user ID is available to you in all callbacks received from our server. Keep in mind that before you can message a user he must subscribe to your PA or send you a message.

Will the same user ID be valid when sending messages from all Public Accounts?

User ID is unique per user and per Public Account. This means that the same user will have different user IDs on each Public Account.

Can the user ID change or expire?

User IDs do not change or expire. Each user has a unique and permanent ID when communicating with a Public Account. The user ID will only change if the user activated Viber with a different number, as this will create a completely new Viber account. Keep in mind that the same user will have a different user ID on each Public Account.

Keyboards

What is the keyboards maximum size?

The maximum JSON size for all API requests is 30kb. The keyboard can contain up to 12 rows in portrait mode.

What happens if I send an invalid keyboard?

Most keyboard validations take place on the client. If the request is successfully sent to the client and then fails one of the client validations you will receive a “failed” callback. The flow for such a case will be as follows:

  1. Message is sent.
  2. Response with status 0 is received to indicate a successful request.
  3. The message reaches the client and fails client validation.
  4. Failed callback is sent to the webhook, containing the unique message token and a string explaining the failure.

I sent a few keyboards, which one will the user see?

Viber will always display the last keyboard sent to the user.


Public Account API Access – White Paper

Viber 6.5 introduced a new Public Account API, which third parties can use to send and receive messages between a Public Account (run by a company or service) and a Viber user.

Table of Contents

Using the Public Account API

Public Accounts contain two communications channels:

  1. Public Chats – Public communication channel from the Public Account visible to all of the Public Account’s followers. All information shared through this communications channel is publicly accessible by all the Public Account’s followers and open to free access via external API’s.
  2. Public Account API – Private encrypted communications channel between a Public Account and a subscribed Viber user. All information communicated over this channel can only be seen by the subscribed Viber user and the Public Account. It cannot be accessed by any 3rd party API.

When creating a new Public Account you will receive a Public Account token which is used for all communication with the Viber Back End.

In order to enable communication between the Viber Back End and the Public Account, the Public Account must call the set web hook request with the Public Account token providing the Public Account’s URL for receiving the web hook. There is also an optional parameter (v6.5.1 and up) to define which events it will receive (such as delivered and seen notifications when clients receive and read messages). Once the set web hook request is received by the Viber Back End, it will validate the URL and send a response.

Communication between Public Accounts and Viber users

All communication between Public Accounts and Viber users can only be initialized by the Viber user starting a new conversation or subscribing to the Public Account (opt–in) (in both cases the user will be subscribed to the Public Account). When a Viber user subscribes to the Public Account, the Public Account will receive the following information about the user:

Once a Viber user subscribes to the Public Account, the Public Account can send messages to the Viber user freely (not only in response to a message from the user). Viber users can unsubscribe at any time from the Public Account, which will immediately block any further communication from the Public Account to the user. All messages will include a unique message token and timestamp created by the Viber Back End and will be synchronized between all users’ devices. Messages sent to the Public Account will also include the user’s Viber name and avatar.

Security

Privacy

Successful delivery definition


Viber API Terms of Service

Thank you for using the Viber application programming interfaces (the “Viber APIs”). As used herein, the terms “you” and “your” refer to each administrator, developer and user of the Viber APIs. By using the Viber APIs, you agree to these Terms of Service (the “Terms of Service”) and the Viber Terms of Use (the “TOU”). If you use the Viber APIs as an interface to, or in conjunction with other Viber products or services, then the terms of those products or services will also apply. If you disagree with any of the terms below or the TOU, Viber does not grant you a license to use the Viber APIs. In the event of any inconsistency between these Terms of Service and the TOU, these Terms of Service control.

Viber Media S.a r.l., its subsidiaries and affiliated companies (collectively, “Viber,” “we,” “our,” or “us”) reserve the right to update and change, from time to time, these Terms of Service and all documents incorporated by reference, and Viber may change these Terms of Service by posting a new version without notice to you. Use of the Viber APIs after such change constitutes acceptance of such changes.

1. License
Subject to the restrictions set forth in these Terms of Service, Viber grants you a non-exclusive, worldwide, personal, non-transferable, non-assignable, non-sublicensable, royalty-free license to use the Viber APIs. All rights not expressly granted to you are reserved by Viber.

2. Use of the Viber APIs
(a) You will comply with all applicable law, regulation, and third party rights (including without limitation laws regarding the import or export of data or software, privacy, and local laws). You will not use the Viber APIs to encourage or promote illegal activity or violation of third party rights. You will not violate any other terms of use or agreements with Viber.

(b) You will only access (or attempt to access) the Viber APIs by the means described in the documentation of that API. If Viber assigns you developer credentials (e.g. client IDs), you must use them with the applicable Viber APIs. You will not misrepresent or mask either your identity or your API Client’s identity when using the Viber APIs or developer accounts.

(c) Viber may set and enforce limits on your use of the Viber APIs (e.g. limiting the number of API requests that you may make or the number of users you may serve) in our sole discretion. You agree to and will not attempt to circumvent such limitations . If you would like to use any Viber API beyond the applicable limits, you must obtain our express consent (and we may decline such request or condition acceptance on your agreement to additional terms and/or charges for that use).

3. API Clients and Monitoring
The Viber APIs are designed to help you enhance your websites and applications (“API Client(s)”). Viber is not required to promote or recommend your API Client. YOU AGREE THAT VIBER MAY MONITOR USE OF THE APIS TO ENSURE QUALITY, IMPROVE VIBER PRODUCTS AND SERVICES, AND VERIFY YOUR COMPLIANCE WITH THE TERMS OF SERVICE. This monitoring may include Viber accessing and using your API Client, for example, to identify security issues that could affect Viber or its users. You will not interfere with this monitoring. Viber may use any technical means to overcome such interference. Viber may suspend access to the Viber APIs by you or your API Client without notice if we reasonably believe that you are in violation of the Terms of Service.

4. Security
You will use commercially reasonable efforts to protect user information collected by your API Client, including personally identifiable information (“PII”), from unauthorized access or use and will promptly report to your users and any other party as required by applicable law any unauthorized access or use of such information to the extent required by applicable law.

5. User Privacy and API Clients
You will comply with all applicable privacy laws and regulations including those applying to PII. You will provide and adhere to a privacy policy for your API Client that clearly and accurately describes to users of your API Client what user information you collect and how you use and share such information (including for advertising) with Viber and third parties.

6. Viber API Prohibitions
When using the Viber APIs, you may not (or allow those acting on your behalf to):

1. Perform an action with the intent of introducing to Viber products and services any viruses, worms, defects, Trojan horses, malware, or any items of a destructive nature.
2. Defame, abuse, harass, stalk, or threaten others.
3. Interfere with or disrupt the Viber APIs or the servers or networks providing the Viber APIs.
4. Promote or facilitate unlawful online gambling or disruptive commercial messages or advertisements.
5. Reverse engineer or attempt to extract the source code from any Viber API or any related software, except to the extent that this restriction is expressly prohibited by applicable law.
6. Use the Viber APIs for any activities where the use or failure of the Viber APIs could lead to death, personal injury, or environmental damage (such as the operation of nuclear facilities, air traffic control, or life support systems).
7. Use the Viber APIs to process or store any data that is subject to the International Traffic in Arms Regulations maintained by the U.S. Department of State.
8. Remove, obscure, or alter any Viber Terms of Service or any links to or notices of those terms.

Viber reserves the right to charge fees for future use of or access to the Viber APIs in Viber’s sole discretion. If Viber decides to charge for use of the Viber APIs, such charges will be disclosed to you prior to their effect. Viber also reserves the right to include advertising in or associated with any information provided to you through the Viber APIs.

7. Confidential Information
(a) Developer credentials (such as passwords, keys, and client IDs) are intended to be used by you and to identify your API Client. You will keep your credentials confidential and make reasonable efforts to prevent and discourage other API Clients from using your credentials. Developer credentials may not be embedded in open source projects.

(b) Our communications to you and the Viber APIs may contain Viber confidential information. Viber confidential information includes any materials, communications, and information that are marked confidential or that would normally be considered confidential under the circumstances. If you receive any such information, then you will not disclose it to any third party without Viber’s prior written consent. Viber confidential information does not include information that you independently developed, that was rightfully given to you by a third party without confidentiality obligation, or that becomes public through no fault of your own. You may disclose Viber confidential information when compelled to do so by law if you provide us reasonable prior notice. If you have entered a specific Non Disclosure Agreement with Viber, such Non Disclosure Agreement shall prevail over the confidentiality obligations set forth in this Section 7(b).

8. Ownership
The Viber APIs may be protected by copyrights, trademarks, service marks, international treaties, and/or other proprietary rights and laws of the U.S. and other countries. Viber’s rights apply to the Viber APIs and all output and executables of the Viber APIs, excluding any software components developed by you which do not themselves incorporate the Viber APIs or any output or executables of such software components. You agree to abide by all applicable proprietary rights laws and other laws including without limitation the laws of the United States of American and all other countries where you use the Viber APIs, as well as any additional copyright notices or restrictions contained in these Terms of Service. Viber owns all rights, title, and interest in and to the Viber APIs. These Terms of Service grant you no right, title, or interest in any intellectual property owned or licensed by Viber, including (but not limited to) the Viber APIs.

9. Termination
You may stop using the Viber APIs at any time with or without notice. Further, if you want to terminate the Terms of Service, you must provide Viber with prior written notice and upon termination, cease your use of the Viber APIs. Viber reserves the right to terminate the Terms of Service with you without notice, liability, or other obligation to you.

10. Support
Viber may elect to provide you with support or modifications for the Viber APIs (collectively, “Support”), in its sole discretion, and may terminate such Support at any time without notice to you. Viber may change, suspend, or discontinue any aspect of the Viber APIs for any reason at any time, including the availability of any Viber APIs. Viber may also impose limits on certain features and services or restrict your access to parts or all of the Viber APIs without notice or liability.

11. Your Obligations Post-Termination
Upon any termination of the Terms of Service or discontinuation of your access to the Viber APIs, you will immediately stop using the Viber APIs. Viber may independently communicate with any account owner whose account(s) are associated with your API Client and developer credentials to provide notice of the termination of your right to use the Viber APIs.

12. Survival clause
When the Terms of Service terminate, those terms that by their nature are intended to continue indefinitely will continue to apply.

13. Disclaimer of Warranty
SOME OF THE VIBER APIS ARE EXPERIMENTAL AND HAVE NOT BEEN TESTED IN ANY MANNER. VIBER DOES NOT REPRESENT OR WARRANT THAT VIBER APIS ARE FREE OF INACCURACIES, ERRORS, BUGS, OR INTERRUPTIONS, OR ARE RELIABLE, ACCURATE, COMPLETE, OR OTHERWISE VALID.

TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE VIBER APIS ARE PROVIDED “AS IS” WITH NO WARRANTY, EXPRESS OR IMPLIED, OF ANY KIND AND VIBER EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES AND CONDITIONS, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AVAILABILITY, SECURITY, TITLE AND/OR NON-INFRINGEMENT.

YOUR USE OF THE VIBER APIS IS AT YOUR OWN DISCRETION AND RISK, AND YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE THAT RESULTS FROM THE USE OF THE VIBER APIS INCLUDING, BUT NOT LIMITED TO, ANY DAMAGE TO YOUR COMPUTER SYSTEM OR LOSS OF DATA.

14. Limitation of Liability
TO THE EXTENT PERMITTED BY APPLICABLE LAW, VIBER SHALL NOT, UNDER ANY CIRCUMSTANCES, BE LIABLE TO YOU FOR ANY DIRECT, INDIRECT, PUNITIVE, ACTUAL, INCIDENTAL, CONSEQUENTIAL, SPECIAL OR EXEMPLARY DAMAGES ARISING OUT OF OR IN CONNECTION WITH ANY USE, OR INABILITY TO USE, THE VIBER APIS, WHETHER BASED ON BREACH OF CONTRACT, BREACH OF WARRANTY, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, OR ANY OTHER PECUNIARY LOSS, REGARDLESS OF THE BASIS UPON WHICH LIABILITY IS CLAIMED AND WHETHER OR NOT VIBER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGES. UNDER NO CIRCUMSTANCES SHALL VIBER BE LIABLE TO YOU FOR ANY AMOUNT. WITHOUT LIMITATION, YOU (AND NOT VIBER) ASSUME THE ENTIRE COST OF ALL NECESSARY SERVING, REPAIR, OR CORRECTION IN THE EVENT OF ANY SUCH LOSS OR DAMAGE ARISING THEREIN. IF APPLICABLE LAW DOES NOT ALLOW ALL OR ANY PART OF THE ABOVE LIMITATION OF LIABILITY TO APPLY TO YOU, THE LIMITATIONS WILL APPLY TO YOU ONLY TO THE EXTENT PERMITTED BY APPLICABLE LAW. In no event shall Viber’s total liability to you for all damages (other than as may be required by applicable law in cases involving personal injury) exceed the amount of fifty U.S. dollars ($50.00). The foregoing limitations will apply even if the above stated remedy fails of its essential purpose.

15. Indemnification
To the maximum extent permitted by applicable law, you agree to hold harmless and indemnify Viber and its subsidiaries, affiliates, officers, agents, licensors, co-branders or other partners, and employees from and against any third party claims arising from or in any way related to your use of the Viber APIs, including any liability or expense arising from all claims, losses, damages (actual and/or consequential), suits, judgments, litigation costs and attorneys’ fees, of every kind and nature. Viber shall use good faith efforts to provide you with written notice of such claim, suit or action.

16. Relationship of the Parties
Notwithstanding any provision hereof, for all purposes of the Terms of Service, you and Viber shall be and act independently and not as partner, joint venturer, agent, employee or employer of the other. You shall not have any authority to assume or create any obligation for or on behalf of Viber, express or implied, and you shall not attempt to bind Viber to any contract.

17. Invalidity of Specific Terms
If any provision of these Terms of Service are adjudged, by written decision, to be unlawful, void, or for any reason unenforceable, then that provision shall be deemed severable from this agreement and shall not affect the validity and enforceability of any remaining provisions.

18. Choice of Law
To the extent permitted by law, the Terms of Service and any provisions therein shall be governed by, construed and enforced in accordance with the laws of the State of New York, as they are applied to agreements entered into and to be performed entirely within New York.

19. No Waiver of Rights by Viber
Viber’s failure to exercise or enforce any right or provision of the Terms of Service shall not constitute a waiver of such right or provision.

20. Miscellaneous
The section headings and subheadings contained in this agreement are included for convenience only, and shall not limit or otherwise affect the terms of the Terms of Service. Any construction or interpretation to be made of the Terms of Service shall not be construed against the drafter. The Terms of Service, the Viber Terms of Use and any other applicable Viber product or service terms, constitute the entire agreement between Viber and you with respect to the subject matter hereof.


Badge Guidelines

Promote your Public Account with a Viber badge!

With the Viber badge on your website, emails, communications, ads, promotions and more, you can direct people straight to your Public Account.

Adding the badge will clearly show your users that you have a Public Account, and will make it easy for them to subscribe.

Start bringing people to your Public Account today.

Purple badge White badge
Download Download

Adding the badge

  1. Download a badge to your computer
  2. Paste it in your material/ on your website
  3. Link your Public Account URL

Some badges dos and don’ts

The following conditions must be observed when adding the Viber badge to your materials.

  1. Do use the Viber Badges as provided. Don’t alter the badges.
  2. Do make sure there is clear space surrounding the badge equal to one-quarter of the height of the Viber Badges.
  3. Do make the Viber Badge large enough that all of the text is legible.
  4. Do make the Viber Badge the same size or larger than other application store badges.
  5. Do display the Viber Badge on a solid colored background or a simple background image that does not obscure the badge.
  6. Don’t use the Viber Badge for any purpose other than to promote content available on Viber.
  7. Do include the following legal attribution when there is space in the creative: Viber and the Viber logo are trademarks of Viber Media S.a.r.l.

Conditions of Use

By using the Viber Badge, you agree to the terms above and below, the Public Account Guidelines, and all other Viber Policies as well as all other relevant API documentation. The Viber Badge does not allow you to use the Viber trademark and brand in any way not expressly authorized below.


Getting started with bots

Create and build a bot to interact with users through Viber. A Viber bot is a form of Public Account, that will only interact with users through automated messaging in 1on1 messages.

Read more for information about how to create and publish your bot.

Table of Contents

Get started

Start creating your bot from the link below.

Remember, you must have a valid Viber account before you can create a bot on Viber. If you don’t, your application will not be approved.

Create a Bot

Once your application has been approved, you will be sent a message inviting you to start creating your bot. In order to start creating your account you must:

API

Use the API documentation to learn how to attach your bot to your account. Once this process has been completed you will be able to send and receive messages from users through the bot.

Sharing your bot with Viber users

Upon creation you can share your bot with others using Viber’s share button. You can also create a deep link using your account’s URI. This deep link can be used to share your bot with your users in Viber and across other platforms.

Viber offers a discover section where bots enjoy increased exposure and engagement. Your bot must be published to appear on the discover screen. Learn what it takes to make your bot public:

Viber bot guidelines

The following checklist sets out the features that must be included in your bot. In order for your bot to be approved, you will need to be able to demonstrate that they are there.

Bot details

All details should display as intended. Bot must comply with Viber’s naming and content policy.

Functionality

Performance

Make your bot public - COMING SOON

Once you have completed your bot, ensuring it meets all guidelines, you may submit a bot publication form.

Once your bot has been approved it will become available for publication on Viber’s search and discovery section.


Glossary

Table of Contents

Public Accounts

Public Accounts are a communication hub within Viber. Connect with followers by:

  1. Customizing your info screen with your brand, description and location.
  2. Sending free 1on1 messages to users.
  3. Attaching Bots to interact with users.
  4. Delivering information in Public Chat conversations.

Public Chats

Viber group conversations which can be found and followed by any Viber user. Public Chats are accessed from the Public Account info screen. Group participants can post in the group and contribute content.

Info Screen

The Public Account home screen. Customize the info screen with your brand, description and location. The info screen contains links to other services in the account, as well as Joker buttons with URLs to relevant pages.

Joker Buttons

Customized buttons directing users to predetermined URLs. Up to four Joker buttons allowed for each Public Account. Account admins can choose to show or hide a specific button. Buttons include links such as “play”, “download”, “buy now”, “more” and so on.

1on1 Chat

Free private messages between the account and users. Rich formats supported, including: text, images, video, links, location and more.

Public Accounts API

Integrate 1on1 chat or Bots with your Public Account using the Public Accounts API. The Public Account user token can be found in the Edit Details screen.

Integrated Partners

Link an existing CRM to send 1on1 chats with users. A complete list of integrated partners can be found here. All communication will be managed through the CRM backend.

Bots

Bots are fully customizable apps that can be added to the Public Account to facilitate interaction between users and your account. See the Public Accounts API to learn more about how to add a pre-existing Bot to an account.

Keyboards

Keyboards are the preferred Bot communication form for Viber’s Public Accounts. Keyboards allow the account to define the conversation you wish to have with users by providing answer options to each question. Use the Public Accounts API to add a keyboard to your account.

Discover

Featured and top Public Accounts appear on Discover. Discover is localized, so users will see Public Accounts most relevant to them in their country or local area.

Authentication token

The authentication token (also known as application key) is a unique and secret account identifier. It is used to authenticate requests in the Public Accounts API and to prevent unauthorized persons from sending requests on behalf of a Public Account. You will need this token when during the integration process.

The authentication token is generated upon Public Account creation and can be viewed by the account’s admins in the “edit info” screen of their Public Account.

Public Account URI

The Public Account URI is used in several use cases. From deep linking to just sharing your group. Get your Public Account URI by placing a call to the get_account_info API method. The URI will be part of the response object.


Public Accounts 101

A Public Account allows businesses, brands and public figures to interact and form connections with Viber users around the globe. As a channel that encourages both engagement and personal connections, Public Accounts can be used for a wide variety of purposes - including sales, marketing, support, announcements and more.

Your Public Account consists of three parts:

Info screen The face of a Public Account and the place where users choose how to interact with it.

Public Chat Allowing Public Account owners to build their brand personality by sharing various types of content and exposing users to behind the scenes at your brand.

1-on-1 chat Viber users and businesses interact directly, in the familiar way users use personal chats.

API

One of the great services we offer our Public Account owners is the ability to chat with their users in a 1-on-1 conversation through our PA-API.

Once a Public Account has registered, it can use this API to programmatically send messages and receive responses from users.

Access

Start creating your Public Account by opening the Viber app on your phone.

  1. Open Public Accounts through the Public Accounts icon at the top right of your screen
  2. Once you’re on the Public Accounts home page, tap on the create button at the bottom of the screen
  3. Tap on Join now to start creating your Public Account

Now you can create your account in the three steps below. A more detailed guide to each of these steps can be found in our support site.

Setup

Once your application has been approved you will be sent a message inviting you to start creating your Public Account.

Authentication token

The authentication token (also known as application key) is a unique and secret account identifier. It is used to authenticate requests in the Public Accounts API and to prevent unauthorized persons from sending requests on behalf of a Public Account. You will need this token when during the integration process.

The authentication token is generated upon Public Account creation and can be viewed by the account’s admins in the “edit info” screen of their Public Account.

Supported platforms

Public accounts are currently supported on iOS and android devices running Viber version 6.5 and above and on desktop from version 6.5.3.


Don’t forget to check our support site for tips, best practices and guidance.


Deep Links

Public accounts will be able to implement a deep link that directs users to a 1-on-1 chat with a PA. Pressing this link will open a conversation with the PA and trigger a conversation started event.

A conversation started event will be triggered each time the user presses the link, even if the user has a conversation history with the PA.

The deep link is created using the PA URI, according to two schemes:

viber://pa?chatURI=<Public Account URI> 

Additional parameters

The public account will be able to attach two additional parameters to the deep link:

Context

The value of this parameter will be forwarded to the PA under the context parameter in the conversation started callback (see conversation started for additional details). The context will be transferred as a string and has no length limit (up to URL length limit).

Text

The value of this parameter will appear in the text input field when the 1-on-1 chat with the PA is opened by pressing the deep link. The user will be able to send the text as it is, edit it, or delete it.

A deep link with context parameter will look as follows:

viber://pa?chatURI=<Public Account URI>&context=abcdefg&text=hello

Note: Some browsers might have a problem identifying the deep link. To make sure the link works try sending it as a Viber message and pressing it from within Viber.


Keyboard Examples

Examples of keyboard layouts based on Public Account content.

Restaurants

Smoking / non smoking

{
	"Type": "keyboard",
	"Buttons": [{
		"Columns": 3,
		"Rows": 2,
		"Text": "<font color=\"#494E67\">Smoking</font><br><br>",
		"TextSize": "medium",
		"TextHAlign": "center",
		"TextVAlign": "bottom",
		"ActionType": "reply",
		"ActionBody": "Smoking",
		"BgColor": "#f7bb3f",
		"Image": "https: //s12.postimg.org/ti4alty19/smoke.png"
	}, {
		"Columns": 3,
		"Rows": 2,
		"Text": "<font color=\"#494E67\">Non Smoking</font><br><br>",
		"TextSize": "medium",
		"TextHAlign": "center",
		"TextVAlign": "bottom",
		"ActionType": "reply",
		"ActionBody": "Non smoking",
		"BgColor": "# f6f7f9",
		"Image": "https: //s14.postimg.org/us7t38az5/Nonsmoke.png"
	}]
}

Food types

{
	"Type": "keyboard",
	"Buttons": [{
		"Columns": 2,
		"Rows": 2,
		"Text": "<br><font color=\"#494E67\"><b>ASIAN</b></font>",
		"TextSize": "large",
		"TextHAlign": "center",
		"TextVAlign": "middle",
		"ActionType": "reply",
		"ActionBody": "ASIAN",
		"BgColor": "#f7bb3f",
		"Image": "https://s18.postimg.org/9tncn0r85/sushi.png"
	}, {
		"Columns": 2,
		"Rows": 2,
		"Text": "<br><font color=\"#494E67\"><b>FRENCH</b></font>",
		"TextSize": "large",
		"TextHAlign": "center",
		"TextVAlign": "middle",
		"ActionType": "reply",
		"ActionBody": "French",
		"BgColor": "#7eceea",
		"Image": "https://s18.postimg.org/ntpef5syd/french.png"
	}, {
		"Columns": 2,
		"Rows": 2,
		"Text": "<br><font color=\"#494E67\"><b>MEXICAN</b></font>",
		"TextSize": "large",
		"TextHAlign": "center",
		"TextVAlign": "middle",
		"ActionType": "reply",
		"ActionBody": "Mexican",
		"BgColor": "#f6f7f9",
		"Image": "https://s18.postimg.org/t8y4g4kid/mexican.png"
	}, {
		"Columns": 2,
		"Rows": 2,
		"Text": "<br><font color=\"#494E67\"><b>ITALIAN</b></font>",
		"TextSize": "large",
		"TextHAlign": "center",
		"TextVAlign": "middle",
		"ActionType": "reply",
		"ActionBody": "Italian",
		"BgColor": "#dd8157",
		"Image": "https://s18.postimg.org/x41iip3o5/itallian.png"
	}, {
		"Columns": 2,
		"Rows": 2,
		"Text": "<br><font color=\"#494E67\"><b>INDIE</b></font>",
		"TextSize": "large",
		"TextHAlign": "center",
		"TextVAlign": "middle",
		"ActionType": "reply",
		"ActionBody": "Indie",
		"BgColor": "#f6f7f9",
		"Image": "https://s18.postimg.org/wq06j3jkl/indi.png"
	}, {
		"Columns": 2,
		"Rows": 2,
		"Text": "<br><font color=\"#494E67\"><b>MORE</b></font>",
		"TextSize": "large",
		"TextHAlign": "center",
		"TextVAlign": "middle",
		"ActionType": "reply",
		"ActionBody": "More",
		"BgColor": "#a8aaba",
		"Image": "https://s18.postimg.org/ylmyu98et/more_Options.png"
	}]
}

Restaurant listing

{
	"Type": "keyboard",
	"Buttons": [{
		"Columns": 2,
		"Rows": 2,
		"ActionType": "reply",
		"ActionBody": "Zepras_image",
		"BgColor": "#f6f7f9",
		"Image": "https://s14.postimg.org/pireym5h9/Restaurant01.png"
	}, {
		"Columns": 4,
		"Rows": 2,
		"Text": "<br><b>\u00A0\u00A0ZEPRAS</b><br>\u00A0\u00A0Minimum: 100 \u20BD Delivery: 10 \u20BD<br>\u00A0\u00A012:00 - 23:30<br>\u00A0\u00A0aprox. delivery time: 90 min.<br>\u00A0\u00A0Rating: 4 stars, 760 reviews",
		"TextSize": "regular",
		"TextHAlign": "left",
		"TextVAlign": "top",
		"ActionType": "reply",
		"ActionBody": "Zepras_text",
		"BgColor": "#f6f7f9"
	}, {
		"Columns": 2,
		"Rows": 2,
		"ActionType": "reply",
		"ActionBody": "Giraffa_image",
		"BgColor": "#f6f7f9",
		"Image": "https://s14.postimg.org/otdojdb99/Restaurant02.png"
	}, {
		"Columns": 4,
		"Rows": 2,
		"Text": "<br><b>\u00A0\u00A0Giraffa</b><br>\u00A0\u00A0Minimum: 55 \u20BD Delivery: 10 \u20BD<br>\u00A0\u00A012:00 - 23:45<br>\u00A0\u00A0aprox. delivery time: 120 min.<br>\u00A0\u00A0Rating: 4.5 stars, 1300 reviews",
		"TextSize": "regular",
		"TextHAlign": "left",
		"TextVAlign": "top",
		"ActionType": "reply",
		"ActionBody": "Giraffa_text",
		"BgColor": "#f6f7f9"
	}]

}

Games

Selection

{
	"Type": "keyboard",
	"Buttons": [{
		"Columns": 1,
		"Rows": 1,
		"ActionType": "reply",
		"ActionBody": "purple_flower",
		"BgColor": "#e0e0e0",
		"Image": "https://s15.postimg.org/fvaegniyf/Game1.png"
	}, {
		"Columns": 1,
		"Rows": 1,
		"ActionType": "reply",
		"ActionBody": "green_flower",
		"BgColor": "#e0e0e0",
		"Image": "https://s15.postimg.org/df8l2t0vr/Game2.png"
	}, {
		"Columns": 1,
		"Rows": 1,
		"ActionType": "reply",
		"ActionBody": "green_mushroom",
		"BgColor": "#e0e0e0",
		"Image": "https://s15.postimg.org/u4a0ypxh3/Game3.png"
	}, {
		"Columns": 1,
		"Rows": 1,
		"ActionType": "reply",
		"ActionBody": "cactus",
		"BgColor": "#e0e0e0",
		"Image": "https://s15.postimg.org/c2vhenstz/Game4.png"
	}, {
		"Columns": 1,
		"Rows": 1,
		"ActionType": "reply",
		"ActionBody": "blue_pink_flower",
		"BgColor": "#e0e0e0",
		"Image": "https://s15.postimg.org/srwxakpfb/Game5.png"
	}, {
		"Columns": 1,
		"Rows": 1,
		"ActionType": "reply",
		"ActionBody": "greenish_flower",
		"BgColor": "#e0e0e0",
		"Image": "https://s15.postimg.org/knot5u307/Game6.png"
	}, {
		"Columns": 6,
		"Rows": 1,
		"ActionType": "reply",
		"ActionBody": "mud",
		"BgColor": "#e0e0e0",
		"Image": "https://s15.postimg.org/huvllt2nr/longbutton.png"
	}]
}

Quiz

{
	"Type": "keyboard",
	"Buttons": [{
		"Columns": 2,
		"Rows": 2,
		"ActionType": "reply",
		"ActionBody": "salmon",
		"BgColor": "#e0e0e0",
		"Image": "https://s22.postimg.org/es631qrq5/salmon.png"
	}, {
		"Columns": 2,
		"Rows": 2,
		"ActionType": "reply",
		"ActionBody": "flamingo",
		"BgColor": "#e0e0e0",
		"Image": "https://s22.postimg.org/67crakhjx/flamingo.png"
	}, {
		"Columns": 2,
		"Rows": 2,
		"ActionType": "reply",
		"ActionBody": "snakes",
		"BgColor": "#e0e0e0",
		"Image": "https://s22.postimg.org/r82svhl25/snake.png"
	}]
}

News

{
	"Type": "keyboard",
	"Buttons": [{
		"Columns": 2,
		"Rows": 2,
		"Text": "<br><br><br><br><br>\u00A0\u00A0\u00A0<font color='#ffffff'>Politics</font>",
		"TextHAlign": "left",
		"TextVAlign": "middle",
		"ActionType": "reply",
		"ActionBody": "clinton_image",
		"BgColor": "#ffffff",
		"Image": "https://s9.postimg.org/mebu960yz/politics.png"
	}, {
		"Columns": 4,
		"Rows": 2,
		"ActionType": "reply",
		"ActionBody": "clinton_text",
		"BgColor": "#ffffff",
		"Text": "\u00A0\u00A0\u00A0<b>Clinton and Trump Begin <br>\u00A0\u00A0\u00A0 Final Sprint to Election Day </b><br><br>\u00A0\u00A0\u00A0Hillary Clinton \"Allergic\" to Trump<br><br><font color=#999999'>\u00A0\u00A0\u00A01 min. ago</font>",
		"TextHAlign": "left",
		"TextVAlign": "top"
	}, {
		"Columns": 2,
		"Rows": 2,
		"Text": "<br><br><br><br><br>\u00A0\u00A0\u00A0<font color='#ffffff'>Sports</font>",
		"TextHAlign": "left",
		"TextVAlign": "middle",
		"ActionType": "reply",
		"ActionBody": "serena_image",
		"BgColor": "#ffffff",
		"Image": "https://s9.postimg.org/ok653o4ff/sports.png"
	}, {
		"Columns": 4,
		"Rows": 2,
		"ActionType": "reply",
		"ActionBody": "serena_text",
		"BgColor": "#ffffff",
		"Text": "\u00A0\u00A0\u00A0<b>Serena Williams: World No .1 <br>\u00A0\u00A0\u00A0surpasses Federer's record </b><br><br>\u00A0\u00A0\u00A0Wiliams breaks grand slam record<br><br><font color=#999999>\u00A0\u00A0\u00A02 hours ago</font>",
		"TextHAlign": "left",
		"TextVAlign": "top"
	}]
}

E-commerce

{
	"Type": "keyboard",
	"Buttons": [{
		"Columns": 1,
		"Rows": 2,
		"ActionType": "reply",
		"ActionBody": "lotion1",
		"BgColor": "#e0e0e0",
		"Text": "<font color=’#807b78’>5.99 \u20BD</font>",
		"TextHAlign": "center",
		"TextVAlign": "bottom",
		"Image": "http://s12.postimg.org/484u3tg89/cream_01.png"
	}, {
		"Columns": 1,
		"Rows": 2,
		"ActionType": "reply",
		"ActionBody": "lotion2",
		"BgColor": "#e0e0e0",
		"Text": "<font color=’#807b78’>7.99 \u20BD</font>",
		"TextHAlign": "center",
		"TextVAlign": "bottom",
		"Image": "http://s12.postimg.org/k7s3141nt/cream_02.png"
	}, {
		"Columns": 1,
		"Rows": 2,
		"ActionType": "reply",
		"ActionBody": "lotion3",
		"BgColor": "#e0e0e0",
		"Text": "<font color=’#807b78’>9.99 \u20BD</font>",
		"TextHAlign": "center",
		"TextVAlign": "bottom",
		"Image": "http://s12.postimg.org/9m87p3vc9/cream_03.png"
	}, {
		"Columns": 1,
		"Rows": 2,
		"ActionType": "reply",
		"ActionBody": "lotion4",
		"BgColor": "#e0e0e0",
		"Text": "<font color=’#807b78’>12.99 \u20BD</font>",
		"TextHAlign": "center",
		"TextVAlign": "bottom",
		"Image": "http://s12.postimg.org/5r4tmjc6h/cream_04.png"
	}, {
		"Columns": 1,
		"Rows": 2,
		"ActionType": "reply",
		"ActionBody": "lotion5",
		"BgColor": "#e0e0e0",
		"Text": "<font color=’#807b78’>19.99 \u20BD</font>",
		"TextHAlign": "center",
		"TextVAlign": "bottom",
		"Image": "http://s12.postimg.org/y5a96ezqh/cream_05.png"
	}, {
		"Columns": 1,
		"Rows": 2,
		"ActionType": "reply",
		"ActionBody": "lotion6",
		"BgColor": "#e0e0e0",
		"Text": "<br><font color=’#807b78’>23.99 \u20BD</font>",
		"TextHAlign": "center",
		"TextVAlign": "bottom",
		"Image": "http://s12.postimg.org/6vyvrwynd/cream_06.png"
	}, {
		"Columns": 6,
		"Rows": 1,
		"ActionType": "reply",
		"ActionBody": "lotion_promotion",
		"BgColor": "#e0e0e0",
		"Text": "<font color=#ffffff>\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0HOLIDAY SEASON SPECIAL OFFERS<br>\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0GET IT NOW FOR ONLY </font><font color=#e897ad>29.99\u20BD</font>",
		"TextHAlign": "left",
		"TextVAlign": "middle",
		"Image": "http://s13.postimg.org/5b8k7118z/image.png"
	}]
}

Keyboards

The public accounts API allows sending a custom keyboard with each messsage, to supply the user with a set of predefined replies or actions. The keyboard can be attached to any message type or sent on it’s on. Once received, the keyboard will appear to the user instead of the device’s native keyboard. The keyboards are fully customizable and can be created and designed specifically for the PA’s needs.

The client will always display the last keyboard that was sent to it.

Table of Contents

Attaching a keyboard to a message

Keyboards can be attached to any message type and be sent and displayed together. To attach a keyboard to a message simply add the keyboard’s parameters to the message JSON.
The keyboard JSON object defines different visual and logic attributes. From the background color, number of buttons and so on.

The example below shows a keyboard sent with a single message.

{
	"keyboard": {
		"DefaultHeight": true,
		"BgColor": "#FFFFFF",
		"Buttons": [{
			"Columns": 6,
			"Rows": 1,
			"BgColor": "#2db9b9",
			"BgMediaType": "gif",
			"BgMedia": "http://www.url.by/test.gif",
			"BgLoop": true,
			"ActionType": "open-url",
			"ActionBody": "www.tut.by",
			"Image": "www.tut.by/img.jpg",
			"Text": "Key text",
			"TextVAlign": "middle",
			"TextHAlign": "center",
			"TextOpacity": 60,
			"TextSize": "regular"
		}]
	}
}

Which in turn will look like this

General keyboard parameters

Name Description Possible values Default value
Buttons required. Array containing all keyboard buttons by order. See buttons parameters below for buttons parameters details    
BgColor optional. Background color of the keyboard Valid color HEX value Default Viber keyboard background
DefaultHeight optional. When true - the keyboard will always be displayed with the same height as the native keyboard.When false - short keyboards will be displayed with the minimal possible height. Maximal height will be native keyboard height true, false false

Buttons parameters

The following parameters can be defined for each button in the “buttons” array separately. Each button must contain at least one of the following optional parameters: text, BgMedia, image, BgColor.

Name Description Possible values Default value
Columns optional. Button width in columns. See keyboard design for more details 1-6 6
Rows optional. Button height in rows. See keyboard design for more details 1-2 1
BgColor optional. Background color of button Valid color HEX value Default Viber button color
Silent optional. Determine whether the user action is presented in the conversation true/false false
BgMediaType optional. Type of the background media picture, gif. For picture - JPEG and PNG files are supported. Max size: 500 kb picture
BgMedia optional. URL for background media content (picture or gif). Will be placed with aspect to fill logic Valid URL  
BgLoop optional. When true - animated background media (gif) will loop continuously. When false - animated background media will play once and stop true , false true
ActionType optional. Type of action pressing the button will perform. Reply - will send a reply to the PA. open-url - will open the specified URL and send the URL as reply to the PA. See reply logic for more details reply, open-url, none reply
ActionBody required. Text for reply and none. ActionType or URL for open-url. See reply logic for more details For ActionType reply - text For ActionType open-url - Valid URL.  
Image optional. URL of image to place on top of background (if any). Can be a partially transparent image that will allow showing some of the background. Will be placed with aspect to fill logic Valid URL. JPEG and PNG files are supported. Max size: 500 kb  
Text optional. Text to be displayed on the button. Can contain some HTML tags - see keyboard design for more details Free text. Valid and allowed HTML tags Max 250 characters. If the text is too long to display on the button it will be cropped and ended with “…”  
TextVAlign optional. Vertical alignment of the text top, middle, bottom middle
TextHAlign optional. Horizontal align of the text left, center, right center
TextOpacity optional. Text opacity 0-100 100
TextSize optional. Text size out of 3 available options small, regular, large regular
OpenURLType optional. Determine the open-url action result, in app or external browser internal, external internal
OpenURLMediaType optional. Determine the url media type. not-media - force browser usage. video - will be opened via media player. gif - client will play the gif in full screen mode. picture - client will open the picture in full screen mode not-media , video , gif , picture not-media
TextBgGradientColor optional. Background gradient to use under text, Works only when TextVAlign is equal to top or bottom Hex value (6 characters)  

Note: The Silent parameter is supported on devices running Viber version 6.7 and above.

Keyboard design

The keyboard is divided into 6 columns. Each button has a width of 1-6 columns. The client will display the buttons according to the order they were sent in, and will fit as many buttons as possible into each row. If the next button to display can’t be fitted into the current row it will be displayed in the row below. For landscape mode, keyboard’s width will be doubled to 24 columns, and buttons will be displayed according to the same logic. Button height can be 1-2 rows.

Note: keyboards can contain up to 24 rows.

Text design

The buttons’ text can contain some HTML tags for design purposes. The allowed tags are listed in the table below.

Tag Description
<b>X</b> Bold text
<i>X</i> Italic text
<u>X</u> Underlined text
<br> Line break
<font color=”#7F00FF”>X</font> Specific text color. Must be a HEX value. Double quotes in JSON should be escaped.

Adding special characters or spaces at the beginning of the row can be done using Unicode. For example, setting a button’s text that starts with a space should look like this:

"Text": "\u00A0 Button text"

Keyboard Reply logic

Pressing a keyboard button would trigger a different reply depending on the buttons “actionType” value.

For actionType reply:

For actionType open-url:

For actionType none:

Note: The none action type is supported on devices running Viber version 6.7 and above.

Keyboard design guidelines

You can learn more about keyboard design guidelines in the following spec.

Keyboard examples

Check our examples section for different keyboard use cases.


Public Chat Plugin

The Public Chat plugin is a quick and easy way to call attention to your most recent Public Chat content anywhere on your website. Engage and immerse your website visitors in your Public Account and drive traffic directly to it.

To embed the plugin on your website, place the following within the code anywhere you’d like the plugin to appear:

https://live.viber.com/#/<Your URI>

Best practice

Embed the plugin within a device visual, to imitate the experience of scrolling through your Public Chat content.

For example, https://live.viber.com/#/fcbarcelona:


Viber Share Button

Viber provides a custom URL scheme to help your mobile website visitors share your content via a Viber message.
The Viber Share button is currently supported on iOS and Android and can be accessed from the mobile application or mobile web page only.

Sharing (forwarding) a message

To perform this action use the following URL scheme

viber://forward?text=  

How does it work?

With the Viber Share button you can share content from your mobile website directly on Viber.

Once your mobile website user selects the Viber Share button, a predefined text and the current page’s url can be sent to any Viber contact selected by your user.

The user will either be able to edit the text or simply send it without making any changes.

Setting up the Viber Share button

In order to setup the Viber Share button, follow the instructions below:

1. Download Viber Share button kit.
2. Place the following code in the page you want to integrate the Viber Share button:

<a id="viber_share">Click</a>
<script>
    var buttonID = "viber_share";
    var text = "Check this out: ";
    document.getElementById(buttonID)
        .setAttribute('href', "https://3p3x.adj.st/?adjust_t=u783g1_kw9yml&adjust_fallback=https%3A%2F%2Fwww.viber.com%2F%3Futm_source%3DPartner%26utm_medium%3DSharebutton%26utm_campaign%3DDefualt&adjust_campaign=Sharebutton&adjust_deeplink=" + encodeURIComponent("viber://forward?text=" + encodeURIComponent(text + " " + window.location.href)));
</script>

3. Choose one of our Viber Share button images and place it on your website within the <a> tag.
4. To change the sharing text, change the text variable:

var text = "Check this out: ";

5. Optional: In case you are already using a viber_share variable on your website, you can change the variable to any ID.

Troubleshooting


Sticker IDs

The following chart shows basic sticker examples and their sticker IDs, for sending to user as a sticker message.

You can find even more stickers by chatting with sticker bot!

Image Sticker ID
40133
40132
40131
40130
40129
40128
40127
40126
40125
40124
40123
40122
40121
40120
40119
40118
40117
40116
40115
40114
40113
40112
40111
40110
40109
40108
40107
40106
40105
40104
40103
40102
40101
40100
40151
40146
40145
40141
40140
40138
40137
40136
40134
114400
114434
114435
114401
114402
114403
114405
114406
114404
114407
114408
114409
114410
114411
114412
114413
114414
114415
114416
114417
114418
114419
114420
114421
114422
114423
114424
114425
114426
114427
114428
114429
114430
114432
114431
114433