Skip to content

Commit

Permalink
Update Examples
Browse files Browse the repository at this point in the history
The cat fact API used in several of the examples is no longer responding.  Replace with catfact.ninja API (which is working as of now).

Ensure the future imports are done consistently.

Update script metadata (authors, contributors and copyright notices).

Lint examples and make PEP8 corrections.
  • Loading branch information
cmlccie committed Jan 6, 2018
1 parent 4829bcb commit 591b95b
Show file tree
Hide file tree
Showing 8 changed files with 190 additions and 108 deletions.
62 changes: 35 additions & 27 deletions examples/bot-example-flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,65 +25,73 @@
"""


from __future__ import (absolute_import, division,
print_function, unicode_literals)
# Use future for Python v2 and v3 compatibility
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
from builtins import *

import json

import requests
__author__ = "Chris Lunsford"
__author_email__ = "[email protected]"
__contributors__ = ["Brad Bester <[email protected]>"]
__copyright__ = "Copyright (c) 2016-2018 Cisco and/or its affiliates."
__license__ = "MIT"


from flask import Flask, request
import requests

from ciscosparkapi import CiscoSparkAPI, Webhook


# Module constants
CAT_FACTS_URL = 'http://catfacts-api.appspot.com/api/facts?number=1'
CAT_FACTS_URL = 'https://catfact.ninja/fact'


# Initialize the environment
flask_app = Flask(__name__) # Create the web application instance
spark_api = CiscoSparkAPI() # Create the Cisco Spark API connection object


urls = ('/sparkwebhook', 'webhook')


# Helper functions
def get_catfact():
"""Get a cat fact from appspot.com and return it as a string.
"""Get a cat fact from catfact.ninja and return it as a string.
Functions for Soundhound, Google, IBM Watson, or other APIs can be added
to create the desired functionality into this bot.
"""
response = requests.get(CAT_FACTS_URL, verify=False)
response_dict = json.loads(response.text)
return response_dict['facts'][0]
response.raise_for_status()
json_data = response.json()
return json_data['fact']


# Core bot functionality
@flask_app.route('/sparkwebhook', methods=['GET', 'POST']) # Your Spark webhook should point to http://<serverip>:5000/sparkwebhook
def sparkwebhook():
"""Processes incoming requests to the '/sparkwebhook' URI."""
if request.method == 'GET':
return (""" <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spark Bot served via Flask</title>
</head>
<body>
<p>
<strong>Your Flask web server is up and running!</strong>
</p>
<p>
Here is a nice Cat Fact for you:
</p>
<blockquote> {} </blockquote>
</body>
</html>
return ("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spark Bot served via Flask</title>
</head>
<body>
<p>
<strong>Your Flask web server is up and running!</strong>
</p>
<p>
Here is a nice Cat Fact for you:
</p>
<blockquote>{}</blockquote>
</body>
</html>
""".format(get_catfact()))
elif request.method == 'POST':
"""Respond to inbound webhook JSON HTTP POST from Cisco Spark."""
Expand Down
47 changes: 30 additions & 17 deletions examples/bot-example-webpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,22 @@
"""


from __future__ import print_function
from builtins import object
# Use future for Python v2 and v3 compatibility
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
from builtins import *


__author__ = "Brad Bester"
__author_email__ = "[email protected]"
__contributors__ = ["Chris Lunsford <[email protected]>"]
__copyright__ = "Copyright (c) 2016-2018 Cisco and/or its affiliates."
__license__ = "MIT"

import json

import web
import requests
Expand All @@ -37,38 +49,39 @@


# Module constants
CAT_FACTS_URL = 'http://catfacts-api.appspot.com/api/facts?number=1'
CAT_FACTS_URL = 'https://catfact.ninja/fact'


# Global variables
urls = ('/sparkwebhook', 'webhook') # Your Spark webhook should point to http://<serverip>:8080/sparkwebhook
app = web.application(urls, globals()) # Create the web application instance
api = CiscoSparkAPI() # Create the Cisco Spark API connection object
urls = ('/sparkwebhook', 'webhook') # Your Spark webhook should point to http://<serverip>:8080/sparkwebhook
app = web.application(urls, globals()) # Create the web application instance
api = CiscoSparkAPI() # Create the Cisco Spark API connection object


def get_catfact():
"""Get a cat fact from appspot.com and return it as a string.
"""Get a cat fact from catfact.ninja and return it as a string.
Functions for Soundhound, Google, IBM Watson, or other APIs can be added
to create the desired functionality into this bot.
"""
response = requests.get(CAT_FACTS_URL, verify=False)
response_dict = json.loads(response.text)
return response_dict['facts'][0]
response.raise_for_status()
json_data = response.json()
return json_data['fact']


class webhook(object):
def POST(self):
"""Respond to inbound webhook JSON HTTP POSTs from Cisco Spark."""
json_data = web.data() # Get the POST data sent from Spark
json_data = web.data() # Get the POST data sent from Spark
print("\nWEBHOOK POST RECEIVED:")
print(json_data, "\n")

webhook_obj = Webhook(json_data) # Create a Webhook object from the JSON data
room = api.rooms.get(webhook_obj.data.roomId) # Get the room details
message = api.messages.get(webhook_obj.data.id) # Get the message details
person = api.people.get(message.personId) # Get the sender's details
webhook_obj = Webhook(json_data) # Create a Webhook object from the JSON data
room = api.rooms.get(webhook_obj.data.roomId) # Get the room details
message = api.messages.get(webhook_obj.data.id) # Get the message details
person = api.people.get(message.personId) # Get the sender's details

print("NEW MESSAGE IN ROOM '{}'".format(room.title))
print("FROM '{}'".format(person.displayName))
Expand All @@ -85,9 +98,9 @@ def POST(self):
# Message was sent by someone else; parse message and respond.
if "/CAT" in message.text:
print("FOUND '/CAT'")
cat_fact = get_catfact() # Get a cat fact
cat_fact = get_catfact() # Get a cat fact
print("SENDING CAT FACT '{}'".format(cat_fact))
response_message = api.messages.create(room.id, text=cat_fact) # Post the fact to the room where the request was received
api.messages.create(room.id, text=cat_fact) # Post the fact to the room where the request was received
return 'OK'


Expand Down
35 changes: 25 additions & 10 deletions examples/people.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Script to demostrate the use of ciscosparkapi for the people API
""" Script to demonstrate the use of ciscosparkapi for the people API
The package natively retrieves your Spark access token from the
SPARK_ACCESS_TOKEN environment variable. You must have this environment
Expand All @@ -9,28 +9,43 @@
"""


from __future__ import print_function
# Use future for Python v2 and v3 compatibility
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
from builtins import *


__author__ = "Jose Bogarín Solano"
__author_email__ = "[email protected]"
__contributors__ = ["Chris Lunsford <[email protected]>"]
__copyright__ = "Copyright (c) 2016-2018 Cisco and/or its affiliates."
__license__ = "MIT"


from ciscosparkapi import CiscoSparkAPI


try:
api = CiscoSparkAPI() # Create a CiscoSparkAPI connection object; uses your SPARK_ACCESS_TOKEN
except Exception as e:
print(e)
api = CiscoSparkAPI() # Create a CiscoSparkAPI connection object; uses your SPARK_ACCESS_TOKEN environment variable


# Get my user information
print("Get my information ...")
me = api.people.me()
print(me)

# Get my user information using id

# Get my user information using my id
print("Get my information but using id ...")
me_by_id = api.people.get(me.id)
print(me_by_id)


# Get my user information using id
print("Get the list of people I know ...")
people = api.people.list(displayName="Jose") # Creates a generator container (iterable) that lists the people I know
print("Get the list of people I know...")
people = api.people.list(displayName="Jose") # Creates a generator container (iterable) that lists the people I know
for person in people:
print(person.displayName) # Return the displayName of every person found
print(person.displayName) # Return the displayName of every person found
7 changes: 4 additions & 3 deletions examples/pyramidSparkBot/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ Documentation

A simple bot script, built on Pyramid using Cornice

This sample script leverages the Pyramid web framework (https://trypyramid.com/) with
Cornice (https://cornice.readthedocs.io). By default the web server will be reachable at
port 6543 you can change this default if desired (see `pyramidSparkBot.ini`).
This sample script leverages the Pyramid web framework https://trypyramid.com/
with Cornice https://cornice.readthedocs.io. By default the web server will be
reachable at port 6543 you can change this default if desired
(see `pyramidSparkBot.ini`).

ngrok (https://ngrok.com/) can be used to tunnel traffic back to your server
if your machine sits behind a firewall.
Expand Down
14 changes: 11 additions & 3 deletions examples/pyramidSparkBot/pyramidSparkBot/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
"""Main entry point
"""
# -*- coding: utf-8 -*-
"""Main entry point."""


__author__ = "Jose Bogarín Solano"
__author_email__ = "[email protected]"
__contributors__ = ["Chris Lunsford <[email protected]>"]
__copyright__ = "Copyright (c) 2016-2018 Cisco and/or its affiliates."
__license__ = "MIT"


from pyramid.config import Configurator


Expand All @@ -8,4 +17,3 @@ def main(global_config, **settings):
config.include("cornice")
config.scan("pyramidSparkBot.views")
return config.make_wsgi_app()

58 changes: 41 additions & 17 deletions examples/pyramidSparkBot/pyramidSparkBot/views.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
# -*- coding: utf-8 -*-
"""A simple bot script, built on Pyramid using Cornice
This sample script leverages the Pyramid web framework (https://trypyramid.com/) with
Cornice (https://cornice.readthedocs.io). By default the web server will be reachable at
port 6543 you can change this default if desired (see `pyramidSparkBot.ini`).
This sample script leverages the Pyramid web framework https://trypyramid.com/
with Cornice https://cornice.readthedocs.io. By default the web server will be
reachable at port 6543 you can change this default if desired
(see `pyramidSparkBot.ini`).
ngrok (https://ngrok.com/) can be used to tunnel traffic back to your server
if your machine sits behind a firewall.
Expand All @@ -19,25 +21,41 @@
script.
This script supports Python versions 2 and 3.
"""
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from cornice import Service


# Use future for Python v2 and v3 compatibility
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
from builtins import *

import json

import requests
__author__ = "Jose Bogarín Solano"
__author_email__ = "[email protected]"
__contributors__ = [
"Brad Bester <[email protected]>",
"Chris Lunsford <[email protected]>",
]
__copyright__ = "Copyright (c) 2016-2018 Cisco and/or its affiliates."
__license__ = "MIT"


from ciscosparkapi import CiscoSparkAPI, Webhook
from cornice import Service
import requests


import logging
log = logging.getLogger(__name__)


# Module constants
CAT_FACT_URL = 'http://catfacts-api.appspot.com/api/facts?number=1'
CAT_FACTS_URL = 'https://catfact.ninja/fact'


# Initialize the environment
Expand All @@ -46,28 +64,35 @@

# Helper functions
def get_catfact():
"""Get a cat fact from catfacts-api.appspot.com and return it as a string.
"""Get a cat fact from catfact.ninja and return it as a string.
Functions for Soundhound, Google, IBM Watson, or other APIs can be added
to create the desired functionality into this bot.
"""
response = requests.get(CAT_FACT_URL, verify=False)
response_dict = json.loads(response.text)
return response_dict['facts'][0]
response = requests.get(CAT_FACTS_URL, verify=False)
response.raise_for_status()
json_data = response.json()
return json_data['fact']


sparkwebhook = Service(name='sparkwebhook', path='/sparkwebhook', description="Spark Webhook")
sparkwebhook = Service(
name='sparkwebhook',
path='/sparkwebhook',
description="Spark Webhook",
)


@sparkwebhook.get()
def get_sparkwebhook(request):
log.info(get_catfact())
return {"fact": get_catfact()}

@sparkwebhook.post()

# Your Spark webhook should point to http://<serverip>:6543/sparkwebhook
@sparkwebhook.post()
def post_sparkwebhook(request):
"""Respond to inbound webhook JSON HTTP POST from Cisco Spark."""

json_data = request.json # Get the POST data sent from Cisco Spark
log.info("\n")
log.info("WEBHOOK POST RECEIVED:")
Expand Down Expand Up @@ -99,4 +124,3 @@ def post_sparkwebhook(request):
log.info("SENDING CAT FACT'{}'".format(catfact))
spark_api.messages.create(room.id, text=catfact) # Post the fact to the room where the request was received
return {'Message': 'OK'}

Loading

0 comments on commit 591b95b

Please sign in to comment.