Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including messaging-api-viber with all npm packages installed. Try it out:

var messagingApiViber = require("messaging-api-viber")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

messaging-api-viber v0.8.2

Messaging API client for Viber

messaging-api-viber

Messaging API client for Viber

Viber

Table of Contents

Installation

npm i --save messaging-api-viber

or

yarn add messaging-api-viber


Usage

Initialize

const { ViberClient } = require('messaging-api-viber');

// get authToken from the "edit info" screen of your Public Account.
const client = ViberClient.connect(authToken);

Error Handling

messaging-api-viber uses axios as HTTP client. We use axios-error package to wrap API error instances for better formatting error messages. Directly console.log on the error instance will return formatted message. If you'd like to get the axios request, response, or config, you can still get them via those keys on the error instance.

client.setWebhook(url).catch(error => {
  console.log(error); // formatted error message
  console.log(error.stack); // error stack trace
  console.log(error.config); // axios request config
  console.log(error.request); // HTTP request
  console.log(error.response); // HTTP response
});


API Reference

All methods return a Promise.


Webhook API

setWebhook(url [, eventTypes])

Setting a Webhook.

ParamTypeDescription
urlStringHTTPS Account webhook URL to receive callbacks & messages from users.
eventTypesArray<String>Indicates the types of Viber events that the account owner would like to be notified about. Possible values: delivered, seen, failed, subscribed, unsubscribed and conversation_started.

Example:

client.setWebhook('https://4a16faff.ngrok.io/');

You can filter event types using optional parameter:

client.setWebhook('https://4a16faff.ngrok.io/', [
  'delivered',
  'seen',
  'conversation_started',
]);


removeWebhook

Removing your webhook.

Example:

client.removeWebhook();


Send API

sendMessage(receiver, message) - Official Docs

Sending a message to a user.

ParamTypeDescription
receiverStringUnique Viber user id.
messageObjectMessage and options to be sent.

Example:

client.sendMessage(USER_ID, {
  type: 'text',
  text: 'Hello',
});

Note: Maximum total JSON size of the request is 30kb.


sendText(receiver, text [, options]) - Official Docs

Sending a text message to a user.

ParamTypeDescription
receiverStringUnique Viber user id.
textStringThe text of the message.
optionsObjectOther optional parameters.

Example:

client.sendText(USER_ID, 'Hello');


sendPicture(receiver, picture [, options]) - Official Docs

Sending a picture message to a user.

ParamTypeDescription
receiverStringUnique Viber user id.
pictureObject
picture.textStringDescription of the photo. Can be an empty string if irrelevant. Max 120 characters.
picture.mediaStringURL of the image (JPEG). 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.
picture.thumbnailStringURL of a reduced size image (JPEG). Max size 100 kb. Recommended: 400x400. Only JPEG format is supported.
optionsObjectOther optional parameters.

Example:

client.sendPicture(USER_ID, {
  text: 'Photo description',
  media: 'http://www.images.com/img.jpg',
  thumbnail: 'http://www.images.com/thumb.jpg',
});


sendVideo(receiver, video [, options]) - Official Docs

Sending a video message to a user.

ParamTypeDescription
receiverStringUnique Viber user id.
videoObject
video.mediaStringURL of the video (MP4, H264). Max size 50 MB. Only MP4 and H264 are supported.
video.sizeNumberSize of the video in bytes.
video.durationNumberVideo duration in seconds; will be displayed to the receiver. Max 180 seconds.
video.thumbnailStringURL of a reduced size image (JPEG). Max size 100 kb. Recommended: 400x400. Only JPEG format is supported.
optionsObjectOther optional parameters.

Example:

client.sendVideo(USER_ID, {
  media: 'http://www.images.com/video.mp4',
  size: 10000,
  thumbnail: 'http://www.images.com/thumb.jpg',
  duration: 10,
});


sendFile(receiver, file [, options]) - Official Docs

Sending a file message to a user.

ParamTypeDescription
receiverStringUnique Viber user id.
fileObject
file.mediaStringURL of the file. Max size 50 MB. See forbidden file formats for unsupported file types.
file.sizeNumberSize of the file in bytes.
file.file_nameStringName of the file. File name should include extension. Max 256 characters (including file extension).
optionsObjectOther optional parameters.

Example:

client.sendFile(USER_ID, {
  media: 'http://www.images.com/file.doc',
  size: 10000,
  file_name: 'name_of_file.doc',
});


sendContact(receiver, contact [, options]) - Official Docs

Sending a contact message to a user.

ParamTypeDescription
receiverStringUnique Viber user id.
contactObject
contact.nameStringName of the contact. Max 28 characters.
contact.phone_numberStringPhone number of the contact. Max 18 characters.
optionsObjectOther optional parameters.

Example:

client.sendContact(USER_ID, {
  name: 'Itamar',
  phone_number: '+972511123123',
});


sendLocation(receiver, location [, options]) - Official Docs

Sending a location message to a user.

ParamTypeDescription
receiverStringUnique Viber user id.
locationObject
location.latStringLatitude (±90°) within valid ranges.
location.lonStringLongitude (±180°) within valid ranges.
optionsObjectOther optional parameters.

Example:

client.sendLocation(USER_ID, {
  lat: '37.7898',
  lon: '-122.3942',
});


sendURL(receiver, url [, options]) - Official Docs

Sending an URL message to a user.

ParamTypeDescription
receiverStringUnique Viber user id.
urlStringURL. Max 2,000 characters.
optionsObjectOther optional parameters.

Example:

client.sendURL(USER_ID, 'http://developers.viber.com');


sendSticker(receiver, stickerId [, options]) - Official Docs

Sending a sticker message to a user.

ParamTypeDescription
receiverStringUnique Viber user id.
stickerIdNumberUnique Viber sticker ID. For examples visit the sticker IDs page.
optionsObjectOther optional parameters.

Example:

client.sendSticker(USER_ID, 46105);


sendCarouselContent(receiver, richMedia [, options]) - Official Docs

Sending a carousel content message to a user.

ParamTypeDescription
receiverStringUnique Viber user id.
richMedia.ButtonsGroupColumnsNumberNumber of columns per carousel content block. Default 6 columns. Possible values: 1 - 6.
richMedia.ButtonsGroupRowsNumberNumber of rows per carousel content block. Default 7 rows. Possible values: 1 - 7.
richMedia.ButtonsArray<Object>Array of buttons. Max of 6 _ ButtonsGroupColumns _ ButtonsGroupRows.
optionsObjectOther optional parameters.

Example:

client.sendCarouselContent(USER_ID, {
  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',
    },
  ],
});


Keyboards - Official Docs

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. 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 options:

client.sendText(USER_ID, 'Hello', {
  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:


Broadcast API - Official Docs

Those API methods use the same parameters as the send methods with a few variations described below. You should specify a list of receivers instead of a single receiver.

  • broadcastMessage(broadcastList, message)
  • broadcastText(broadcastList, text [, options])
  • broadcastPicture(broadcastList, picture [, options])
  • broadcastVideo(broadcastList, video [, options])
  • broadcastFile(broadcastList, file [, options])
  • broadcastContact(broadcastList, contact [, options])
  • broadcastLocation(broadcastList, location [, options])
  • broadcastURL(broadcastList, url [, options])
  • broadcastSticker(broadcastList, stickerId [, options])
  • broadcastCarouselContent(broadcastList, richMedia [, options])
ParamTypeDescription
broadcastListArray<String>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.

Example:

client
  .broadcastText(
    [
      'pttm25kSGUo1919sBORWyA==',
      '2yBSIsbzs7sSrh4oLm2hdQ==',
      'EGAZ3SZRi6zW1D0uNYhQHg==',
      'kBQYX9LrGyF5mm8JTxdmpw==',
    ],
    'a broadcast to everybody'
  )
  .then(result => {
    console.log(result);
    // {
    //   message_token: 40808912438712,
    //   status: 0,
    //   status_message: 'ok',
    //   failed_list: [
    //     {
    //       receiver: 'pttm25kSGUo1919sBORWyA==',
    //       status: 6,
    //       status_message: 'Not subscribed',
    //     },
    //     {
    //       receiver: 'EGAZ3SZRi6zW1D0uNYhQHg==',
    //       status: 5,
    //       status_message: 'Not found',
    //     },
    //   ],
    // }
  });


Get Account Info

getAccountInfo() - Official Docs

It will fetch the account’s details as registered in Viber.

Example:

client.getAccountInfo().then(info => {
  console.log(info);
  // {
  //   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',
  //     },
  //   ],
  // }
});


Get User Details

getUserDetails(id) - Official Docs

It will fetch the details of a specific Viber user based on his unique user ID.

ParamTypeDescription
idStringUnique Viber user id.

Example:

client.getUserDetails('01234567890A=').then(user => {
  console.log(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',
  // };
});


Get Online

getOnlineStatus(ids) - Official Docs

It will fetch the online status of a given subscribed account members.

ParamTypeDescription
idArray<String>Array of unique Viber user id. 100 ids per request.

Example:

client
  .getOnlineStatus(['01234567890=', '01234567891=', '01234567893='])
  .then(status => {
    console.log(status);
    // [
    //   {
    //     id: '01234567890=',
    //     online_status: 0,
    //     online_status_message: 'online',
    //   },
    //   {
    //     id: '01234567891=',
    //     online_status: 1,
    //     online_status_message: 'offline',
    //     last_online: 1457764197627,
    //   },
    //   {
    //     id: '01234567893=',
    //     online_status: 3,
    //     online_status_message: 'tryLater',
    //   },
    // ];
  });

Debug Tips

Log requests details

To enable default request debugger, use following DEBUG env variable:

DEBUG=messaging-api-viber

If you want to use custom request logging function, just define your own onRequest:

const client = ViberClient.connect({
  accessToken: ACCESS_TOKEN,
  onRequest: ({ method, url, headers, body }) => {
    /* */
  },
});

Test

Point requests to your dummy server

To avoid sending requests to real Viber server, specify origin option when constructing your client:

const { ViberClient } = require('messaging-api-viber');

const client = ViberClient.connect({
  accessToken: ACCESS_TOKEN,
  origin: 'https://mydummytestserver.com',
});

Warning: Don't do this on production server.

Manual Mock with Jest

create __mocks__/messaging-api-viber.js in your project root:

// __mocks__/messaging-api-viber.js
const jestMock = require('jest-mock');
const { ViberClient } = require.requireActual('messaging-api-viber');

module.exports = {
  ViberClient: {
    connect: jest.fn(() => {
      const Mock = jestMock.generateFromMetadata(
        jestMock.getMetadata(ViberClient)
      );
      return new Mock();
    }),
  },
};

Then, mock messaging-api-viber package in your tests:

// __tests__/mytest.spec.js
jest.mock('messaging-api-viber');

Metadata

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free