Need a chatbot in your custom app? – Here you go!

Introduction

Oracle offers a state-of-the-art intelligent chatbot which is not only already embedded in several Oracle applications but also can be used in any custom app.
Oracle provides specifc chatbot SDK’s for Javascript, IOS and Android, but Oracle’s chatbot can easily be used with any other platform as well.
This blog article discusses how the underlying technical interface can be used directly with any platform.

Main Article

Oracle chatbots can use any channel to interact with an user.
The technology used for that is called “Webhooks”.
A Webhook is a quite simple mechanism. It’s a HTTP URL on which a given app listens and other apps can communicate with it.
For Oracle’s chatbot the chatbot is publishing a HTTP URL to allow channels to send messages to the chatbot. And vice cersa the channel is publishing a HTTP URL to allow the chatbot to send messages back to the user.

As an example we will create a bot channel written in Python.

First thing to do is to create a channel for your chatbot in Oracle’s chatbot admin UI.

Choose “Webhook” as Channel Type.
Choose “1.1 (Conversational Model)” as Platform Version.
Specify the HTTP URL on which your channel is listening for messages to the user as Outbound Webhook URI. HTTPS need to be used.
Set the channel to enabled.

After channel creation you will see the webhook URL of the chatbot and a secret key in the channel details.
The Webhook URL together with the secret key will be used by the channel to send user messages to the chatbot.

Sending user messages to the chatbot is done by sending a HTTP POST request with a simple JSON payload and a SHA256 hashcode of the payload in the X-Hub-Signature HTTP header to the chatbot Webhook URL.
The payload looks like this:

{
  "userId": "12345",
  "messagePayload": {
    "type": "text",
    "text": "Hi"
  }
}

The SHA256-hashcode will be created with the hmac python library:

hmac.new( self.channelSecretKey.encode('utf-8'), payload, hashlib.sha256 ).hexdigest()

Receiving chatbot messages by the channel is done by listening to HTTP POST requests on the channel’s Webhook URL.
In the simplest case of pure text messages the JSON payload looks like this:

{
  "userid": "12345"
  "messagePayload": {
    "type": "text",
    "text": "Hi there!""
  }
}

If you have a simple chatbot which only uses text messages for user interaction you can use following python script to test your chatbot channel.
It will open a command line input prompt and allows you to send your input to the chatbot. In return it will display the chatbot response as command line output.
(You need to specify the WebhookURL and the SecretKey of your chatbot in the script)

#!/usr/local/bin/python3
import logging
import threading
import time
import requests
from flask import Flask, request, json, jsonify
import hmac
import hashlib

class Bot:
  """Oracle Bot Channel"""
  log = logging.getLogger('werkzeug')
  log.setLevel(logging.ERROR)
  webhookURL = "https://..."
  channelSecretKey = "..."
  prompt = 'bot> '
  srv = Flask(__name__)
  def startHTTPSrv(self):
    @self.srv.route("/", methods = ['GET', 'POST'])
    def handler():
      if request.method == 'GET':
        resp = jsonify({"status": "bot channel up and running"})
      elif request.method == 'POST':
        if request.headers['Content-Type'] == 'application/json':
          if request.json["messagePayload"]["type"] == 'text':
            print("\r%s\n%s" % (request.json["messagePayload"]["text"], self.prompt), end='')
            if "actions" in request.json["messagePayload"]:
              print("\r(", end='')
              for i in range(len(request.json["messagePayload"]["actions"])):
                if i != 0:
                  print(", ", end='')
                print("%s" % request.json["messagePayload"]["actions"][i]["label"], end='')
              print(")\n%s" % self.prompt, end='')
          elif request.json["messagePayload"]["type"] == 'card':
            print("\rRequest payload: %s\n%s" % (json.dumps(request.json), self.prompt), end='')
        resp = jsonify({"result": "ok"})
      resp.status_code = 200
      return resp
    t = threading.Thread(target=self.srv.run,name='httpsrv')
    t.daemon = True
    t.start()
  def buildSignatureHeader(self, payload):
    signature = hmac.new( self.channelSecretKey.encode('utf-8'), payload, hashlib.sha256 ).hexdigest()
    return 'sha256=' + signature
  def cmdloop(self):
    msg = input(self.prompt)
    while msg != "quit":
      self.send(msg)
      msg = input(self.prompt)
  def send(self, msg):
    payload = {
      "userId": "12345",
      "messagePayload": {
        "type": "text",
        "text": msg
        }
      }
    payload=json.dumps(payload).encode('utf-8')
    signature = self.buildSignatureHeader(payload)
    headers = {
      'X-Hub-Signature': signature,
      'ContentType': 'application/json; charset=utf-8'
      }
    r = requests.post(self.webhookURL, headers=headers, data=payload)
if __name__ == '__main__':
  Bot().startHTTPSrv()
  time.sleep(1)
  print('Welcome to Oracle Bot Channel ©2018@max-ateam')
  Bot().cmdloop()

For running the python test script locally on your PC you need to expose your local IP port 5000 to the internet with a developer tool like ngrok or lt (localtunnel):

ngrok http 5000

or

lt --port 5000 --subdomain <choose_your_own_subdomain_name> --print-requests

This will basically define the channel’s public internet facing webhook URL which you needed in the beginning to create the channel.

Summary

You have seen how easy it is to implement a chatbot integration into any custom app even if the app is not built with Javascript or natively for IOS/Android mobile devices.
The Webhook mechanism allows easy integration into almost any platform.

Add Your Comment