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
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:
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
this is awesome post it help me a lot. i have search internet for viber messenger by luckily i found on your site. you have given what i wanted. thank you. keep the good work.
Glad to know this post helped you 🙂
how can i get the user id for send message
To get user id for send message, the user needs to send a message to us. We get his user id in the callback.
Please check this line in the PHP code:
$sender_id = $input[‘sender’][‘id’];
This is unique Viber id of the user who sent the message. We use this user id to send message back to the user.
How To publish this php webhook code and are you tested this script before
I got this code working. I used SSL host (https) and successfully setup the webhook as per the above example. @Ayman maybe you are missing something.
Cool 🙂
can you tell me please how to setup the webhook on the site
Hi Ayman, you can use tools like POSTMAN or cURL to send POST request to this API with parameters shown above:
https://chatapi.viber.com/pa/set_webhook
i use this request to set webhooks by using PSTMAN but the error message is :
{
“status”: 1,
“status_message”: “Result[HttpRequest[POST HTTP/1.1]@c55c0fb > HttpResponse[null 0 null]@39a99f3f] java.nio.channels.UnresolvedAddressException”
}
I have updated the POST to setup webhook using cURL. Also, note that we need to have code at our webhook URL to handle response from Viber.
i did as you said and upload the php to my ssl server , now when i request to set webhooks with my auth_token , new error message appear :
{
“status”: 1,
“status_message”: “Result[HttpRequest[POST /~webtechi/taxicom/viberServer.php HTTP/1.1]@642ecb3f > HttpResponse[null 0 null]@54b25de3] java.util.concurrent.TimeoutException: Total timeout elapsed”
}
i used POSTMAN in request
Could you confirm you are sending post request to https://chatapi.viber.com/pa/set_webhook with your auth_token and url in Body and raw option selected?
If you still face problem, try the cURL code provided in the article.
Hi. thank for the useful tutorial.
However I am trying to set the webhook url but I am recieving
{
“status”: 1,
“status_message”: “Result[HttpRequest[POST /assets/php/v1/viber HTTP/1.1]@79369638 > HttpResponse[HTTP/1.1 404 Not Found]@235f6d24] null”
}
I tried advance rest clint and php script. Still the same result.
Could you please advice?
Thanks
Hi, Thanks.
This article is a great help.
I have two questions please:
1) Is there a way to test my webhook url for its responses?
2) On the setup a webhook part (3) the two PHP codes suppose to be in the same page?
Thanks
Hi Oshik,
The two PHP codes are different. The first PHP code in setup a webhook part is for setting webhook. You can run it in your local server. Actually, the first code sends auth_token along with URL of the second code to set_webhook API.
The second one is your webhook url. It receives message from Viber and sends message to Viber.
If webhook is setup successfully, your webhook url (second code) receives users message from Viber. You can check the message content by writing the value of file_get_contents(“php://input”) to text file in your server.
Hope this helps you.
Thanks a lot.
Exactly what I did, so actually from now on, every message sent in my public account chat Im suppose to receive a call to my webhook url.
So what is the reason it doesnt happen? maybe admin messages doesnt create callbacks?
Found the problem. Thanks
Cool 🙂
This article give brief description for newbies like me. I wish it had a better explanation and files, for better understanding. I can not figure it out
Hi. Can you help me. I have a your number phone . I want get to user id then send to api viber
Pls help me to send API get Receive id
Thanks
You can only get user_id of those users (phone) who have subscribed to your chat bot (Public Account). You can get user id from chat log and then send message.
Ok . Thank you so much
I have problem. I want set subscriber but i dont know send to link ??
Can you help me. Pls send url to subscriber or unsubscribe ??
I cannot create Public Account for Viber. I have filled up the form and got the email that they will send me email shortly. But I havent got it yet. Its been a week.
Help me out.
Hello I followed the exact method but, once i send the message bot doesn’t reply me back, I checked my webhook by writing user inputs to a text file, it works well!
I think problem is space at the end of url >> curl_init(“https://chatapi.viber.com/pa/send_message “
my problem is number , i created webhook and another api for call send to user but problem i have phone number and i see viber uniq id , but how to i convert phone number to viber id ? have a api i call and get viber id ?
Hi
Can you help me to unsubscirbe user viber ???
How do you view the photos received as picture messages? i see a value for message->file_name but message->media is always empty. i believe message->media should be the URL to access it from Viber’s servers?
i have a phone numbers how can i get the user is viber user or not and he/she is my subscriber or not
Hi there, I’m a complete noob but was just wondering if there’s a way to push notifications to a viber bot from my WordPress site every time there has been a new post. This is a great article btw unfortunatlly I have no idea as to what is going on.