def test_get_messages(self): room = Room.get(session, name=roomname) msgs = room.get_messages(session) print 'get messages from room {}'.format(room.title) for msg in msgs: print msg.text
def test_get_room_members(self): rooms = Room.get(session) self.assertIsInstance(rooms, list) self.assertTrue(len(rooms) > 1) members = rooms[0].get_members(session) self.assertIsInstance(members, list) self.assertTrue(len(rooms) > 1)
def test_create_message(self): message = Message() room = Room.get(session, name=roomname) message.text = 'test message from python sdk automated testing' room.send_message(session, message) resp = session.post(message.url(), message.json()) self.assertTrue(resp.ok)
def createRoomWebhook(self, roomname, webhookUrl, webhookName): webhook = Webhook() room = Room.get(self.session, name=roomname) webhook.set_targetUrl(webhookUrl) webhook.set_filter('roomId={}'.format(room.id)) webhook.set_name(webhookName) webhook.set_resource('messages') webhook.set_event('created') webhook.create(self.session) return webhook
def test_create_webhook(self): webhook = Webhook() room = Room.get(session, name=roomname) webhook.targetUrl ='http://foo.net/api/v1' webhook.filter = 'roomId={}'.format(room.id) webhook.name = 'python sdk testing webhook' webhook.resource = 'messages' webhook.event = 'created' webhook = webhook.create(session) self.assertIsInstance(webhook, Webhook)
def test_create_webhook(self): webhook = Webhook() room = Room.get(session, name=roomname) webhook.set_targetUrl('http://foo.net/api/v1') webhook.set_filter('roomId={}'.format(room.id)) webhook.set_name('python sdk testing webhook') webhook.set_resource('messages') webhook.set_event('created') resp = webhook.create(session) self.assertTrue(resp.ok)
def init(): global room,spark_room,spark_client, wanted_pokemon # get list of pokemon to send notifications for wanted_pokemon = _str( config.WANTED_POKEMON ) . split(" ,") # transform to lowercase wanted_pokemon = [a.lower() for a in wanted_pokemon] # get api key api_key = _str( config.SPARK_KEY ) if api_key: spark_client = Session('https://api.ciscospark.com', api_key) spark_room = config.SPARK_ROOM # pushbullet_client = Pushbullet(api_key) # channel = pushbullet_client.channels[0] try: spark_room = Room.get(spark_client, spark_room) except ValueError: exit(" Exiting as I failed to authenticate your Spark API key")
def sparci(spark_key, spark_room, apic_address, apic_user, apic_pass, action='all', user="", dn_filter="", debug=False): def on_message(ws, message): message = json.loads(message) message = message["imdata"][0]["aaaModLR"] print "Websocket Message: {descr}".format( descr=message["attributes"]["descr"]) spark_message = dedent(""" New APIC Event! {descr} DN: {affected} Change Set: {changeSet} """.format(**message["attributes"])).lstrip('\n').rstrip('\n') room.send_message(ss, spark_message) print " - Update sent to Spark room {room}".format(room=room) def on_error(ws, error): print error def on_close(ws): print "### closed ###" def on_open(ws): # Convert "all" to "" if action == "all": action_wcard = "" else: action_wcard = action query = dedent(""" https://{apic_address}/api/node/class/aaaModLR.json? subscription=yes& order-by=aaaModLR.created|desc& page=0& page-size=15& &query-target-filter= and( wcard(aaaModLR.user, "{user}"), wcard(aaaModLR.ind, "{action_wcard}"), wcard(aaaModLR.affected, "{dn_filter}") ) """.format(apic_address=apic_address, user=user, action_wcard=action_wcard, dn_filter=dn_filter)).replace('\n', '') resp = s.get(query, verify=False) if not resp.ok: exit("Failed to subscribe to aaaModLR") print "" print "===================================================" print "Sparci" print "===================================================" print "" print "Authenticating with Spark" ss = Session('https://api.ciscospark.com', spark_key) try: room = Room.get(ss, spark_room) except ValueError: exit(" Exiting as I failed to authenticate your Spark API key") if type(room) == list: print " So, I couldn't find the room {spark_room}, but I did find:".format( spark_room=spark_room) for r in room: print " -", r print " maybe try one of those?" exit() else: print " Found Spark room {room}".format(room=room) print "" print "Authenticating with APIC" data = {"aaaUser": {"attributes": {"name": apic_user, "pwd": apic_pass}}} s = requests.Session() s.headers.update({'Content-Type': 'application/json'}) r = s.post('https://{apic_address}/api/aaaLogin.json'.format( apic_address=apic_address), json=data, verify=False) if not r.ok: exit(" Failed to authenticate with APIC") auth = r.json()["imdata"][0]["aaaLogin"] token = auth["attributes"]["token"] print " Session token = {token}...".format( token=str.join('', token[0:15])) print "" print "===================================================" print "Subscribing to system audit logs" print "===================================================" print "" if action != "all": print "Action Filter:", action if user: print "User Filter:", user if dn_filter: print "Dn Filter:", dn_filter if debug: websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://{apic_address}/socket{token}".format( apic_address=apic_address, token=token), on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever()
def test_cleanup_after_testing(self): room = Room.get(session, name=roomname) room.delete(session)
def test_get_all_rooms(self): rooms = Room.get(session) self.assertIsInstance(rooms, list) self.assertTrue(len(rooms) > 1)
def getRoomMessages(self, roomname): room = Room.get(self.session, name=roomname) msgs = room.get_messages(self.session) return msgs
def getRoom(self, roomname): return Room.get(self.session, name=roomname)
def sparci(spark_key, spark_room, apic_address, apic_user, apic_pass, action='all', user="", dn_filter="", debug=False): def on_message(ws, message): message = json.loads(message) message = message["imdata"][0]["aaaModLR"] print "Websocket Message: {descr}".format(descr=message["attributes"]["descr"]) spark_message = dedent(""" New APIC Event! {descr} DN: {affected} Change Set: {changeSet} """.format(**message["attributes"])).lstrip('\n').rstrip('\n') room.send_message(ss, spark_message) print " - Update sent to Spark room {room}".format(room=room) def on_error(ws, error): print error def on_close(ws): print "### closed ###" def on_open(ws): # Convert "all" to "" if action == "all": action_wcard = "" else: action_wcard = action query = dedent(""" https://{apic_address}/api/node/class/aaaModLR.json? subscription=yes& order-by=aaaModLR.created|desc& page=0& page-size=15& &query-target-filter= and( wcard(aaaModLR.user, "{user}"), wcard(aaaModLR.ind, "{action_wcard}"), wcard(aaaModLR.affected, "{dn_filter}") ) """.format( apic_address=apic_address, user=user, action_wcard=action_wcard, dn_filter=dn_filter)).replace('\n', '') resp = s.get(query, verify=False) if not resp.ok: exit("Failed to subscribe to aaaModLR") print "" print "===================================================" print "Sparci" print "===================================================" print "" print "Authenticating with Spark" ss = Session('https://api.ciscospark.com', spark_key) try: room = Room.get(ss, spark_room) except ValueError: exit(" Exiting as I failed to authenticate your Spark API key") if type(room) == list: print " So, I couldn't find the room {spark_room}, but I did find:".format(spark_room=spark_room) for r in room: print " -", r print " maybe try one of those?" exit() else: print " Found Spark room {room}".format(room=room) print "" print "Authenticating with APIC" data = { "aaaUser": { "attributes": { "name": apic_user, "pwd": apic_pass } } } s = requests.Session() s.headers.update({'Content-Type': 'application/json'}) r = s.post('https://{apic_address}/api/aaaLogin.json'.format(apic_address=apic_address), json=data, verify=False) if not r.ok: exit(" Failed to authenticate with APIC") auth = r.json()["imdata"][0]["aaaLogin"] token = auth["attributes"]["token"] print " Session token = {token}...".format(token=str.join('', token[0:15])) print "" print "===================================================" print "Subscribing to system audit logs" print "===================================================" print "" if action != "all": print "Action Filter:", action if user: print "User Filter:", user if dn_filter: print "Dn Filter:", dn_filter if debug: websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://{apic_address}/socket{token}".format(apic_address=apic_address, token=token), on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever()
from spark.rooms import Room from spark.session import Session token = 'YOUR TOKEN HERE' roomname = 'YOUR ROOM NAME' url = 'https://api.ciscospark.com' session = Session(url, token) room = Room.get(session, name=roomname) msgs = room.get_messages(session) print 'get messages from room {}'.format(room.title) for msg in msgs: print msg.text
class SyslogUDPHandler(SocketServer.BaseRequestHandler): def handle(self): data = bytes.decode(self.request[0].strip()) socket = self.request[1] print( "%s : " % self.client_address[0], str(data)) logging.info(str(data)) room.send_message(ss, str(data)) if __name__ == "__main__": try: server = SocketServer.UDPServer((HOST,PORT), SyslogUDPHandler) print "Authenticating with Spark" try: ss = Session('https://api.ciscospark.com', SPARK_KEY) room = Room.get(ss, SPARK_ROOM) room.send_message(ss, '자 시작합니다.!!') except ValueError: exit(" Exiting as I failed to authenticate your Spark API key") server.serve_forever(poll_interval=0.5) except (IOError, SystemExit): raise except KeyboardInterrupt: print ("Crtl+C Pressed. Shutting down.")
def test_send_message_to_room(self): room = Room.get(session, name=roomname) resp = room.send_message(session, 'this is a str message') self.assertTrue(resp.ok)
def test_get_room_info(self): room = Room.get(session)[0] self.assertIsInstance(room.title, unicode) self.assertIsInstance(room.created, unicode)
from spark.rooms import Room from spark.messages import Message from spark.session import Session token = 'YOUR TOKEN HERE' roomname = 'YOUR ROOM NAME' url = 'https://api.ciscospark.com' session = Session(url, token) message = Message() room = Room.get(session, name=roomname) message.text = 'test message from python sdk automated testing' room.send_message(session, message)
def getRooms(self): rooms = Room.get(self.session) return rooms
def createMessage(self, roomname, messageTxt): room = Room.get(self.session, name=roomname) resp = room.send_message(self.session, messageTxt) if resp.status_code != 200 and resp.status_code != 201: raise RestException(resp.text, resp.status_code)
def test_get_room_by_name(self): room = Room.get(session, name=roomname) self.assertIsInstance(room, Room)