Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Chatbot on Azure and Couchbase for Viber

DZone's Guide to

Chatbot on Azure and Couchbase for Viber

This was really fun, and I could definitely get carried away playing with this new chatbot. It could analyze images, tell jokes, look up all kinds of info, and more.

· AI Zone ·
Free Resource

Insight for I&O leaders on deploying AIOps platforms to enhance performance monitoring today. Read the Guide.

A chatbot can be a novel way to interact with users. After writing a post introducing the basics of serverless, and also writing a post on writing Azure Functions, I decided I would try to build something a little more practical than a "hello, world".

Using a serverless architecture for a chatbot makes sense. Chatbot usage may be sporadic. Usage may peak and drop at various times of the day. By using serverless, you'll only be paying for the resources and time that you need.

Viber Chatbot

I could have chosen a lot of different platforms to create a chatbot for: Facebook Messenger, Skype, WhatsApp, and more. But I decided to go with Viber.

In the United States, Viber doesn't seem to have a huge following, but I've been using it a lot. It's a very handy way to chat with my wife, send pictures, send funny GIFs, and so on. I find it to be more reliable and faster than SMS, especially for pictures. I wish everyone in my family was using it! It's also a nice side effect that Viber is a Couchbase customer. They switched from MongoDB to support their growing data needs.

Also, Viber's REST API is simple and well-documented. Between the use of serverless architecture and Viber's API, I couldn't believe how fast I went from 0 to chatbot.

Setup

First, You'll need to start by creating a bot in Viber (you'll need a Viber account at some point). Viber will give you an API key that looks something like 30a6470a1c67d66f-4207550bd0f024fa-c4cacb89afc04094. You'll use this in the HTTP headers to authenticate to the Viber API.

I decided to use C# to write my Azure functions. Unfortunately, there is no.NET SDK for Viber (as far as I know), so I'll have to use the REST API directly. Not a big deal; I just used RestSharp. But if you prefer NodeJS or Python, Viber has got you covered with SDKs for those languages.

Before you start coding, you'll need to set up a Webhook. This is simply a way of telling Viber where to send incoming messages. You'll only need to do this at the beginning. I did this by first deploying a barebones Azure Function that returns a 200. I used Postman to set the initial webhook.

Finally, I set up a Couchbase cluster on Azure. Getting started with Couchbase and Azure is easy and free. (You can even use the Test Drive button to get three hours of Couchbase Server without expending any Azure credit.) I created a single user called "viberchatbot" a bucket called "ViberChatBot" and I loaded the "travel-sample" bucket.

Azure Function

For this application, I wanted to create a chatbot with a little more substance than "Hello, world" and I also wanted to have a little fun. Here are the commands I want my chatbot to understand:

  • If I say "hi" (or hello, etc.), it will respond with "Howdy!"
  • If I ask for "metrics," it will tell me how many messages it's processed so far.
  • If I mention "twitter," it will make a recommendation about who to follow.
  • If I ask for flights from CMH to ATL (or other airports) it will tell me how many flights there are today (I will use the travel-sample bucket for this data).
  • If I say "help," it will give me a list of the above commands.

I decided not to use any natural language processing or parsing libraries. I'm just going to use simple if/else statements and some basic string matching. If you are planning to create a robust chatbot with rich capabilities, I definitely recommend checking out libraries and tools like LUIS, wit.ai, NLTK, and others.

Chatbot Code

I started by creating a few C# classes to represent the structure of the data that Viber will be sending to my serverless endpoint.

Viber Classes

This is not an exhaustive representation of Viber’s capabilities by far, but it’s enough to start receiving basic text messages.

public class ViberIncoming
{
    public string Event { get; set; }
    public long Timestamp { get; set; }
    public ViberSender Sender { get; set; }
    public ViberMessage Message { get; set; }
}

public class ViberSender
{
    public string Id { get; set; }
    public string Name { get; set; }
}

public class ViberMessage
{
    public string Text { get; set; }
    public string Type { get; set; }
}

Next, the Azure function will convert the raw HTTP request into a ViberIncoming object.

[FunctionName("Chatbot")]
public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req,
    TraceWriter log)
{
    var incoming = req.Content.ReadAsAsync<ViberIncoming>().Result;

    var viber = new ViberProcessor(Bucket.Value);
    viber.Process(incoming);

    // return "OK" each time
    // this is most important for the initial Viber webhook setup
    return req.CreateResponse(HttpStatusCode.OK);
}

After this, I created a ViberProcessor class with a Process method that receives this object.

public void Process(ViberIncoming incoming)
{
    if (incoming?.Message?.Type == "text")
    {
        LogIncoming(incoming);
        ProcessMessage(incoming);
    }
}

Processing Viber Messages

LogIncoming creates a record (in Couchbase) so that I know everything about each request that comes in.

ProcessMessage will analyze the text of the message and figure out what to do in response. You can check out the complete code on GitHub, but here’s a brief snippet to give you the idea:

// if the message contains "hi", "hello", etc say "howdy"
else if (HelloStrings.Any(incoming.Message.Text.ToLower().Contains))
    SendTextMessage("Howdy!", incoming.Sender.Id);
// if message contains "?" then link to the forums
else if (incoming.Message.Text.Contains("?"))
    SendTextMessage("If you have a Couchbase question, please ask on the forums! http://forums.couchbase.com", incoming.Sender.Id);
else
    SendTextMessage("I'm sorry, I don't understand you. Type 'help' for help!", incoming.Sender.Id);

Getting Metrics

One of the things my chatbot listens for is “metrics.” When you ask it for metrics, it will give you a count of the incoming messages that it’s processed. Since I’m logging every request to Couchbase, querying for metrics is easily done with an N1QL query.

Sending a Message Back

The chatbot needs to communicate back to the person who’s talking to it. As I said earlier, there is no Viber.NET SDK, so I have to create a REST call “manually.” This is easy enough with RestSharp:

private void SendTextMessage(string message, string senderId)
{
    var client = new RestClient("https://chatapi.viber.com/pa/send_message");
    var request = new RestRequest(RestSharp.Method.POST);
    request.AddJsonBody(new
    {
        receiver = senderId,    // receiver(Unique Viber user id, required)
        type = "text",          // type(Message type, required) Available message types: text, picture, etc
        text = message
    });
    request.AddHeader("X-Viber-Auth-Token", ViberKey);
    var response = client.Execute(request);

    // log to Couchbase
    _bucket.Insert("resp::" + Guid.NewGuid(), response.Content);
}

Note that I’m also logging each response from Viber to Couchbase. This could be very useful information for later analysis and/or troubleshooting. If Viber decides to change the structure and content of their response, the data in Couchbase is all stored as flexible JSON data. You will not get any surprise errors or missing data at this ingestion point.

Summary

That's all the basics. Check out the source code for the complete set of actions/operations that the chatbot can do. To test out the bot, I used my Viber app for Android on my phone (and my wife's, to make sure it worked when I went public).

Beware: By the time you read this, the chatbot I created will likely be taken offline. Anyone else who creates a "Couchbase Bot" is not me!

Here's a recap of the benefits of this approach to creating a chatbot:

  • The serverless approach is a good way to control costs of a chatbot. Whether it's Viber or some other messaging platform, there is potential for sporadic and cyclic use.
  • Viber's REST API utilizes JSON, which makes Couchbase a natural fit for tracking/storing/querying.
  • Couchbase's ease of scaling and partnerships with Microsoft (and Amazon and Google) make it a great choice for a chatbot backend.

This was really fun, and I could definitely get carried away playing with this new chatbot. It could analyze images, tell jokes, look up all kinds of information, sell products and services, or any number of useful operations.

I would love to hear what you're doing with chatbots! Please leave a comment or contact me on Twitter @mgroves.

TrueSight is an AIOps platform, powered by machine learning and analytics, that elevates IT operations to address multi-cloud complexity and the speed of digital transformation.

Topics:
ai ,chatbot ,couchbase ,viber ,bot development ,nlp ,machine learning ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}