Over a million developers have joined DZone.

Building Bots Using Webhooks

DZone's Guide to

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.

· IoT Zone
Free Resource

Cisco IoT makes digital transformation a reality in factories, transportation, and utilities. Learn how to start integrating with Cisco DevNet.

It is really fascinating to see how chat bots 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.

Image title

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.

Image title

Image title

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. 


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.


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",
    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",
    request.add_header("Authorization", "Bearer "+bearer)
    contents = urllib2.urlopen(request).read()
    return contents

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())
                msg = format(res)
        if msg != None:
            print msg
            sendSparkPOST("https://api.ciscospark.com/v1/messages", {"roomId": webhook['data']['roomId'], "text": msg})
    return "true"

bot_email = "infrahealthbot@sparkbot.io"
bot_name = "infrahealthbot"
run_itty(server='wsgiref', host='', port=10010)


def get_disk_usage_values(*args):
    templ = "%-17s %8s %8s %8s %5s%% %9s  %s"
    print(templ % ("Device", "Total", "Used", "Free", "Use ", "Type",
    for part in psutil.disk_partitions(all=False):
        if os.name == 'nt':
            if 'cdrom' in part.opts or part.fstype == '':
        usage = psutil.disk_usage(part.mountpoint)
        print(templ % (
        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.

Questions or want to share your Cisco Spark bots building experience? Find me @YadavYogesh.

Happy coding!

Cisco is a software company. Surprised? Don’t be. Join DevNet to explore APIs, tools, and techniques that developers are using to add collaboration, IoT, security, network priority, and more!

bots ,webhooks ,artifical intelligence ,devops ,ci/cd ,devnet ,python

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


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

{{ parent.tldr }}

{{ parent.urlSource.name }}