-
Notifications
You must be signed in to change notification settings - Fork 16
/
bot_demo.py
70 lines (65 loc) · 2.91 KB
/
bot_demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from itty import *
import urllib2
import json
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. i.e.
/batman - replies to the room with text
/batcave - echoes the incoming text to the room
/batsignal - replies to the room with an image
"""
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 'batman' in in_message or "whoareyou" in in_message:
msg = "I'm Batman!"
elif 'batcave' in in_message:
message = result.get('text').split('batcave')[1].strip(" ")
if len(message) > 0:
msg = "The Batcave echoes, '{0}'".format(message)
else:
msg = "The Batcave is silent..."
elif 'batsignal' in in_message:
print "NANA NANA NANA NANA"
sendSparkPOST("https://api.ciscospark.com/v1/messages", {"roomId": webhook['data']['roomId'], "files": bat_signal})
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 = "[email protected]"
bot_name = "yourBotDisplayName"
bearer = "BOT BEARER TOKEN HERE"
bat_signal = "https://upload.wikimedia.org/wikipedia/en/c/c6/Bat-signal_1989_film.jpg"
run_itty(server='wsgiref', host='0.0.0.0', port=10010)