Build a Complete Viber Chat Bot in 6 simple steps

Chat Bot is very popular these days. With Chat Bot, you can connect to your customers with Deeper Interactions and grow your business.

In this post, I am going to share how to develop Viber Chat Bot in 6 simple steps using PHP.

1. Create Public Account in Viber

To get started, first of all, you should have a Viber Public account. If you don’t have a Public Account, apply for a Public Account in Viber Public Accounts page.
Once your application has been approved, you will be sent a invitation message to start creating your Public Account. To create account, you need to:
• Restart your device.
• Enter the Public Accounts home-screen. You will see the Create Public Accounts button.
• Tap on the button, and get started!

2. Get authentication token

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

Example token: 455a0f2c05b4fe54-cb4e33d3200fbbae-95f29ebc06af09a8

Viber edit account detail
Example for Viber edit account detail page

3. Setup webhook

Once the token is received, 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.

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: Before sending request to set_webhook API, we need to have code to handle callback from Viber at our webhook URL. Sample PHP Code is provided in this article.

Call a POST request to this api:
https://chatapi.viber.com/pa/set_webhook
Post Parameters:

{
  "auth_token": "455a0f2c05b4fe54-cb4e33d3200fbbae-95f29ebc06af09a8",
  "url": "https://mysite.com/webhook_page",
  "event_types": ["delivered", "seen"]
}

auth_token = The token string provided by Viber on PA creation.
url = PA webhook URL to receive callbacks & messages from users (must use SSL i.e. https)
event_type = (optional) Indicates the types of Viber events that the PA owner would like to be notified about. Default values: [“delivered”, “seen”]

In order to make POST request to set_webhook API, we can use cURL or tools like POSTMAN. Here’s the sample PHP code:

<?php

$url = 'https://chatapi.viber.com/pa/set_webhook';

$jsonData='{ "auth_token": "your_auth_token", "url": "https://yoursite.com/webhook_page" }';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);

?>

 

After we call set_webhook api, Viber will send a callback to the webhook URL to confirm it is available, i.e https://mysite.com/webhook_page in the above example. The callback data format is as follow:

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

event = Callback type – which event triggered the callback. Possible value is webhook.
timestamp= Time of the event that triggered the callback
message_token = Unique ID of the message

Now we need to give response as

{
  "status": 0,
  "status_message": "ok",
  "event_types": ["delivered", "seen"] //Not yet implemented
}

status = Action result (0 for success, error number for errors)
status_message = Ok or failure reason
event_types = delivered or seen (not implemented yet)

This will set webhook url. Now, whenever an event occurs related to the Public Account, a callback is sent to the webhook url and we need to handle the events in webhook url that is discussed below.

Code for webhook url:

<?php 

$request = file_get_contents("php://input");
$input = json_decode($request, true);

if($input['event'] == 'webhook') {
  $webhook_response['status']=0;
  $webhook_response['status_message']="ok";
  $webhook_response['event_types']='delivered';
  echo json_encode($webhook_response);
  die;
}
else if($input['event'] == "subscribed") {
  // when a user subscribes to the public account
}
else if($input['event'] == "conversation_started"){
  // when a conversation is started
}
elseif($input['event'] == "message") {
  /* when a user message is received */
  $type = $input['message']['type']; //type of message received (text/picture)
  $text = $input['message']['text']; //actual message the user has sent
  $sender_id = $input['sender']['id']; //unique viber id of user who sent the message
  $sender_name = $input['sender']['name']; //name of the user who sent the message

  // here goes the data to send message back to the user
  $data['auth_token'] = "4453b6ac1s345678-e02c5f12174805f9-95f29ebc06af09a8";
  $data['receiver'] = $sender_id;
  $data['text'] = "The message to send to user";
  $data['type'] = 'text';

  //here goes the curl to send data to user
  $ch = curl_init("https://chatapi.viber.com/pa/send_message ");
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  $result = curl_exec($ch);
}

?>

4. Receive message

Whenever user sends a message to the public account in 1-to-1 chat, the following callback data is sent to the webhook url.

{ 
  "event": "message", 
  "timestamp": 1457764197627, 
  "message_token": 4912661846655238145, 
  "sender": 
  { 
    "id": "01234567890A=",
     "name": "yarden",
     "avatar": "http://avatar_url"
   }, 
  "message": 
  { 
    "type": "text",
     "text": "a message to the service",
     "media": "http://download_url",
     "location":
    {
      "lat": 50.76891,
      "lon": 6.11499},
      "tracking_data": "tracking data"
     } 
  }
}

event = in case of message sent by user event value will be message
timestamp = time of the event that triggered the callback
message_token = unique id of message
sender = sender details (id, name, avatar)
message = message details like text, media (if any) and so on

In this way we can receive message from user and appropriate message can be sent to user which will be discussed below.

5. Send message

In order to send message to user, we need to call a Post request to send_message api as below:

Sending text message:
Url : https://chatapi.viber.com/pa/send_message
Post parameters:

{
  "auth_token": "455a0f2c05b4fe54-cb4e33d3200fbbae-95f29ebc06af09a8", 
  "receiver": "01234567890A=", 
  "type": "text", 
  "text": "a message from pa" 
}

auth_token = The token string provided by Viber on Public Account creation.
receiver = unique viber user id to whom the message is being sent
type = Message type (“text” for text messages)
text = text message to be sent

Sending images:
Url: https://chatapi.viber.com/pa/send_message

{ 
  "auth_token": "455a0f2c05b4fe54-cb4e33d3200fbbae-95f29ebc06af09a8",
  "receiver": "01234567890A=", 
  "type": "picture", 
  "text": "Photo description", 
  "media": "http://www.images.com/img.jpg", 
  "thumbnail": "http://www.images.com/thumb.jpg"
 }

auth_token = The token string provided by Viber on Public Account creation.
receiver = unique viber user id to whom the message is being sent
type = Message type (“picture” for image)
text = photo description (can be null if not required)
media = URL of image (only JPEG supported)
thumbnail = reduced image URL (only JPEG supported)

Similarly, we can also send file messages as well.

6. Send keyboard (Menu)

The public account 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.

A keyboard can be attached to a message as follows:
Url: https://chatapi.viber.com/pa/send_message
Post parameters:

{ 
  "auth_token": "455a0f2c05b4fe54-cb4e33d3200fbbae-95f29ebc06af09a8", 
  "receiver": "01234567890A=",
  "type":"text",
  "text":"The message",
  "keyboard": { 
    "Type": "keyboard", 
    "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" 
    },

    { 
      "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": "<b>Key text</b>", 
      "TextVAlign": "middle", 
      "TextHAlign": "center", 
      "TextOpacity": 60, 
      "TextSize": "regular" 
    } 	
    ] 
  } 
}

Image For Keyboard can be:

Image for keyboard(menu)
Viber chat example menu

All parameters are same as that of sending normal text message except for the param keyboard.
The button array contains array of buttons as per the requirement.

General Keyboard parameters are:
Type: Required. Type of keyboard display (currently only “keyboard” is available).
Buttons: Required. It is array containing all keyboard buttons by order.
BgColor: Optional. Background color of keyboard to be provided HEX value.
DefaultHeight: Optional. Possible values are true or false.
Button Array 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.
– Columns: button width in columns. possible values 1-6.
– Rows: button height in rows. possible values 1 and 2.
– BgColor: background color to be provided HEX value.
– BgMediaType: type of background media. Possible values: picture or gif.
– BgMedia: url for background media (picture or gif)
– BgLoop: possible values: true or false.
– ActionType: type of action on pressing the button. Possible values: reply or open-url. reply will send reply as normal message and open-url will open a link.
– ActionBody: text to reply if ActionType is reply and link to open if ActionType is open-url.
– Image: url of image to be placed on top of background.
– Text: text to be displayed in button.
– TextVAlign: vertical alignment of text. Possible values: top or middle or buttom.
– TextHAlign: horizontal alignment of text. Possible values: left or center or right.
– TextOpacity: text opacity. Possible values 1-100.
– TextSize: size of text. possible values: small or regular or large.

Button text can support some HTML tags:

<b>Text Here</b> Bold
<i>Text Here</i> Italic
<u> Text Here </u> Underline
Line Break 
<span style="color: #7f00ff;">X</span> Font Color

Get Public Account Info
In order to get Public account details, you need to call get_account_info api as follows:
url: https://chatapi.viber.com/pa/get_account_info
Post parameters:

{ 
    "auth_token": "455a0f2c05b4fe54-cb4e33d3200fbbae-95f29ebc06af09a8"
}

where auth_token is  the token string provided by Viber on Public Account creation.

In this way, you can develop a simple Chat Bot for Viber using PHP. Moreover, it is the starting point to build complex bot. You should try to implement your own to respond to the various messages.

Updates: After having a lot of requests from readers, we have extended the Viber chat bot further with structure messages like keyboard menu, images, links and so on. Please go through the article below to find live example.

Sending structured message and keyboard menu in Viber chat bot

 

23 Comments

Leave a Reply