Building Bots Using Webhooks
Learn how to build your own bot using Cisco Spark Webhooks. This tutorial will take you from start to finish to get your bot up and running.
It is really fascinating to see how chatbots can automate contextual conversational interactions. According to Casey Newton from The Verge “Bots are here, they’re learning – and in 2016, they might eat the web”, which seems to be very realistic because there are thousands of bots out there and more are being developed that increase productivity, simplify the user experience, or are just for plain entertainment.
The majority of the bots as of today are simple commands to automate daily tasks. However, Artificial Intelligence (AI) powered bots are the future — you can build natural languages as services to communicate directly with customers to order food for example, and even pay for items entirely through it. AI stuff is bubbling with the explosive growth of social messaging, there is a real opportunity here to wire-up and manifest the bot to ride the bot wave. Bots are transforming users interactive conversion experience; giving an illusion of a real human being behind the interface. There are tons of bots related to shopping, restaurant visits, project management, etc. There are many more bots with different levels of complexity and artificial personas being developed each day.
Some bots can just be a source of real-time messaging — a platform that interacts with external applications, it’s not an AI bot, but it’s a bot for sharing just-in-time information/conversion. Below is one of the popular Cisco Spark bots that a development team in Cisco uses for tracking the build activity that passes through CI/CD pipeline. This bot keeps the development team up-to-date with activities related to Jenkins, Stash, SonarQube etc. Click here for more details.
Whether you are a new or experienced developer, this blog will help you create your Cisco Spark bot using webhooks and engage your imagination to build high-quality bots. Cisco Spark is a complete business collaboration service from the Cisco cloud that enables you to message, meet, or call anyone, anywhere, and anytime.
How to Get Started?
Spark Bot Demo blog helped me develop my first bot using webhooks (see MyBot01 below). The Spark Bot Demo blog will show you how to install the prerequisite technologies, create a Spark bot, how to obtain a Spark token, how to add it to a Spark room, and how to create an outbound Webhook. Everything that you need to know from bot registration to code upload and testing is covered. I developed my first Spark bot in a few simple steps, connected to the spark room, sent messages, and it responded back! It was a thrilling experience. Building a bot is not complicated; however once you get started it can become complicated.
After developing my first bot, I thought about adding complexity by teaching the bot how to respond to commands and provide real-time information. I wanted to build a bot that addresses the challenge of a team responsible for monitoring enterprise platforms and enabling them to fetch real-time platform infra health in the spark room where rest of the team members are available. Imagine having a bot that provides the health of infra on demand, again it’s not an AI bot, it’s just a simple bot example for sharing just-in-time information/conversion. I refactored my first blog python scripts to demonstrate a simple bot development framework with a potential use case to fetch Platform Infra Health.
InfraHealthBot
Platform Infra Health Bot is a sample bot that demonstrates the approach to build a bot using Cisco Spark webhooks to fetch disk usage information. This is a proof of concept that I build on top of Spark Demo Bot blog code and disk_usage python script. Planning to add features such as CPU usage, memory utilization, process management, etc. incrementally. You will find Infra Health Bot scripts on GitHub here.
- sendSparkGET Method is used for retrieving message text when the webhook is triggered with a message.
- sendSparkPOST Method is used to post a message to the spark room to confirm that a command was received and processed.
- Spark Bot identification details and bearer token is captured in the code.
- The example Webhook allows to POST/GET message to and from the spark room in which the bot is mentioned to the server using HTTP requests with a JSON payload. Learn more about Spark Webhooks on Cisco DevNet Learning Labs.
- get_disk_usage_values method utilizes python library in disk_usage.py script to retrieve information related to infra disk usage.
InfraHealthBot.py
def sendSparkGET(url): """ This method is used for: -retrieving message text, when the webhook is triggered with a message -Getting the username of the person who posted the message if a command is recognized """ request = urllib2.Request(url, headers={"Accept" : "application/json", "Content-Type":"application/json"}) request.add_header("Authorization", "Bearer "+bearer) contents = urllib2.urlopen(request).read() return contents def sendSparkPOST(url, data): """ This method is used for: -posting a message to the Spark room to confirm that a command was received and processed """ request = urllib2.Request(url, json.dumps(data), headers={"Accept" : "application/json", "Content-Type":"application/json"}) request.add_header("Authorization", "Bearer "+bearer) contents = urllib2.urlopen(request).read() return contents @post('/') def index(request): """ When messages come in from the webhook, they are processed here. The message text needs to be retrieved from Spark, using the sendSparkGet() function. The message text is parsed. If an expected command is found in the message, further actions are taken. """ webhook = json.loads(request.body) print webhook['data']['id'] result = sendSparkGET('https://api.ciscospark.com/v1/messages/{0}'.format(webhook['data']['id'])) result = json.loads(result) msg = None if webhook['data']['personEmail'] != bot_email: in_message = result.get('text', '').lower() in_message = in_message.replace(bot_name, '') if 'disk_usage' in in_message: res = (get_disk_usage_values()) print(res) msg = format(res) if msg != None: print msg sendSparkPOST("https://api.ciscospark.com/v1/messages", {"roomId": webhook['data']['roomId'], "text": msg}) return "true" ####CHANGE THESE VALUES##### bot_email = "infrahealthbot@sparkbot.io" bot_name = "infrahealthbot" bearer = "ZWFmZjJmNTItM2FlNS00NWVkLTg5ZTEtNjVhNWYwYzlhN2JlMGExYjBhNDUtZTFh" run_itty(server='wsgiref', host='0.0.0.0', port=10010)
disk_usage.py
def get_disk_usage_values(*args): templ = "%-17s %8s %8s %8s %5s%% %9s %s" print(templ % ("Device", "Total", "Used", "Free", "Use ", "Type", "Mount")) for part in psutil.disk_partitions(all=False): if os.name == 'nt': if 'cdrom' in part.opts or part.fstype == '': continue usage = psutil.disk_usage(part.mountpoint) print(templ % ( part.device, bytes2human(usage.total), bytes2human(usage.used), bytes2human(usage.free), int(usage.percent), part.fstype, part.mountpoint)) header01 = (templ % ("Device", "Total", "Used", "Free", "Use ", "Type","Mount")) sparkpart = part.device sparktot = bytes2human(usage.total) sparkused = bytes2human(usage.used) sparkfree = bytes2human(usage.free) sparkpct = int(usage.percent) sparktype = part.fstype sparkmtpt = part.mountpoint return (header01 + '\n' + sparkpart + " " + sparktot + " " + sparkused + " " + sparkfree + " " + str(sparkpct) + " " + sparktype + " " + sparkmtpt)
So there you have it, that’s how you can build a bot from scratch using Cisco Spark webhooks. However, there are alternatives to building a Spark bot using Cisco partners (for example Bot Builder platform like Gupshup.io) that allows you to create and deploy spark bots in a jiffy. You will be amazed to see how easy it is to build and deploy a bot on Cisco Spark. It is a fantastic platform meant to abstract away a lot of the underlying concepts and streamline the bot creation process. It takes care of scaling, hosting, analytics, content management and testing of the spark bot. Watch Cisco DevNet Innovators video below to know more about building bots with Cisco Spark and Gupshup.