Monthly Archives: November 2017

Create Python Webhook for Chat BOT

As we all know chatbot is getting popular day by day. There are number of tools and platforms that support building chatbot.In this post we will see how we can create simple python webhook to work with bot platforms. For example,

  • Facebook Messenger
  • Slack
  • Telegram

These all platform provides front end for your chatbot. The frontend where user can type and see the messages from chatbot. But behind the scene there is something called webhook that powers your Chatbot. Read my blog about why Chatbots are so popular.

Why Chatbot is required?

What is a Python Webhook ?

A WebHook is an HTTP callback . An HTTP POST that occurs when something happens.  For chatbot webhook is constantly running process which will receive data from bot, process it and send result back.

When you are working with platforms like FB messenger or slack for chatbot, you have to create webhook and add it to platform. This webhook will listen for users message. As soon as it get message, it will process and send reply back to bot.

Python Webhook

For this post, I assume that you have Python installed in your system.

Install virtual environment

sudo pip install virtualenv

Create folder and activate virtual environment

mkdir DemoPythonWebhook

cd DemoPythonWebhook

source bvenv/bin/activate

Install Python Flask and other packages

pip install flask

sudo pip install requests

pip install json

sudo pip install CORS

Here requests are required for sending HTTP request from webhook, if required. JSON is not encode and decode json data. CORS are required in case you want to handle cross domain requests.

Create Webhook file

Now create new file with name webhook.py and add following code to it.

import requests
import json
from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route(‘/’, methods=[‘POST’])
def handle_incoming_messages():
data = request.json
message = data[‘message’]
if(message == ‘Hi’):
return json.dumps({
“reply” : “Hi, How are you?”
})
if __name__ == ‘__main__’:
app.run(host=’0.0.0.0′)

As you can see in above code, we have created flask app and configured it for handling cross platform request. We have specified app route.

@app.route(‘/’, methods=[‘POST’])

and here we have defined a method to handle in. In this method we are decoding JSON payload and sending appropriate response back.

To run this web hook, you can type following code in terminal

python webhook.py

That’s it and your webhook is running. You can use Ngrok to publish it or you can host it on AWS lambda. You can check following link on how to use Ngrok

How to use Ngrok?

Please note this is just an example code. In case you are working with FB messenger or any other platform, you have to change code according to platform, you are using.  Here are some resources in case you want to work on chatbot.

Facebook Messenger Platform for Bot

Slack Bot API

Progressive Web App – App Manifest

Welcome to Progressive Web App Series. If you have missed previous blog posts, please read from following links. In this blog post we will understand one of the important component of PWA, which is App Manifest, which is nothing but meta data about app.

  1. What Are Progressive Web Apps?
  2. Progressive Web App – App Shell

What is App Manifest?

The manifest allows developer to configure look and feel of PWA. For example if user saves it on home page, the icon will be displayed, that we can configure it in manifest. If you don’t add this file to PWA, user will not be able to save it on home page.

So you can configure app name, app icon, launch url etc. in this file. So user can distinguish it from other sites and apps. It’s JSON based file and following is the default structure of the file.

App Manifest

 

{
“name”: “PWA Demo”,
“short_name”: “PWA Demo”,
“icons”: [{
“src”: “images/pwaDemo.png”,
“sizes”: “192×192”,
“type”: “image/png”
}],
“start_url”: “/index.html”,
“display”: “standalone”,
“background_color”: “#3E4EB8”,
“theme_color”: “#2F3BA2″
}

After you create this file in your PWA, you have to link this to your html page. So browser will know about it and will use it’s metadata when users saves it on home page. Add following line to your head tag.

<link rel=”manifest” href=”/manifest.json”>

As you can see the structure of the manifest file, you can add title, short title and add number of icons. You can add different size of the icons for different mobile screens. For example for low resolution, you can add small icon.

{
“src”: “images/pwaDemo128.png”,
“type”: “image/png”,
“sizes”: “128×128”
}

Auto Generated Splash Screen

If you add above file in PWA and save it on home screen and open it, you will notice a splash screen coming up. That’s the magic of PWA. This splash screen is built with following things of manifest.

  • background_color
  • icon
  • name
  • theme_color

This splash screen will be displayed till its loading cached resources and other resources required to start the app.

The display property define the look and feel of app. If you set it as standalone, your app will be displayed in full screen and it you want top url bar to be displayed, you can set it as browser.

So by using this file, you can configure look and feel of your PWA app. In next post we will understand about service worker. You can also get more information about manifest from Google developers site.

Web Application Manifest

Microservice Architecture with Laravel and Lumen

Recently in Google DevFest Ahmedabad I got to learn about Microservice Architecture. So I decided to try and implement with Laravel. In this post I am going to explain about it.

What is Microservice Architecture?

It is a method of developing software applications as a suite of independently deployable, small, modular services in which each service runs a unique process and communicates through a well-defined, lightweight mechanism to serve a business goal.

So as definition suggest, it’s a set of independently deployable services. So how we can implement it with Laravel? Please check the diagram below.

Microservice Architecture

Microservice Architecture

Here first layer is a Laravel application, which act as API gateway. All the front ends call API Gateway URL, all the users are first authorized by API gateway. API gateway then calls respective service which is created in Laravel Lumen.

Gateway has sort of service repository which is nothing but singleton class which includes service metadata and hostnames. Using which it can determine which service to call.Here we are using Laravel Passport to authenticate and call service.

Gateway makes asynchronous requests to microservice which is nothing but API call. We don’t block any user request. Gateway  can also modify the service response if required and also can cache the request to make response faster.

This microservice will then execute and process the call and will return data in JSON format.  Each service is deployed as stand alone instance and have separate host name. The reason for using Lumen for service is it has all the features of Laravel and it’s fast and easy to scale and maintain and it’s ideal for making APIs.

Benefits of mircoservice architecture

There are number of benefits of mircoservice architecture.

Because each service is focused on only a small part they can be more lightweight and much faster performance-wise.

Also since it’s just API calls. It is possible to have different languages for different service. For example there could be notification service made in NodeJs. So it’s not necessary to be only Lumen or Laravel.

Each service can be scaled depending on usage. In short could be a good architecture for large application. In upcoming post I will show you how does this really work with example code.

Send Firebase Web Push Notification with NodeJs

NodeJs

Sending Web Push Notification using NodeJs

Recently I was exploring NodeJs for learning and I had bit tough time in figuring out how to send Firebase PushNotifications with NodeJs. In this blog, I am going explain how to do this.

What is Web Push Notification?

Web push notifications are clickable rich content messages sent to your device by a website or a web app. Push notifications are delivered to your mobile device or desktop, even when your browser is closed. These notifications can only be sent to users who have subscribed for these notifications from a specific website. As these notifications are pushed to user’s device, users don’t have to be present on the specific website to receive these notifications.

Push Notifications are best used for delivering content in a timely manner and engage users. Other common use cases include retargeting, activation and retention.

For this blog we assume that you have added Firebase registration process on server side and getting following three fields from your client app.

1) Auth Key

2) p256dh

3) Endpoint

You will get this three things when you register for web push notification with Firebase. You have to save this on server for sending push notifications.

First of all for sending web push notifications you will need to install npm module web-push

If you have not installed it yet. Please install it first.

npm install web-push –save

Now that you have it installed, use following code to send Web Push Notifications.
const webpush = require(‘web-push’);
const sub = {
            “keys” : {
                “auth” : “AUTH_KEY”,
                “p256dh” : “P256DH”
            },
            “endpoint” : “END_POINT”
    };
const params = {
        title: ‘Test title’,
        message: ‘Hi How are you doing?’
    };
webpush.setGCMAPIKey(‘YOUR_API_KEY);
webpush.sendNotification(sub, new Buffer(JSON.stringify(params), ‘utf8’))
         .then(
             function (data) {
                 console.log(“sucesss”);
             },
             function (err) {
                console.log(err);
             }
         )
         .catch(function (ex) {
             //return callback(new Error(ex), null);
         }
    );
That’s it and now you will be able to send PUSH notifications using NodeJs
Hope this helps you.