- It’s easier than you think
- Tech stack
- Open source
- Cross platform
- Get started
- Check our NodeJS sample to see Viber bot in action
- Dive deeper and read the documentation for more information and steps to get started.
- need help?
- Source code viber android
- Viber API Documentation 7.3.0
- Docs / API / Viber REST API
- Viber REST API
- Get Started
- Authentication token
- Webhooks
- Setting a Webhook
- Resource URL
- Post data
- Set webhook Response
- Event types filtering
- Set webhook callback
- Removing your webhook
- Resource URL
- Post data
- Send Message
- Resource URL
- General send message parameters
- Message types
- Text message
- Picture message
- Video message
- File message
- Contact message
- Location message
- URL message
- Sticker message
- Rich Media message / Carousel content message
- Keyboards
- Resource URL
- Post data
- Broadcast Message
- Resource URL
- Post parameters
- broadcast_list
- Place holders
- Post example
- Response
- Get Account Info
- Resource URL
- Post data
- Response
- Get User Details
- Resource URL
- Post data
- Response
- Get Online
- Resource URL
- Post data
- Response
- Callbacks
- Re-try logic
- Input
- Output
- Subscribed
- Callback data
- Unsubscribed
- Callback data
- Conversation started
- Callback data
- Sending a welcome message
- Welcome message flow
- Message receipts callbacks
- Callback data
- Failed callback
- Callback data
- Receive message from user
- Callback data
- Error Codes
It’s easier than you think
With Viber’s APIs, you can create unique experiences for users at scale. There are no registration fees and our team is here to support you through the development and integration process.
Tech stack
Develop bots with NodeJS, Python and REST
Open source
Viber libraries are open source projects maintained by Viber and an active community of contributors
Cross platform
Your bots will run on iOS, Android, Mac and Windows
Get started
Use our solutions to build and connect bots to interact with your users. Use Viber’s API to connect a bot, or team up with a trusted partner to develop the solution that suits you.
Check our NodeJS sample to see Viber bot in action
Dive deeper and read the documentation for more information and steps to get started.
need help?
Ask questions in the Gitter. Prefer to reach out privately? Email devsupport@viber.com.
We’ve teamed up with the best companies in the world to bring you channels, tools, service integrations and more to enrich communication with your customers.
Источник
Source code viber android
Последнее обновление программы в шапке: 03.12.2021
Краткое описание:
Бесплатный мессенджер, аудио/видео звонки, голосовые сообщения, стикеры, группы, сообщества, игры. и вот это вот всё.
Мессенджер Viber — это возможность писать бесплатные сообщения и совершать бесплатные звонки и видеовызовы на телефон или планшет, отправлять голосовые сообщения, фото и видео, не тратя денег на смс.
Используйте групповые видеозвонки до 20 человек и безлимитный чат, чтобы всегда оставаться на связи с друзьями и семьей. Звонить на мобильный, совершать видеозвонки онлайн или отправлять сообщение бесплатно можно с любого Андроид устройства.
Viber дает возможность совершать звонки по видеосвязи, отправлять записи в голосовой чат, делиться с друзьями фотографиями, видео, данными о местонахождении, контактами, ссылками, стикерами и эмодзи.
Создавайте чаты до 250 участников! Бесплатный мессенджер Viber позволяет легко создавать и вступать в групповые чаты будь то чат с родителями, сообщества по интересам, группы с друзьями или паблик чат. Станьте администратором чата, контролируйте видео чат и звонки, редактируйте аватар и информацию, удаляйте участников, ставьте лайки понравившимся сообщениям. Участники получат оповещения о любых изменениях в группе.
Почему пользователи по всему миру выбирают Viber мессенджер?
★ Межгород и бесплатные международные звонки и видеовызовы без настройки аккаунта.
★ Бесплатные звонки через интернет со звуком в HD-качестве.
★ Мгновенно записывайте и отправляйте 30-секундные видео, чтобы поделиться лучшими моментами.
★ Безопасные звонки, сообщения и видеовызовы, надежно защищенные end-to-end шифрованием.
★ Верифицированные контакты – подтверждайте контакты вручную, чтобы убедиться в «подлинности» собеседника.
★ В Магазине стикеров вы можете скачать стикеры, чтобы сделать свой чат веселее!
★ Вы можете удалять отправленные вами сообщения, даже если собеседник их уже получил.
★ Скрывайте чаты, если не хотите, чтобы они отображались в общем списке.
★ Игры с Viber персонажами: Violet и Legcat. Соревнуйся с друзьями прямо сейчас.
★ Паблик аккаунты в Viber – возможность вести диалог с брендом или администратором тематического сообщества напрямую. Читайте публичные чаты, делитесь контактами и местоположением, просматривайте информацию о просмотрах и лайках ваших сообщений.
★ Сообщения могут быть до 7 000 символов длиной. Не тратьте деньги на отправку смс любимой или друзьям!
★ Отправляйте документы, презентации, архивы и файлы других типов прямо через бесплатный мессенджер Viber.
★ Push-уведомления не дадут пропустить видеовызов на Андроид или сообщение даже при выключенном Viber!
Сообщества и чаты Viber объединяют более 800 миллионов человек по всему миру. Звонки за границу, смс поздравления, фотографии и видео по WiFi или 3G/4G/EDGE. * Могут применяться тарифы оператора
Источник
Viber API Documentation 7.3.0
Docs / API / Viber REST API
Viber REST API
Get Started
In order to implement the API you will need the following:
- An Active Viber account on a platform which supports bots (iOS/Android). This account will automatically be set as the account administrator during the account creation process.
- Active bot — Create a bot here. Note: an active Viber account is needed to receive the login code to access the bot creation page.
- 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 account will need to contain the token.
- 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. In order to implement the API you will need the following:
Supported platforms
Bots are currently supported on iOS and Android devices running Viber version 6.5 and above and on desktop from version 6.5.3.
Important notes for bot developers:
- Viber’s bot platform is open and free for developers to create bots in our ecosystem. Once you’ve created your bot you are welcome to share it with your Viber contacts or promote it outside Viber on your website or social media channels using a deeplink. Please note that Viber is not responsible for promoting your bot, and that by default your bot will not have an active landing page under viber.com after creation. Enabling this URL is part of the paid services we offer to official partners. Likewise, after creating your bot it will not appear in search results in Viber, and enabling this also part of the paid services we offer to official partners. If you’re interested in discussing a partnership agreement or know more about the paid channels to promote your bot on Viber, please email devsupport@viber.com and include your company details, including your company’s country.
- We recommend that you record the subscriber ID of each subscriber, as there’s no API for fetching all subscriber IDs for your bot. You can find the subscriber ID in the sender.id property of the Message callback, or the user.id property of the Subscribed callback. You can see whether a user is subscribed in the subscribed parameter of the conversation_started callback. Note that users’ first message to the bot will make them subscribed, but will not result in a Subscribed callback.
- If you wish to message users based on their phone number and using an API, we offer a service called Business Messages that supports this. Application to use this service is done via one of our official partners. You can see which partners cover your geographical area in their description in the link above. Our partners will be able to provide you with further details about the service, such as pricing.
Send and receive message flow
The following diagram describes the flow of sending and receiving messages by the 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 Viber API and to prevent unauthorized persons from sending requests on behalf of a bot. Each API request must include an HTTP Header called X-Viber-Auth-Token containing the account’s authentication token.
HTTP header
The authentication token is generated upon bot creation and can be viewed by the account’s admins in the “edit info” screen of their bot or on the Viber Admin Panel.
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 and user messages from Viber.
Setting the webhook will be done by calling the set_webhook API with a valid & certified URL. This action defines the account’s webhook and the type of events the account wants to be notified about.
For security reasons only URLs with valid and official SSL certificate from a trusted CA will be allowed. The certificate CA should be on the Sun Java trusted root certificates list.
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. The check succeeds if the Viber server receives HTTP status 200 in response to the callback, but fails if it recieves any other status. If your set_webhook response doesn’t have «status»:0 , please verify that all requests to your webhook URL receive HTTP status 200 in response.
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.
Viber’s API allows you to receive user names and photos. This has been updated to comply with privacy laws and allow developers who don’t make use of user names and photos as part of their service to opt out. If you don’t use user names photos, please opt-out to default values.
To set the request, pass send_name and send_photo flags with the set_webhook request.
Note: This feature will work if the user has allowed “Content Personalisation” (More → Privacy → personal data). If the user has disallowed content personalization, you will receive placeholder values.
Setting a Webhook
Resource URL
Post data
Post parameters
Name | Description | Validation |
---|---|---|
url | required. Account 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 account 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 |
send_name | optional. Indicates whether or not the bot should receive the user name. Default false | Possible values: true , false |
send_photo | optional. Indicates whether or not the bot should receive the user photo. Default false | Possible values: true , false |
Set webhook Response
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 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
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 bot 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 bot 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
Post data
Post parameters
Name | Description |
---|---|
url | required. Account 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 accounts to send messages to Viber users who subscribe to the account. Sending a message to a user will be possible only after the user has subscribed to the bot. (see subscribed callback for additional information). You can share your bot with the users via a deeplink.
The API supports a variety of message types: text , picture , video , file , location , sticker , contact , carousel content 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.
Can send up to 100 messages to a user in an hour (XX:00-XX:00) without reply, message count towards the limit is reset when a user replies to a message. Once the limit is reached, you will receive an error callback saying:
Resource URL
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 720×720 |
tracking_data | Allow the account 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. Certain features may not work as expected if set to a number that’s below their requirements. |
Message types
Below is a list of all supported message types with post data examples.
Text message
Post data
Post parameters
Name | Description | Validation |
---|---|---|
type | Message type | required. text . Supports text formatting |
text | The text of the message | required. Max length 7,000 characters |
Picture message
Post data
Post parameters
Name | Description | Validation |
---|---|---|
type | Message type | required. picture |
text | Description of the photo. Can be an empty string if irrelevant | required. Max 512 characters |
media | URL of the image (JPEG, PNG, non-animated GIF) | required. The URL must have a resource with a .jpeg , .png or .gif file extension as the last path segment. Example: http://www.example.com/path/image.jpeg . Animated GIFs can be sent as URL messages or file messages. Max image size: 1MB on iOS, 3MB on Android. |
thumbnail | URL of a reduced size image (JPEG, PNG, GIF) | optional. Recommended: 400×400. Max size: 100kb. |
Video message
Post data
Post parameters
Name | Description | Validation |
---|---|---|
type | Message type | required. video |
media | URL of the video (MP4, H264) | required. Max size 26 MB. Only MP4 and H264 are supported. The URL must have a resource with a .mp4 file extension as the last path segment. Example: http://www.example.com/path/video.mp4 |
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: 400×400. Only JPEG format is supported |
File message
Post data
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
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
Post parameters
Name | Description | Validation |
---|---|---|
type | Message type | required. location |
location | Location coordinates | required. latitude (±90°) & longitude (±180°) within valid ranges |
URL message
Post data
Post parameters
Name | Description | Validation |
---|---|---|
type | Message type | required. url |
media | URL | required. Max 2,000 characters |
Sticker message
Post data
Post parameters
Name | Description | Validation |
---|---|---|
type | Message type | required. sticker |
sticker_id | Unique Viber sticker ID. For examples visit the sticker IDs page |
Rich Media message / Carousel content message
The Rich Media message type allows sending messages with pre-defined layout, including height (rows number), width (columns number), text, images and buttons.
Below you will find an exmaple of a Carousel Content Message, that allows a user to scroll through a list of items, each composed of an image, description and call to action button.
Each item on the list shown to the user is a button in the Rich Media message’s “Buttons” array. Sending one button is also permitted.
The parameters for Rich Media message and its buttons are also used for Keyboards. You can find additional information on them in the following article.
Notes:
- Carousel Content Message is supported on devices running Viber version 6.7 and above.
- Each button is limited to a maximum of 7 rows.
- Forwarding is not supported for Rich Media messages.
Post data
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 Viber 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 account’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
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).
Broadcast Message
The broadcast_message API allows accounts to send messages to multiple Viber users who subscribe to the account. Sending a message to a user will be possible only after the user has subscribed to the bot by sending a message to the bot.
The API supports a variety of message types: text , picture , video , file , location , sticker , contact , carousel content and URL .
Validation
Maximum total JSON size of the request is 30kb. The maximum list length is 300 receivers. The Broadcast API is used to send messages to multiple recipients with a rate limit of 500 requests in a 10 seconds window.
Resource URL
Post parameters
This API method uses the same parameters as the send REST API method with a few variations described below.
broadcast_list
This mandatory parameter defines the recipients for the message. Every user must be subscribed and have a valid user id. The maximum list length is 300 receivers. For example (this should be a part of the full JSON body):
Place holders
Broadcast message can contain place holders that will be replaced with receiver information (each receiver will get it’s own information). The place holders can appear anywhere in the message, even in tracking data. The list of the place holders:
- replace_me_with_receiver_id — will be replaced by the receiver ID
- replace_me_with_url_encoded_receiver_id — will be replaced by the URL encoded receiver ID
- replace_me_with_user_name — will be replaced by the receiver user name
Post example
The following example demonstrates send carousel content with place holders ( replace_me_with_receiver_id , replace_me_with_url_encoded_receiver_id , replace_me_with_user_name ) to 4 receivers:
Response
Response parameters
Name | Description | Possible values |
---|---|---|
message_token | Unique ID of the message | |
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 |
failed_list | Contains all the receivers to which the message could not be sent properly | See error codes table for additional information |
Response example
Get Account Info
The get_account_info request will fetch the 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
Post data
Response
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 account | |
name | Account name | Max 75 characters |
uri | Unique URI of the Account | |
icon | Account icon URL | JPEG, 720×720, size no more than 512 kb |
background | Conversation background URL | JPEG, max 1920×1920, size no more than 512 kb |
category | Account category | |
subcategory | Account sub-category | |
location | Account location (coordinates). Will be used for finding accounts near me | lat & lon coordinates |
country | Account country | 2 letters country code — ISO ALPHA-2 Code |
webhook | Account registered webhook | webhook URL |
event_types | Account registered events – as set by set_webhook request | delivered , seen , failed and conversation_started |
subscribers_count | Number of subscribers | |
members | Members of the bot’s public chat | id , name , avatar , role for each Public Chat member (admin/participant). Deprecated. |
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 account regarding user’s actions. This request can be sent twice during a 12 hours period for each user ID.
Resource URL
Post data
Post parameters
Name | Description | Validation |
---|---|---|
id | Unique Viber user id | required. subscribed valid user id |
Response
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 | The language set in the user’s Viber settings. | 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 account members. The API supports up to 100 user id per request and those users must be subscribed to the account.
Resource URL
Post data
Post parameters
Name | Description | Validation |
---|---|---|
ids | Unique Viber user id | required. 100 ids per request |
Response
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 |
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 until HTTP status code 200 is received. There will be 2 retry attempts 2 second apart.
Input
Key (your bot’s authentication token):
Output
HTTP header
Subscribed
Before an account can send messages to a user, the user will need to subscribe to the account. Subscribing can take place if the user sends a message to the bot — when a user sends its first message to a bot the user will be automatically subscribed to the bot. Sending the first message will not trigger a subscribe callback, only a message callback (see receive message from user section).
You will receive a subscribed event when unsubscribed users do the following:
- Open conversation with the bot.
- Tap on the 3-dots button in the top right and then on “Chat Info”.
- Tap on “Receive messages”.
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
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 | |
chat_hostname | Internal use |
Unsubscribed
The user will have the option to unsubscribe from the PA. This will trigger an unsubscribed callback.
Callback data
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 bot using the “message” button (found on the account’s info screen) or using a deep link.
This event is not considered a subscribe event and doesn’t allow the account 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.
Note: the conversation_started callback doesn’t contain the context parameter by default.
To add this paramater and determine its value, you can use a deeplink like this: viber://pa?chatURI=your_bot_URI&context=your_context
Callback data
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 Viber API allows sending messages to users only after they subscribe to the account. However, Viber will allow the account 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 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:
- User opens 1-on-1 conversation with account.
- Viber server sends a conversation_started callback to bot’s webhook.
- The account receives the conversation_started callback 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:
Note: The welcome message should be sent as the body of the HTTP response to the conversation_started callback, and not to the send_message endpoint.
Message receipts callbacks
Viber offers message status updates for each message sent, allowing the account 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 ).
The seen callback will only be sent once when the user reads the unread messages, regardless of the number of messages sent to them, or the number of devices they are using.
If the message recipient is using their Viber account on multiple devices, each of the devices will return a delivered, meaning that several delivered 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
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:
- Message is sent.
- Response with status 0 is received to indicate a successful request.
- The message reaches the client and fails client validation.
- “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
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 bot to user and from user to bot. 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
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 | |
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 account |
7 | publicAccountBlocked | The account is blocked |
8 | publicAccountNotFound | The account associated with the token is not a account. |
9 | publicAccountSuspended | The account is suspended |
10 | webhookNotSet | No webhook was set for the account |
11 | receiverNoSuitableDevice | The receiver is using a device or a Viber version that don’t support accounts |
12 | tooManyRequests | Rate control breach |
13 | apiVersionNotSupported | Maximum supported account version by all user’s devices is less than the minApiVersion in the message |
14 | incompatibleWithVersion | minApiVersion is not compatible to the message fields |
15 | publicAccountNotAuthorized | The account is not authorized |
16 | inchatReplyMessageNotAllowed | Inline message not allowed |
17 | publicAccountIsNotInline | The account is not inline |
18 | noPublicChat | Failed to post to public account . The bot is missing a Public Chat interface |
19 | cannotSendBroadcast | Cannot send broadcast message |
20 | broadcastNotAllowed | Attempt to send broadcast message from the bot |
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.
Источник