Setting Up A Webex Bot

Tags: bot, python

Contents


This post contains some rough notes on setting up a basic Webex bot.

Creating A Bot Account

The documentation for Webex bots is at https://developer.webex.com/docs/bots. Clicking the ‘Create Bot’ button you arrive at the following page (you will need to sign in/create an account).

Webex create bot page

Fill in this form and select ‘Add Bot’ at the bottom of the page. Take note of the bot access token (this allows you to control the bot’s actions - don’t commit to version control!).

Let’s next look into how to receive notifications for events (such as messages being sent to the bot).

Minimal Flask Server

Check out https://developer.webex.com/docs/api/guides/webhooks for setting up a webhook (i.e. subscribing to a certain type of notification). To do this you will need to provide a web address where you will be receiving POST requests (e.g. set up with AWS - this is out of scope of this post). For example, create a POST request to https://webexapis.com/v1/webhook containing:

{
  "name": "New message received",
  "targetUrl": "http://mydomain.com:8080/bot/message",
  "resource": "messages",
  "event": "created"
}

Refer to https://developer.webex.com/docs/api/guides/webex-meetings-rest-api and https://developer.webex.com/docs/api/basics.

You can then implement the server script to handle these POST requests at the given address. Using Flask (python library) this might look something like the following (see https://flask.palletsprojects.com/en/1.1.x/quickstart/#a-minimal-application).

from flask import Flask, request
import requests
from requests_toolbelt import MultipartEncoder

app = Flask(__name__)

ACCESS_TOKEN = "..."  # Fill in from bot create page

@app.route('/bot/message')
def handle_message():
    data = request.get_json()["data"]
    msg = "I'm *very* excited"
    multipart = MultipartEncoder(
        {"markdown": msg, "personId": data["personId"]}
    )
    response = requests.post(
        "https://api.ciscospark.com/v1/messages",
        data=multipart,
        headers={
            "Authorization": f"Bearer {ACCESS_TOKEN}",
            "Content-Type": multipart.content_type,
        },
    )
    response.raise_for_status()

app.run(port=8080)

This should then be run on the server that can be located on the public internet by Webex at the address you provided (‘mydomain.com’ in the example webhook request above). It can be run as any Python script, although note the dependency on flask, requests and requests_toolkit!

See https://github.com/LewisGaul/webex-bot-example or https://github.com/LewisGaul/minegauler/tree/master/server/bot for more complete examples.


Comments are currently closed