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> """.format(get_catfact())) elif request.method == 'POST': """Respond to inbound webhook JSON HTTP POST from Cisco Spark.""" json_data = request.json # Get the POST data sent from Cisco Spark print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") webhook_obj = Webhook( json_data) # Create a Webhook object from the JSON data room = spark_api.rooms.get( webhook_obj.data.roomId) # Get the room details message = spark_api.messages.get( webhook_obj.data.id) # Get the message details person = spark_api.people.get( message.personId) # Get the sender's details print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = spark_api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return 'OK' else: # 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 print("SENDING CAT FACT '{}'".format(cat_fact)) spark_api.messages.create( room.id, text=cat_fact ) # Post the fact to the room where the request was received return 'OK'
def POST(self): """Respond to inbound webhook JSON HTTP POSTs from Cisco 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 print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return 'OK' else: # 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 print("SENDING CAT FACT '{}'".format(cat_fact)) api.messages.create( room.id, text=cat_fact ) # Post the fact to the room where the request was received return 'OK'
def errbot_spark(self, raw): signature = hmac.new(self._bot.webhook_secret.encode('utf-8'), raw.body.read(), hashlib.sha1).hexdigest() if signature != raw.get_header('X-Spark-Signature'): self.log.debug("X-Spark-Signature failed. Webhook will NOT be processed") else: webhook_event = Webhook(raw.json) bot_name = self._bot.bot_name if webhook_event.actorId == self._bot.bot_identifier.id: self.log.debug("Message created by bot...ignoring") else: # Need to load complete message from Spark as the webhook message only includes IDs # Can only retrieve messages targeted to the bot. User must type @<botname> <message>. message = spark_api.messages.get(webhook_event.data.id) # Get the message details #spark_api.messages.create(webhook_event.data.roomId, text="Welcome to the room!") room = spark_api.rooms.get(webhook_event.data.roomId) # Get the room details person = spark_api.people.get(message.personId) # Get the sender's details occupant = self._bot.get_occupant_using_id(person=person, room=room) # Strip the bot name from the message in order for errbot to process commands properly message_without_botname = message.text.replace(bot_name,"",1).lstrip() msg = self._bot.create_message(body=message_without_botname, frm=occupant, to=room, extras={'roomType': webhook_event.data.roomType}) # Force the bot to process the message and our job is done! self._bot.process_message(msg) return "OK"
def gerard(): if request.method == 'POST': webhook_obj = Webhook(request.json) print(request.json) return '', 200 else: abort(400)
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> </body> </html> """) elif request.method == 'POST': """Respond to inbound webhook JSON HTTP POST from Cisco Spark.""" json_data = request.json print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") webhook_obj = Webhook( json_data) # Create a Webhook object from the JSON data room = spark_api.rooms.get( webhook_obj.data.roomId) # Get the room details message = spark_api.messages.get( webhook_obj.data.id) # Get the message details person = spark_api.people.get( message.personId) # Get the sender's details print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = spark_api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return 'OK' else: # Message was sent by someone else; parse message and respond. tag = message.text.replace(" ", "+") data = json.loads( urllib.request.urlopen( "http://api.giphy.com/v1/gifs/random?tag=" + tag + "&api_key=" + giphyapikey + "&rating=" + rating).read()) api.message.create( roomId=message.roomId, files=data['data']['image_url']) # Post the gif! return 'OK'
def POST(): print("INFO: New HTTP POST request received.") # Creating webhook object try: webhook = Webhook(web.data()) except SparkApiError as err: print("WARNING: Invalid server request, not a JSON format.") print(err) return # Loop prevention, do not react to events triggered by myself if webhook.actorId == p.me.id: return print("INFO: Spark webhook received - {0} {1}.".format(webhook.resource, webhook.event)) # Memberships event if webhook.resource == "memberships": # Register only if the person is me and not others if webhook.data.personId != p.me.id: print("INFO: Event concerning somebody else, skipping.") return if webhook.event == "created": insert_room(webhook.data) elif webhook.event == "deleted": r = p.db.select_room([webhook.data.roomId]) if not r: msg = "ERROR: Cannot get the room data - '{0}'.".format(webhook.data.roomId) print(msg) send_message(p.admin, msg) return update_room(r) else: print("WARNING: Unknown memberships webhook event, discarding request.") # Messages event elif webhook.resource == "messages": if webhook.event == "created": process_message(webhook.data) elif webhook.event == "deleted": message_deleted(webhook.data) else: print("WARNING: Unknown messages webhook event, discarding request.") # Unknown event else: print("WARNING: Unknown webhook event, discarding event.")
def webex_teams_webhook_events(): """Respond to inbound webhook JSON HTTP POST from Webex Teams.""" # Get the POST data sent from Webex Teams json_data = request.json print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. print("THIS IS FROM ME!") return 'OK' else: # Message was sent by someone else; parse message and respond. if "today" in message.text: print("FOUND 'today'") # Get a forcast forcast = get_forcasts()[0] message = "今日の天気は{}".format(forcast['telop']) print("SENDING A MESSAGE '{}'".format(message)) # Post the message to the room where the request was received api.messages.create(room.id, text=message) return 'OK'
def api_root(): if request.method == 'GET': response = { 'message': 'Cisco Spark bot is up and running', 'started': str(started), 'path': path, 'token': "................" + bot.get_id()[-10:] } return jsonify(response) elif request.method == 'POST': hook = Webhook(request.json) print('launch on_hook thread') thread = threading.Thread(target=bot.on_hook, args=[hook]) thread.daemon = True thread.start() print('send response to Spark Cloud') response = 'Seems to be ok' return response
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:") log.info(json_data) log.info("\n") webhook_obj = Webhook( json_data) # Create a Webhook object from the JSON data room = spark_api.rooms.get(webhook_obj.data.roomId) # Get the room details message = spark_api.messages.get( webhook_obj.data.id) # Get the message details person = spark_api.people.get(message.personId) # Get the sender's details log.info("NEW MESSAGE IN ROOM '{}'".format(room.title)) log.info("FROM '{}'".format(person.displayName)) log.info("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = spark_api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return {'Message': 'OK'} else: # Message was sent by someone else; parse message and respond. if "/CHUCKNORRIS" in message.text: log.info("FOUND '/CHUCKNORRIS'") chuck_norris_joke = get_chuck_norris_joke( ) # Get a Chuck Norris Joke log.info( "SENDING CHUCK NORRIS JOKE '{}'".format(chuck_norris_joke)) spark_api.messages.create( room.id, text=chuck_norris_joke ) # Post the fact to the room where the request was received return {'Message': 'OK'}
def webhook(request): #fat=open ("apic_em/at.txt","r+") #at=fat.readline().rstrip() #fat.close at = os.environ['SPARK_AT'] print (at) api = CiscoSparkAPI(at) #print (json.loads(request.body.decode('utf-8'))) """Respond to inbound webhook JSON HTTP POSTs from Cisco Spark.""" json_data = json.loads(request.body.decode('utf-8')) # 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 print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return 'OK' else: # Message was sent by someone else; parse message and respond. if "get config" in message.text: print("FOUND 'config'") config = get_config() # Get the config print("SENDING config '{}'".format(config)) response_message = api.messages.create(room.id, text=config) # Post the fact to the room where the request was received return
def techxbot(): ''' This is the Web Server URI for the Call to bot from Web Hook http://<PUBLIC-IP>:5105/techx/ This info should be configured at the webhook on developer.ciscospark.com ''' #Local Variables data = { } #LOCAL DATA DICTIONARY TO BUILD THE PAYLOAD TO SEND BACK TO SPARK msg = '' #THIS WILL BE THE MSG TO BE POSTED AT SPARK ROOM url = '' logger = logging.getLogger('cliveBot.WebHook') #Techx.bot Instance webhook = request.json #INFO FROM SPARK IN JSON FORMAT #print(webhook['data']['personId']) #Clive Instance req_room = webhook['data']['roomId'] if req_room != os.environ['SLG_ROOM']: #print('Ctach Non SLSG') return {"status_code": 203} clive_token = clus_tkn if not clive_token: clive_token = os.environ['SPARK_ACCESS_TOKEN'] logger.warning( 'Using the embeeded token. Please check environmentals variables') clive = CiscoSparkAPI(access_token=clive_token) clive_wh = Webhook(webhook) room = clive.rooms.get(clive_wh.data.roomId) message = clive.messages.get(clive_wh.data.id) person = clive.people.get(message.personId) me = clive.people.me() files = [] try: if message.personId == me.id: #logger.warning('Can send a message to myself') return {"status_code": 500} else: logger.info('Receiving Data from Spark Room {}'.format(room.title)) bot = theBot() logger.info('Sending Order to Bot: {}'.format(str(message.text))) resp = bot.getOrders(person.id, message.text, room.id) msg = resp['msg'] if not msg: msg = '.' if resp['files'] != '': files.append(resp['files']) clive.messages.create(room.id, markdown=msg, files=files) else: clive.messages.create(room.id, markdown=msg) logger.info('Order executed') respo = {"status_code": 200} except (TypeError, ValueError, Exception) as e: msg = "Unable to execute the task" clive.messages.create(room.id, text=msg) logger.error("Communication Error with Clive message:{}".format(e)) respo = {"status_code": 500} return respo
def sparkwebhook(): if request.method == 'POST': json_data = request.json print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") webhook_obj = Webhook(json_data) # Details of the message created room = spark_api.rooms.get(webhook_obj.data.roomId) message = spark_api.messages.get(webhook_obj.data.id) person = spark_api.people.get(message.personId) email = person.emails[0] print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # Message was sent by the bot, do not respond. # At the moment there is no way to filter this out, there will be in the future me = spark_api.people.me() if message.personId == me.id: return 'OK' else: string = message.text.replace(',', '') string = string.replace('.', '') string = string.lower() words = string.split(' ') x = 0 i = 0 while (i < len(words) and x == 0): word = words[i] if (type != []): if (word == 'yes'): type.remove(1) spark_api.messages.create(room.id, text=random.choice( interaction['another'])) x = 1 elif (word == 'no'): spark_api.messages.create(room.id, text=random.choice( interaction['goodbye'])) sys.exit(0) else: if (word == 'yes'): if (interaction[word] != []): s = str(random.choice(interaction[word])) interaction[word].remove(s) x = str(random.choice(interaction[used[-1]])) query.append(x) interaction[used[-1]].remove(x) s = s + x spark_api.messages.create(room.id, text=s) x = 1 elif (word == 'no'): r = str(response[query[-1]]) r = r.replace('[', '') r = r.replace(']', '') r = str(r[1:-1]) r = r + ' ' w = str(interaction['nextquery']) w = w.replace('[', '') w = w.replace(']', '') w = str(w[1:-1]) r = r + w type.append(1) x = 1 spark_api.messages.create(room.id, text=r) elif (word in interaction): used.append(word) if (interaction[word] != []): s = random.choice(interaction[word]) query.append(s) spark_api.messages.create(room.id, text=s) interaction[word].remove(s) x = 1 i = i + 1 if (x == 0): spark_api.messages.create(room.id, text=random.choice( interaction['generic'])) else: print('received none post request, not handled!')
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>Status:</p> <blockquote> {} </blockquote> </body> </html> """.format("test is good")) elif request.method == 'POST': """Respond to inbound webhook JSON HTTP POST from Cisco Spark.""" json_data = request.json print("json_data", json_data) webhook_obj = Webhook(json_data) print("webhook_ojb", webhook_obj) room_id = webhook_obj.data.roomId print("room_id", room_id) room = spark_api.rooms.get(room_id) print("room", room) data_id = webhook_obj.data.id print("data_id", data_id) try: message = spark_api.messages.get(data_id) print("message", message) except Exception as e: print("exception", e) return 'OK' person_id = message.personId print("person_id", person_id) person = spark_api.people.get(person_id) print("person", person) message_text = message.text print("messsage_text", message_text) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = spark_api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return 'OK' else: print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message_text)) create_msg = "Processing {}".format(message_text) send_message(room_id, create_msg) print("posting msg", message_text) try: result = requests.post(MP_POST_URL, data=message_text) if result.ok: result = result.text if result: send_message(room_id, str(result)) send_message(room_id, "Done") except ConnectionError as e: send_message(room_id, str(e)) return 'OK'