Skip to content

Commit 591b95b

Browse files
committed
Update Examples
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.
1 parent 4829bcb commit 591b95b

File tree

8 files changed

+190
-108
lines changed

8 files changed

+190
-108
lines changed

examples/bot-example-flask.py

Lines changed: 35 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -25,65 +25,73 @@
2525
"""
2626

2727

28-
from __future__ import (absolute_import, division,
29-
print_function, unicode_literals)
28+
# Use future for Python v2 and v3 compatibility
29+
from __future__ import (
30+
absolute_import,
31+
division,
32+
print_function,
33+
unicode_literals,
34+
)
3035
from builtins import *
3136

32-
import json
3337

34-
import requests
38+
__author__ = "Chris Lunsford"
39+
__author_email__ = "[email protected]"
40+
__contributors__ = ["Brad Bester <[email protected]>"]
41+
__copyright__ = "Copyright (c) 2016-2018 Cisco and/or its affiliates."
42+
__license__ = "MIT"
43+
3544

3645
from flask import Flask, request
46+
import requests
3747

3848
from ciscosparkapi import CiscoSparkAPI, Webhook
3949

4050

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

4454

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

4959

50-
urls = ('/sparkwebhook', 'webhook')
51-
52-
5360
# Helper functions
5461
def get_catfact():
55-
"""Get a cat fact from appspot.com and return it as a string.
62+
"""Get a cat fact from catfact.ninja and return it as a string.
5663
5764
Functions for Soundhound, Google, IBM Watson, or other APIs can be added
5865
to create the desired functionality into this bot.
5966
6067
"""
6168
response = requests.get(CAT_FACTS_URL, verify=False)
62-
response_dict = json.loads(response.text)
63-
return response_dict['facts'][0]
69+
response.raise_for_status()
70+
json_data = response.json()
71+
return json_data['fact']
6472

6573

6674
# Core bot functionality
6775
@flask_app.route('/sparkwebhook', methods=['GET', 'POST']) # Your Spark webhook should point to http://<serverip>:5000/sparkwebhook
6876
def sparkwebhook():
6977
"""Processes incoming requests to the '/sparkwebhook' URI."""
7078
if request.method == 'GET':
71-
return (""" <!DOCTYPE html>
72-
<html lang="en">
73-
<head>
74-
<meta charset="UTF-8">
75-
<title>Spark Bot served via Flask</title>
76-
</head>
77-
<body>
78-
<p>
79-
<strong>Your Flask web server is up and running!</strong>
80-
</p>
81-
<p>
82-
Here is a nice Cat Fact for you:
83-
</p>
84-
<blockquote> {} </blockquote>
85-
</body>
86-
</html>
79+
return ("""<!DOCTYPE html>
80+
<html lang="en">
81+
<head>
82+
<meta charset="UTF-8">
83+
<title>Spark Bot served via Flask</title>
84+
</head>
85+
<body>
86+
<p>
87+
<strong>Your Flask web server is up and running!</strong>
88+
</p>
89+
<p>
90+
Here is a nice Cat Fact for you:
91+
</p>
92+
<blockquote>{}</blockquote>
93+
</body>
94+
</html>
8795
""".format(get_catfact()))
8896
elif request.method == 'POST':
8997
"""Respond to inbound webhook JSON HTTP POST from Cisco Spark."""

examples/bot-example-webpy.py

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,22 @@
2525
"""
2626

2727

28-
from __future__ import print_function
29-
from builtins import object
28+
# Use future for Python v2 and v3 compatibility
29+
from __future__ import (
30+
absolute_import,
31+
division,
32+
print_function,
33+
unicode_literals,
34+
)
35+
from builtins import *
36+
37+
38+
__author__ = "Brad Bester"
39+
__author_email__ = "[email protected]"
40+
__contributors__ = ["Chris Lunsford <[email protected]>"]
41+
__copyright__ = "Copyright (c) 2016-2018 Cisco and/or its affiliates."
42+
__license__ = "MIT"
3043

31-
import json
3244

3345
import web
3446
import requests
@@ -37,38 +49,39 @@
3749

3850

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

4254

4355
# Global variables
44-
urls = ('/sparkwebhook', 'webhook') # Your Spark webhook should point to http://<serverip>:8080/sparkwebhook
45-
app = web.application(urls, globals()) # Create the web application instance
46-
api = CiscoSparkAPI() # Create the Cisco Spark API connection object
56+
urls = ('/sparkwebhook', 'webhook') # Your Spark webhook should point to http://<serverip>:8080/sparkwebhook
57+
app = web.application(urls, globals()) # Create the web application instance
58+
api = CiscoSparkAPI() # Create the Cisco Spark API connection object
4759

4860

4961
def get_catfact():
50-
"""Get a cat fact from appspot.com and return it as a string.
62+
"""Get a cat fact from catfact.ninja and return it as a string.
5163
5264
Functions for Soundhound, Google, IBM Watson, or other APIs can be added
5365
to create the desired functionality into this bot.
5466
5567
"""
5668
response = requests.get(CAT_FACTS_URL, verify=False)
57-
response_dict = json.loads(response.text)
58-
return response_dict['facts'][0]
69+
response.raise_for_status()
70+
json_data = response.json()
71+
return json_data['fact']
5972

6073

6174
class webhook(object):
6275
def POST(self):
6376
"""Respond to inbound webhook JSON HTTP POSTs from Cisco Spark."""
64-
json_data = web.data() # Get the POST data sent from Spark
77+
json_data = web.data() # Get the POST data sent from Spark
6578
print("\nWEBHOOK POST RECEIVED:")
6679
print(json_data, "\n")
6780

68-
webhook_obj = Webhook(json_data) # Create a Webhook object from the JSON data
69-
room = api.rooms.get(webhook_obj.data.roomId) # Get the room details
70-
message = api.messages.get(webhook_obj.data.id) # Get the message details
71-
person = api.people.get(message.personId) # Get the sender's details
81+
webhook_obj = Webhook(json_data) # Create a Webhook object from the JSON data
82+
room = api.rooms.get(webhook_obj.data.roomId) # Get the room details
83+
message = api.messages.get(webhook_obj.data.id) # Get the message details
84+
person = api.people.get(message.personId) # Get the sender's details
7285

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

93106

examples/people.py

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#!/usr/bin/env python
22
# -*- coding: utf-8 -*-
3-
""" Script to demostrate the use of ciscosparkapi for the people API
3+
""" Script to demonstrate the use of ciscosparkapi for the people API
44
55
The package natively retrieves your Spark access token from the
66
SPARK_ACCESS_TOKEN environment variable. You must have this environment
@@ -9,28 +9,43 @@
99
"""
1010

1111

12-
from __future__ import print_function
12+
# Use future for Python v2 and v3 compatibility
13+
from __future__ import (
14+
absolute_import,
15+
division,
16+
print_function,
17+
unicode_literals,
18+
)
19+
from builtins import *
20+
21+
22+
__author__ = "Jose Bogarín Solano"
23+
__author_email__ = "[email protected]"
24+
__contributors__ = ["Chris Lunsford <[email protected]>"]
25+
__copyright__ = "Copyright (c) 2016-2018 Cisco and/or its affiliates."
26+
__license__ = "MIT"
27+
28+
1329
from ciscosparkapi import CiscoSparkAPI
1430

1531

16-
try:
17-
api = CiscoSparkAPI() # Create a CiscoSparkAPI connection object; uses your SPARK_ACCESS_TOKEN
18-
except Exception as e:
19-
print(e)
32+
api = CiscoSparkAPI() # Create a CiscoSparkAPI connection object; uses your SPARK_ACCESS_TOKEN environment variable
2033

2134

2235
# Get my user information
2336
print("Get my information ...")
2437
me = api.people.me()
2538
print(me)
2639

27-
# Get my user information using id
40+
41+
# Get my user information using my id
2842
print("Get my information but using id ...")
2943
me_by_id = api.people.get(me.id)
3044
print(me_by_id)
3145

46+
3247
# Get my user information using id
33-
print("Get the list of people I know ...")
34-
people = api.people.list(displayName="Jose") # Creates a generator container (iterable) that lists the people I know
48+
print("Get the list of people I know...")
49+
people = api.people.list(displayName="Jose") # Creates a generator container (iterable) that lists the people I know
3550
for person in people:
36-
print(person.displayName) # Return the displayName of every person found
51+
print(person.displayName) # Return the displayName of every person found

examples/pyramidSparkBot/README.rst

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ Documentation
33

44
A simple bot script, built on Pyramid using Cornice
55

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

1011
ngrok (https://ngrok.com/) can be used to tunnel traffic back to your server
1112
if your machine sits behind a firewall.

examples/pyramidSparkBot/pyramidSparkBot/__init__.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
1-
"""Main entry point
2-
"""
1+
# -*- coding: utf-8 -*-
2+
"""Main entry point."""
3+
4+
5+
__author__ = "Jose Bogarín Solano"
6+
__author_email__ = "[email protected]"
7+
__contributors__ = ["Chris Lunsford <[email protected]>"]
8+
__copyright__ = "Copyright (c) 2016-2018 Cisco and/or its affiliates."
9+
__license__ = "MIT"
10+
11+
312
from pyramid.config import Configurator
413

514

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

examples/pyramidSparkBot/pyramidSparkBot/views.py

Lines changed: 41 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
# -*- coding: utf-8 -*-
12
"""A simple bot script, built on Pyramid using Cornice
23
3-
This sample script leverages the Pyramid web framework (https://trypyramid.com/) with
4-
Cornice (https://cornice.readthedocs.io). By default the web server will be reachable at
5-
port 6543 you can change this default if desired (see `pyramidSparkBot.ini`).
4+
This sample script leverages the Pyramid web framework https://trypyramid.com/
5+
with Cornice https://cornice.readthedocs.io. By default the web server will be
6+
reachable at port 6543 you can change this default if desired
7+
(see `pyramidSparkBot.ini`).
68
79
ngrok (https://ngrok.com/) can be used to tunnel traffic back to your server
810
if your machine sits behind a firewall.
@@ -19,25 +21,41 @@
1921
script.
2022
2123
This script supports Python versions 2 and 3.
24+
2225
"""
23-
from __future__ import (absolute_import, division,
24-
print_function, unicode_literals)
25-
from cornice import Service
2626

27+
28+
# Use future for Python v2 and v3 compatibility
29+
from __future__ import (
30+
absolute_import,
31+
division,
32+
print_function,
33+
unicode_literals,
34+
)
2735
from builtins import *
2836

29-
import json
3037

31-
import requests
38+
__author__ = "Jose Bogarín Solano"
39+
__author_email__ = "[email protected]"
40+
__contributors__ = [
41+
"Brad Bester <[email protected]>",
42+
"Chris Lunsford <[email protected]>",
43+
]
44+
__copyright__ = "Copyright (c) 2016-2018 Cisco and/or its affiliates."
45+
__license__ = "MIT"
46+
3247

3348
from ciscosparkapi import CiscoSparkAPI, Webhook
49+
from cornice import Service
50+
import requests
51+
3452

3553
import logging
3654
log = logging.getLogger(__name__)
3755

3856

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

4260

4361
# Initialize the environment
@@ -46,28 +64,35 @@
4664

4765
# Helper functions
4866
def get_catfact():
49-
"""Get a cat fact from catfacts-api.appspot.com and return it as a string.
67+
"""Get a cat fact from catfact.ninja and return it as a string.
68+
5069
Functions for Soundhound, Google, IBM Watson, or other APIs can be added
5170
to create the desired functionality into this bot.
71+
5272
"""
53-
response = requests.get(CAT_FACT_URL, verify=False)
54-
response_dict = json.loads(response.text)
55-
return response_dict['facts'][0]
73+
response = requests.get(CAT_FACTS_URL, verify=False)
74+
response.raise_for_status()
75+
json_data = response.json()
76+
return json_data['fact']
5677

5778

58-
sparkwebhook = Service(name='sparkwebhook', path='/sparkwebhook', description="Spark Webhook")
79+
sparkwebhook = Service(
80+
name='sparkwebhook',
81+
path='/sparkwebhook',
82+
description="Spark Webhook",
83+
)
5984

6085

6186
@sparkwebhook.get()
6287
def get_sparkwebhook(request):
6388
log.info(get_catfact())
6489
return {"fact": get_catfact()}
6590

66-
@sparkwebhook.post()
91+
6792
# Your Spark webhook should point to http://<serverip>:6543/sparkwebhook
93+
@sparkwebhook.post()
6894
def post_sparkwebhook(request):
6995
"""Respond to inbound webhook JSON HTTP POST from Cisco Spark."""
70-
7196
json_data = request.json # Get the POST data sent from Cisco Spark
7297
log.info("\n")
7398
log.info("WEBHOOK POST RECEIVED:")
@@ -99,4 +124,3 @@ def post_sparkwebhook(request):
99124
log.info("SENDING CAT FACT'{}'".format(catfact))
100125
spark_api.messages.create(room.id, text=catfact) # Post the fact to the room where the request was received
101126
return {'Message': 'OK'}
102-

0 commit comments

Comments
 (0)