Skip to content

Commit

Permalink
Update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
ItamarM authored Dec 13, 2016
1 parent 807746e commit f385e61
Showing 1 changed file with 62 additions and 55 deletions.
117 changes: 62 additions & 55 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# Viber Node.JS Bot API
Use this library to communicate with the Viber API to develop a bot for [Viber](https://developers.viber.com/).
Please visit [Getting Started](https://developers.viber.com/customer/en/portal/articles/2567874-getting-started?b_id=15145) guide for more information about Viber API.
Use this library to develop a bot for the Viber platform.
The library is available on [GitHub](https://github.com/Viber/viber-bot-node) as well as a package on [npm](https://www.npmjs.com/package/viber-bot).

## License
This library is released under the terms of the Apache 2.0 license. See [License](LICENSE.md) for more information.
This library is released under the terms of the Apache 2.0 license. See [License](https://github.com/Viber/viber-bot-node/blob/master/LICENSE.md) for more information.

## Library Prerequisites
* Node >= 5.0.0
* Winston >= 2.0.0
* [Get your Viber Public Account authentication token](https://developers.viber.com/customer/en/portal/articles/2554141-create-a-public-account?b_id=15145).
* [Get your Viber Public Account authentication token](../public-account/create-public-account.md).
* SSL Certification - You'll need a trusted (ca.pem) certificate, not self-signed. You can find one at [Let's Encrypt](https://letsencrypt.org/) or buy one.

## Installation
Expand All @@ -19,6 +19,7 @@ Install with [`npm install viber-bot --save`](https://www.npmjs.com/package/vibe

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

```javascript
app.use("/viber/webhook", bot.middleware());
```
Expand All @@ -29,14 +30,15 @@ For more information see [ViberBot.middleware()](#middleware).
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/
2. Create a Public Account and use the API key from [https://dev.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 webserver url

### A simple Echo Bot
### Creating an echo Bot
Firstly, let's *import and configure* our bot:

```javascript
'use strict';

Expand All @@ -48,7 +50,7 @@ const toYAML = require('winston-console-formatter');

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

Expand All @@ -70,25 +72,24 @@ const https = require('https');
const port = process.env.PORT || 8080;

// Viber will push messages sent to this URL. Webserver should be internet-facing.
const webhookUrl = process.env.WEBHOOK_URL;
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));
```

### Do you supply a basic router for text messages?
Well, funny you ask. Yes we do.
**be careful**, messages sent to your router callback will also be emitted to *BotEvents.MESSAGE_RECEIVED* event.
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.

```javascript
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) =>
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? There's a all bunch of message types you should get familiar with, [here's a list of them](https://developers.viber.com/customer/en/portal/articles/2632255-send-message?b_id=15145).
Every one of them is already modeled:
Have you noticed how we created the `TextMessage` instance? There's a all bunch of message types you should get familiar with.

* [Text Message](#TextMessage)
* [Url Message](#UrlMessage)
Expand All @@ -98,8 +99,7 @@ Every one of them is already modeled:
* [Location Message](#LocationMessage)
* [Sticker Message](#StickerMessage)

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.
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
Expand All @@ -113,7 +113,7 @@ An event emitter, emitting events [described here](#onEvent).
* [.getUserDetails(userProfile)](#getUserDetails)`promise.JSON`
* [.setWebhook(url)](#setWebhook)`promise.JSON`
* [.sendMessage(userProfile, messages, [optionalTrackingData])](#sendMessage)`promise.ARRAY`
* [.on(handler)](#onEvent)
* [.on(handler)](#onEvent)
* [.onTextMessage(regex, handler)](#onTextMessage) : `handler` = [`TextMessageHandlerCallback`](#TextMessageHandlerCallback)
* [.onError(handler)](#onError) : `handler` = [`ErrorHandlerCallback`](#ErrorHandlerCallback)
* [.onConversationStarted(userProfile, onFinish)](#onConversationStarted) : `onFinish` = [`ConversationStartedOnFinishCallback`](#ConversationStartedOnFinishCallback)
Expand All @@ -123,7 +123,7 @@ An event emitter, emitting events [described here](#onEvent).


<a name="newViberBot"></a>
### new ViberBot()
### New ViberBot()

| Param | Type | Description |
| --- | --- | --- |
Expand Down Expand Up @@ -153,6 +153,7 @@ Subscribe to events:
* ERROR (Callback: `function (err) {}`)

**Example**

```js
bot.on(BotEvents.MESSAGE_RECEIVED, (message, response) => ... );
bot.on(BotEvents.MESSAGE_SENT, (message, userProfile) => ... );
Expand All @@ -165,7 +166,8 @@ bot.on(BotEvents.SUBSCRIBED, response =>

<a name="getBotProfile"></a>
### bot.getBotProfile()
Returns a `promise.JSON` ([With the following JSON](https://developers.viber.com/customer/en/portal/articles/2541122-get-account-info?b_id=15145)). **Example**
Returns a `promise.JSON` ([With the following JSON](rest-bot-api.md#getAccountInfo).

```js
bot.getBotProfile().then(response => console.log(`Public Account Named: ${response.name}`));
```
Expand All @@ -176,7 +178,8 @@ bot.getBotProfile().then(response => console.log(`Public Account Named: ${respon
| --- | --- | --- |
| userProfile | [`UserProfile`](#UserProfile) | `UserProfile` object |

Returns a `promise.JSON`. **Example**
Returns a `promise.JSON`.

```js
bot.onSubscribe(response => bot.getUserDetails(response.userProfile)
.then(userDetails => console.log(userDetails)));
Expand All @@ -188,7 +191,8 @@ bot.onSubscribe(response => bot.getUserDetails(response.userProfile)
| --- | --- | --- |
| url | `string` | Trusted SSL Certificate |

Returns a `promise.JSON`. **Example**
Returns a `promise.JSON`.

```js
bot.setWebhook("https://my.bot/incoming").then(() => yourBot.doSomething()).catch(err => console.log(err));
```
Expand All @@ -201,9 +205,10 @@ bot.setWebhook("https://my.bot/incoming").then(() => yourBot.doSomething()).catc
| 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.
*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.

Returns a `promise.ARRAY` array of message tokens. **Example**
```js
// single message
const TextMessage = require('viber-bot').Message.Text;
Expand All @@ -220,8 +225,8 @@ bot.sendMessage(userProfile, [

<a name="middleware"></a>
### bot.middleware()
Returns a middleware implementation to use with `http/https` or any webserver that accept middleware interface as an argument.
**Example**
Returns a middleware implementation to use with `http/https`.

```js
const https = require('https');
https.createServer({ key: ... , cert: ... , ca: ... }, bot.middleware()).listen(8080);
Expand All @@ -236,9 +241,9 @@ https.createServer({ key: ... , cert: ... , ca: ... }, bot.middleware()).listen(

<a name="TextMessageHandlerCallback"></a>
##### TextMessageHandlerCallback: `function (message, response) {}`
**Example**

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

Expand All @@ -250,7 +255,7 @@ bot.onTextMessage(/^hi|hello$/i, (message, response) =>

<a name="ErrorHandlerCallback"></a>
##### ErrorHandlerCallback: `function (err) {}`
**Example**

```js
bot.onError(err => logger.error(err));
```
Expand All @@ -262,16 +267,16 @@ bot.onError(err => logger.error(err));
| userProfile | [`UserProfile`](#UserProfile) |
| onFinish | [`ConversationStartedOnFinishCallback`](#ConversationStartedOnFinishCallback) |

*Note*: onConversationStarted event happens once when A Viber client opens the conversation with your bot for the first time. Callback accepts `null` and [`MessageObject`](#MessageObject) only. Otherwise, an exception is thrown.
*Note*: `onConversationStarted` event happens once when A Viber client opens the conversation with your bot for the first time. Callback accepts `null` and [`MessageObject`](#MessageObject) only. Otherwise, an exception is thrown.

<a name="ConversationStartedOnFinishCallback"></a>
##### ConversationStartedOnFinishCallback: `function (responseMessage, optionalTrackingData) {}`
**Example**

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

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

Expand All @@ -283,7 +288,7 @@ bot.onConversationStarted((userProfile, onFinish) =>

<a name="SubscribeResponseHandlerCallback"></a>
##### SubscribeResponseHandlerCallback: `function (response) {}`
**Example**

```js
bot.onSubscribe(response => console.log(`Subscribed: ${response.userProfile.name}`));
```
Expand All @@ -296,7 +301,7 @@ bot.onSubscribe(response => console.log(`Subscribed: ${response.userProfile.name

<a name="UnsubscribeResponseHandlerCallback"></a>
##### UnsubscribeResponseHandlerCallback: `function (userId) {}`
**Example**

```js
bot.onUnsubscribe(userId => console.log(`Unsubscribed: ${userId}`));
```
Expand Down Expand Up @@ -326,6 +331,7 @@ Members:

<a name="MessageObject"></a>
### Message Object

```javascript
const TextMessage = require('viber-bot').Message.Text;
const UrlMessage = require('viber-bot').Message.Url;
Expand All @@ -348,88 +354,89 @@ const StickerMessage = require('viber-bot').Message.Sticker;

| Param | Type | Description |
| --- | --- | --- |
| optionalKeyboard | `JSON` | [Writing Custom Keyboards](https://developers.viber.com/customer/en/portal/articles/2567880-keyboards?b_id=15145) |
| optionalKeyboard | `JSON` | [Writing Custom Keyboards](rest-bot-api.md#keyboards) |
| optionalTrackingData | `JSON` | Data to be saved on Viber Client device, and sent back each time message is recived |

<a name="TextMessage"></a>
#### TextMessage object
| Member | Type
| Member | Type
| --- | --- |
| text | `string` |
```javascript

```javascript
const message = new TextMessage(text, [optionalKeyboard], [optionalTrackingData]);
console.log(message.text);
```

<a name="UrlMessage"></a>
#### UrlMessage object
| Member | Type
| Member | Type
| --- | --- |
| url | `string` |
```javascript

```javascript
const message = new UrlMessage(url, [optionalKeyboard], [optionalTrackingData]);
console.log(message.url);
```

<a name="ContactMessage"></a>
#### ContactMessage object
| Member | Type
| Member | Type
| --- | --- |
| contactName | `string` |
| contactPhoneNumber | `string` |
```javascript

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

<a name="PictureMessage"></a>
#### PictureMessage object
| Member | Type
| Member | Type
| --- | --- |
| url | `string` |
| text | `string` |
| thumbnail | `string` |
```javascript

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

<a name="VideoMessage"></a>
#### VideoMessage object
| Member | Type
| Member | Type
| --- | --- |
| url | `string` |
| size | `int` |
| thumbnail | `string` |
| duration | `int` |
```javascript

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

<a name="LocationMessage"></a>
#### LocationMessage object
| Member | Type
| Member | Type
| --- | --- |
| latitude | `float` |
| longitude | `float` |
```javascript

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

<a name="StickerMessage"></a>
#### StickerMessage object
| Member | Type
| Member | Type
| --- | --- |
| stickerId | `int` |
```javascript

```javascript
const message = new StickerMessage(stickerId, [optionalKeyboard], [optionalTrackingData]);
console.log(message.stickerId);
```

## Useful links:
* Writing a custom keyboard JSON [described here](https://developers.viber.com/customer/en/portal/articles/2567880-keyboards?b_id=15145).
* [Forbidden file formats list](https://developers.viber.com/customer/en/portal/articles/2541358-forbidden-file-formats?b_id=15145).
* List of [Error Codes](https://developers.viber.com/customer/en/portal/articles/2541337-error-codes?b_id=15145).
* List of [Events and Callbacks](https://developers.viber.com/customer/en/portal/articles/2541267-callbacks?b_id=15145).

0 comments on commit f385e61

Please sign in to comment.