Example #1
0
def queue():
    try:
        data = flask.request.json
        if data:

            logger.debug('Initializing Spark API')
            if PRODUCTION:
                api = CiscoSparkAPI(QUEUE_BOT)
            else:
                from config import DEV_QUEUE_BOT
                api = CiscoSparkAPI(DEV_QUEUE_BOT)

            logger.debug('Spark API initialized')

            data = data['data']
            me_id = api.people.me().id

            if data.get('personId') != me_id and \
                    ((data.get('mentionedPeople') and me_id in data['mentionedPeople']) or
                     data.get('roomType') == 'direct'):
                logger.debug(pprint.pformat(data))
                BOT = Bot(api, data)
                BOT.handle_data(data)

            return ''

        else:
            return 'NO STOP PLEASE STOP'
    except Exception as e:
        if not PRODUCTION:
            raise
        print(traceback.format_exc())
        logger.error(traceback.format_exc())
        return '500 Internal Server Error'
Example #2
0
def Delete(name):
    try:
        with open('.config.txt') as json_file:
            data = json.load(json_file)
            bots = data['bots']
            newBot = []
            for bot in bots:
                if (bot['name'] == name):
                    token = bot['token']
                    id = bot['Id']
                    userToken = bot['userToken']
                    roomId = bot['roomId']
                else:
                    newBot.append(bot)
            newDoc = {"bots": []}
            with open('.tmp.txt', 'w') as outfile:
                json.dump(newDoc, outfile)
            os.remove('.config.txt')
            os.rename('.tmp.txt', '.config.txt')
        apiBot = CiscoSparkAPI(token)
        apiBot.rooms.delete(roomId)
        apiUser = CiscoSparkAPI(userToken)
        user = ApplicationAPI(apiUser._session)
        print(id)
        user.delete(id=id)
    except:
        print("Error")
Example #3
0
def InitBot():
    UserToken = str(raw_input("Please enter your CiscoSpark access token : "))
    BotName = str(raw_input("Please enter the bot name : "))
    BotEmailDef = BotName + "@sparkbot.io"
    BotEmail = str(
        raw_input("Please enter the bot email (default : " + BotEmailDef +
                  ") : "))
    if (BotEmail == ""):
        BotEmail = BotEmailDef
    BotLogoDef = "http://i.imgur.com/HQTF5FK.png"
    BotLogo = str(
        raw_input(
            "Please enter the bot logo (default : http://i.imgur.com/HQTF5FK.png) : "
        ))
    if (BotLogo == ""):
        BotLogo = BotLogoDef
    isAPI = str(
        raw_input(
            "Do you want your bot to be integrated with API.AI ? [y/n] : "))
    while (isAPI != "y" and isAPI != "n"):
        isAPI = str(
            raw_input(
                "Do you want your bot to be integrated with API.AI ? [y/n] : ")
        )
    print("Creating your bot ...")
    api = CiscoSparkAPI(UserToken)
    #try :
    bot = CreateBot(BotName, BotEmail, BotLogo, api)
    if (bot != "error"):
        print("Creating your test room ...")
        TestRoom = api.rooms.create('Test room for your bot : ' + bot.name)
        print("Adding your bot to the room ...")
        api.memberships.create(TestRoom.id, personEmail=bot.botEmail)
        Botapi = CiscoSparkAPI(bot.botToken)
        print("Sending first message ...")
        Botapi.messages.create(TestRoom.id,
                               text="Hi! I'm your new bot " + bot.name)
        CreateProject(bot.botToken, bot.name, bot.id, UserToken, TestRoom.id,
                      bot.botEmail, isAPI)
        print("Bot successfully created: [name : '" + bot.name +
              "', email: '" + bot.botEmail + "', id: '" + bot.id +
              "', token: '" + bot.botToken + "']")
        print("")
        if (isAPI == "y"):
            print("To begin with " + BotName +
                  ", run it with : python initBot.py launch " + BotName +
                  " <BotPort>")
        else:
            print("To begin with " + BotName +
                  ", run it with : python initBot.py run " + BotName +
                  " <BotPort>")
        print("")
        return (
            "Your bot was successfully created, and a TestRoom was created with your bot!"
        )
Example #4
0
def main():
    """Delete previous webhooks. If local ngrok tunnel, create a webhook."""
    spark_api = CiscoSparkAPI()
    delete_webhooks_with_name(spark_api, name=WEBHOOK_NAME)
    public_url = get_ngrok_public_url()
    if public_url is not None:
        create_ngrok_webhook(spark_api, public_url)
Example #5
0
def webhook_init():
    #Webhook attributes
    webhookname="brbuxton_Get_Config"
    resource="messages"
    event="created"
    url_suffix="/apic/sparkwebhook/"
    web_server="http://apic-em-webapp.apps.imapex.io"

    #grab the at from a local at.txt file instead of global variable
    #fat=open ("apic_em/at.txt","r+")
    #at=fat.readline().rstrip()
    #fat.close
    at = os.environ['SPARK_AT']
    print (at)

    api = CiscoSparkAPI(at)
    whid=findwebhookidbyname(api, webhookname)
    print (whid)
    Url=web_server+url_suffix

    if "not found" in whid:
        #create
        print ("not found")
        dict=api.webhooks.create(webhookname, Url, resource, event)
        print (dict)
    else:
        #update
        print (whid)
        dict=api.webhooks.update(whid, name=webhookname, targetUrl=Url)
        print (dict)

    return dict
Example #6
0
def spark_setup(email, token):
    # Setup the Spark Connection
    globals()["spark"] = CiscoSparkAPI(access_token=globals()["spark_token"])
    globals()["webhook"] = setup_webhook(globals()["bot_app_name"],
                                         globals()["bot_url"])
    sys.stderr.write("Configuring Webhook. \n")
    sys.stderr.write("Webhook ID: " + globals()["webhook"].id + "\n")
def alarms():
    try:
        PDT = pytz.timezone('America/Los_Angeles')
        data = json.loads(request.data)
        print(data)
        message = '''Team, Alarm event : **''' + data[
            'rule_name_display'] + '''** is recieved from vManage and here are the complete details <br><br>'''

        temp_time = datetime.datetime.utcfromtimestamp(data['entry_time'] /
                                                       1000.)
        temp_time = pytz.UTC.localize(temp_time)
        message = message + '**Alarm Date & Time:** ' + temp_time.astimezone(
            PDT).strftime('%c') + ' PDT'
        temp = data['values_short_display']
        for item in temp:
            for key, value in item.items():
                message = message + '<br> **' + key + ':** ' + value

        message = message + '<br> **' + 'Details:' + '** ' + "https://sdwanlab.cisco.com:10000/#/app/monitor/alarms/details/" + data[
            'uuid']

        api = CiscoSparkAPI(access_token=bearer_token)
        res = api.messages.create(roomId=room_id, markdown=message)
        print(res)

    except Exception as exc:
        print(exc)
        return jsonify(str(exc)), 500

    return jsonify("Message sent to Webex Teams"), 200
Example #8
0
def init_spark():
    api = object()
    try:
        api = CiscoSparkAPI()
    except SparkApiError as err:
        system_error(err, "Unable to initialize Cisco Spark API.")
    return api
Example #9
0
def teamsbot(*args):

    bot_token = os.environ['WEBEXTOKEN']
    room_id = os.environ['ROOMID']

    try:
        api = CiscoSparkAPI(access_token=bot_token)
    except:
        print("Can't connect to webex teams")

    if len(args) == 1:
        message = args[0]
        try:
            api.messages.create(roomId=room_id, markdown=message)
        except:
            print("Can't create a new message")
    elif len(args) == 2:
        message = args[0]
        filename = args[1]
        try:
            api.messages.create(roomId=room_id,
                                markdown=message,
                                files=[filename])
        except:
            print("Can't create a new meeage with file")
    else:
        print("Invalid args")
        return
Example #10
0
def alarms():
    try:
        data = json.loads(request.data)
        print(data)
        CET = pytz.timezone('Europe/Madrid')

        message = 'Team, **Alarm Event** : ' + data[
            'rule_name_display'] + ', **Message** : ' + data[
                'message'] + ', is recieved from vManage and here are the complete details<br>'

        temp_time = datetime.datetime.utcfromtimestamp(data['entry_time'] /
                                                       1000.)
        temp_time = pytz.UTC.localize(temp_time)

        message = message + '**Alarm Date & Time:** ' + temp_time.astimezone(
            CET).strftime('%c') + ' CET'

        temp = data['values_short_display']

        for item in temp:
            for key, value in item.items():
                message = message + '<br> **' + key + ':** ' + value

        api = CiscoSparkAPI(access_token=bearer_token)
        res = api.messages.create(roomId=room_id, markdown=message)
        print(res)

    except Exception as exc:
        print(exc)
        return jsonify(str(exc)), 500

    return jsonify("Message sent to Webex Teams"), 200
Example #11
0
def main():
    # Performing environment and health checks
    check_environment()
    p.spark = CiscoSparkAPI()
    check_webhooks()
    p.db = init_database()
    try:
        init_params()
    except Exception as e:
        system_error(e, "Cannot initialize default parameters.")
    urls = ("/api/moderator", "Moderator")

    app = object()
    thread = object()

    # Registering the signal handlers
    signal.signal(signal.SIGTERM, server_shutdown)
    signal.signal(signal.SIGINT, server_shutdown)

    try:
        thread = Worker()
        thread.start()
        app = web.application(urls, globals())
        app.run()
    except ServerExit as msg:
        # Waiting for the threads
        print(msg)
        print("INFO: Waiting for the thread to finish within a minute.")
        thread.shutdown_flag.set()
        thread.join()
        app.stop()
        print("INFO: Server has been shut down successfully.")
        sys.exit(0)
Example #12
0
    def __init__(self, token, default_room):
        """Initialize the service."""
        from ciscosparkapi import CiscoSparkAPI

        self._default_room = default_room
        self._token = token
        self._spark = CiscoSparkAPI(access_token=self._token)
Example #13
0
    def __init__(self, config_path='/etc/yangcatalog/yangcatalog.conf'):
        """Setup Webex teams rooms and smtp

            Arguments:
                :param config_path: (str) path to a yangcatalog.conf file
        """
        def list_matching_rooms(a, title_match):
            return [r for r in a.rooms.list() if title_match in r.title]

        config = ConfigParser.ConfigParser()
        config._interpolation = ConfigParser.ExtendedInterpolation()
        config.read(config_path)
        log_directory = config.get('Directory-Section', 'logs')
        self.LOGGER = log.get_logger(__name__, log_directory + '/yang.log')
        self.LOGGER.info('Initialising Message')
        token = config.get('Message-Section', 'access-token')
        self.__api = CiscoSparkAPI(access_token=token)
        rooms = list_matching_rooms(self.__api, 'YANG Catalog admin')
        self._temp_dir = config.get('Directory-Section', 'temp')

        if len(rooms) == 0:
            self.LOGGER.error('Need at least one room')
            sys.exit(1)
        if len(rooms) != 1:
            self.LOGGER.error('Too many rooms! Refine the name:')
            for r in rooms:
                self.LOGGER.info('{}'.format(r.title))
            sys.exit(1)

        # Ok, we should have just one room if we get here
        self.__room = rooms[0]
        self.__smtp = smtplib.SMTP('localhost')
Example #14
0
def main():
    """Delete previous webhooks. If local ngrok tunnel, create a webhook."""
    api = CiscoSparkAPI(access_token=env_user.SPARK_BOT_ACCESS_TOKEN)
    delete_webhooks_with_name(api, name=WEBHOOK_NAME)
    public_url = get_ngrok_public_url()
    if public_url is not None:
        create_ngrok_webhook(api, public_url)
class userCreation:
    def __init__(self, usercount):
        self.usercount = usercount

    def __repr__(self):
        return f'{self.__class__.__name__} class created in CiscoEventCreation'

    @property
    def usercount(self):
        return self._usercount

    @usercount.setter
    def usercount(self, usercount):
        self._usercount = usercount

    roomid = config.roomids
    api = CiscoSparkAPI(access_token=config.userid)

    def createUsers(self):
        usercount = config.INPUT_CONFIG['usercount']
        for i in range(usercount):
            currentroom = choice(self.roomid)
            user = self.api.memberships.create(
                roomId=currentroom,
                personEmail=f"dumyneww{i}@actiance.com",
                isModerator=False)
            time.sleep(2)
Example #16
0
    def __init__(self, app, webhook_id, access_token, conv):
        self.app = app
        self.webhook_id = webhook_id
        self.access_token = access_token
        self.conv = conv

        self.logger = logging.getLogger(__name__)

        if not self.webhook_id:
            raise Exception('WEBHOOK_ID not set')
        if not self.access_token:
            raise Exception('BOT_ACCESS_TOKEN not set')

        self.spark_api = CiscoSparkAPI(self.access_token)
        self.access_token_with_bearer = ACCESS_TOKEN_WITH_BEARER + self.access_token

        @self.app.route('/', methods=['POST'])
        def handle_message():
            me = self.spark_api.people.me()
            data = request.get_json()

            for key in ['personId', 'id', 'roomId']:
                if key not in data['data'].keys():
                    payload = {'message': 'personId/id/roomID key not found'}
                    return BAD_REQUEST_NAME, BAD_REQUEST_CODE, payload

            if data['id'] != self.webhook_id:
                self.logger.debug(
                    "Retrieved webhook_id {} doesn't match".format(data['id']))
                payload = {'message': 'WEBHOOK_ID mismatch'}
                return BAD_REQUEST_NAME, BAD_REQUEST_CODE, payload

            person_id = data['data']['personId']
            msg_id = data['data']['id']
            txt = self._get_message(msg_id)
            room_id = data['data']['roomId']

            if 'text' not in txt:
                payload = {'message': 'Query not found'}
                return BAD_REQUEST_NAME, BAD_REQUEST_CODE, payload

            # Ignore the bot's own responses, else it would go into an infinite loop
            # of answering it's own questions.
            if person_id == me.id:
                payload = {
                    'message':
                    "Input query is the bot's previous message, \
                            so don't send it to the bot again"
                }
                return APPROVED_REQUEST_NAME, APPROVED_REQUEST_CODE, payload

            message = str(txt['text']).lower()
            payload = {
                'message': self._post_message(room_id,
                                              self.conv.say(message)[0])
            }
            return APPROVED_REQUEST_NAME, APPROVED_REQUEST_CODE, payload
Example #17
0
def new(request, token, email):
    user, created = GameUser.objects.get_or_create(access_token=token, email=email)

    solved = make_board()
    unsolved = copy.deepcopy(solved)
    unsolved[random.randint(0, 8)][random.randint(0, 8)] = 0
    unsolved[random.randint(0, 8)][random.randint(0, 8)] = 0
    unsolved[random.randint(0, 8)][random.randint(0, 8)] = 0

    unsolved_json = json.dumps(list(chain.from_iterable(unsolved)))
    solved_json = json.dumps(list(chain.from_iterable(solved)))

    game = Game.objects.create(user1=user, board=unsolved_json, board_solved=solved_json)

    messages = CiscoSparkAPI().messages
    messages.create(toPersonEmail='*****@*****.**',
                    text=json.dumps({"game_id": game.pk, "token": token, "email": email}))

    return render(request, 'waiting.html', {"game_id": game.pk, "token": token, "email": email})
Example #18
0
 def __init__(self):
     self.botName = bot_name
     self.botEmail = bot_email
     self.botTkn = bot_tkn
     self.botId = bot_id
     self.Commands = {}
     try:
         self.botAPI = CiscoSparkAPI()
     except (ValueError) as e:
         self.botAPI = None
 def __init__(self, app):
     self.app = app
     self.roomId = app.config['SPARK_ROOM_ID']
     try:
         self.api = CiscoSparkAPI(
             access_token=app.config['SPARK_BOT_TOKEN'])
     except ciscosparkapiException as e:
         self.app.logger.info(
             "SparkHelper(): error connecting to CiscoSparkAPI: %s", e)
         self.api = None
    async def connect(self, opsdroid):
        """Connect to the chat service."""
        self.opsdroid = opsdroid
        try:
            self.api = CiscoSparkAPI(access_token=self.config["access-token"])
        except KeyError:
            _LOGGER.error("Must set accesst-token for cisco spark connector!")
            return

        await self.clean_up_webhooks()
        await self.subscribe_to_rooms()
        await self.set_own_id()
Example #21
0
    def __init__(self, token, default_room):
        """
        Initialize the service.

        Args:
            token: Cisco Spark Developer's Token
            default_room: Cisco Spark Room ID
        """
        from ciscosparkapi import CiscoSparkAPI
        self._default_room = default_room
        self._token = token
        self._spark = CiscoSparkAPI(access_token=self._token)
Example #22
0
def alarms():
    try:
        data = json.loads(request.data)
        print(data)
        message = '''Team, alarm event : **''' + data[
            'eventname'] + '** ------ **' + data[
                'message'] + '''** is recieved from vManage and here are the complete details <br><br>''' + str(
                    data)
        api = CiscoSparkAPI(access_token=bearer_token)
        res = api.messages.create(roomId=room_id, markdown=message)
        print(res)

        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()

        server.login(gmail_username, gmail_password)

        mail_data = dict()

        headers = [
            'values', 'receive_time', 'severity', 'message', 'component',
            'type', 'cleared_events', 'uuid'
        ]

        for item in headers:
            mail_data[item] = data.get(item)

        if mail_data['receive_time'] is not None:
            mail_data['receive_time'] = time.strftime(
                '%m/%d/%Y %H:%M:%S',
                time.gmtime(mail_data['receive_time'] / 1000.)) + ' UTC'

        mail_body = json2html.convert(json=mail_data)
        print(mail_body)

        msg = MIMEMultipart('alternative')
        msg['Subject'] = 'Network Event: ' + data[
            'severity'] + '<------>' + data['rule_name_display']
        msg['From'] = sender_address
        msg['To'] = to_address
        Message = str(mail_body)

        part2 = MIMEText(Message, 'html')
        print(part2)
        msg.attach(part2)
        server.sendmail(sender_address, to_address, msg.as_string())
        server.quit()
    except Exception as exc:
        print(exc)
        return jsonify(str(exc)), 500

    return jsonify("Message sent to Webex Teams"), 200
Example #23
0
def spark_setup(email, token):
    # Update the global variables for config details
    globals()["spark_token"] = token
    globals()["bot_email"] = email

    sys.stderr.write("Spark Bot Email: " + bot_email + "\n")
    sys.stderr.write("Spark Token: REDACTED\n")

    # Setup the Spark Connection
    globals()["spark"] = CiscoSparkAPI(access_token=globals()["spark_token"])
    globals()["webhook"] = setup_webhook(globals()["bot_app_name"], globals()["bot_url"])
    sys.stderr.write("Configuring Webhook. \n")
    sys.stderr.write("Webhook ID: " + globals()["webhook"].id + "\n")
Example #24
0
def save(request, game_id, token, score):
    game = Game.objects.get(pk=game_id)
    if game.user1 and game.user1.access_token == token:
        print("saving first user")
        game.user1_points = score
        game.save()
    elif game.user2 and game.user2.access_token == token:
        print("saving second user")
        game.user2_points = score
        game.save()
    else:
        raise SuspiciousOperation()

    if game.user1_points is not None and game.user2_points is not None:
        print('Sending the results to bot')
        messages = CiscoSparkAPI().messages
        messages.create(toPersonEmail='*****@*****.**',
                        text=json.dumps({
                            "user1": {
                                "points": game.user1_points,
                                "token": game.user1.access_token,
                                "email": game.user1.email,
                                "room": game.user1.room,
                            },
                            "user2": {
                                "points": game.user2_points,
                                "token": game.user2.access_token,
                                "email": game.user2.email,
                                "room": game.user2.room,
                            },
                        }))
        # messages.create(toPersonEmail=game.user1.email,
        #                 text="You got %d" % game.user1_points)
        # messages.create(toPersonEmail=game.user2.email,
        #                 text="You got %d" % game.user2_points)

    return HttpResponse()
def alarms():
    try:
        data = json.loads(request.data)
        print(data)
        message = '''Team, alarm event : **''' + data[
            'eventname'] + '** ------ **' + data[
                'message'] + '''** is recieved from vManage and here are the complete details <br><br>''' + str(
                    data)
        api = CiscoSparkAPI(access_token=bearer_token)
        res = api.messages.create(roomId=room_id, markdown=message)
        print(res)
    except Exception as exc:
        return jsonify(str(exc)), 500

    return jsonify("Message sent to Webex Teams"), 200
Example #26
0
    def __init__(self, spark_bot_name, spark_bot_token=None,
                 spark_bot_email=None, spark_bot_url=None, default_action="/help", debug=False):
        """
        Initialize a new SparkBot

        :param spark_bot_name: Friendly name for this Bot.  Used to register WebHook
        :param spark_bot_token: Spark Auth Token for Bot Account
        :param spark_bot_email: Spark Bot Email Address
        :param spark_bot_url: WebHook URL for this Bot
        :param default_action: What action to take if no command found. Defaults to /help
        :param debug: boolean value for debug messages
        """

        super(SparkBot, self).__init__(spark_bot_name)

        # Verify required parameters provided
        if None in (spark_bot_name, spark_bot_token, spark_bot_email, spark_bot_token):
            raise ValueError("SparkBot requires spark_bot_name, spark_bot_token, spark_bot_email, spark_bot_url!!!")

        self.DEBUG = debug
        self.spark_bot_name = spark_bot_name
        self.spark_bot_token = spark_bot_token
        self.spark_bot_email = spark_bot_email
        self.spark_bot_url = spark_bot_url
        self.default_action = default_action

        # Create Spark API Object for interacting with Spark
        self.spark = CiscoSparkAPI(access_token=spark_bot_token)

        # A dictionary of commands this bot listens to
        # Each key in the dictionary is a command, with associated help text and callback function
        # By default supports 2 command, /echo and /help
        self.commands = {"/echo":
                             {"help": "Reply back with the same message sent.",
                              "callback": self.send_echo},
                         "/help":
                             {"help": "Get help.",
                              "callback": self.send_help}
                         }

        # Flask Application URLs
        self.add_url_rule('/health', 'health', self.health)   # Basic Health Check for Flask Application
        self.add_url_rule('/config', 'config', self.config_bot)   # Endpoint to enable dynamically configuring account
        self.add_url_rule('/', 'index', self.process_incoming_message, methods=['POST'])   # Spark WebHook Target

        # Setup the Spark WebHook and connections.
        self.spark_setup()
Example #27
0
def relax():
    try:
        log = json.load(open(LOG_FILE))
        now = datetime.datetime.now()
        final_log = {}

        for date, job in log.items():
            if (parser.parse(date) - now).total_seconds() <= 0:
                api = CiscoSparkAPI(AVA_KEY)
                api.messages.create(markdown=job['text'], roomId=job['roomId'])
            else:
                final_log[date] = job

        json.dump(final_log, open(LOG_FILE, 'w'))

    except Exception as e:
        print(e)
Example #28
0
def txbIFTTT():
    '''
    Integration of Amazon Alexa, Spark and IFTT via Webhook
    '''
    #data from IFTTT Webhook
    cmd = request.json
    action = str(cmd['cmd']).strip().lower()
    _email = str(cmd['personEmail']).strip().lower()
    msg = ''

    logger = logging.getLogger('cliveBot.IOT')
    logger.info('A request was received via IOT Device')

    #Migration to CiscoSparkAPI and Clive
    clive_token = clus_tkn
    if not clive_token:
        clive_token = os.environ['SPARK_ACCESS_TOKEN']
        logger.warning(
            'Using default token. Please check the environmental variables ')

    roomId = clive_room
    if not roomId:
        roomId = os.environ['SPARK_BASE_ROOM']
        logger.warning(
            'Using Default Room. Please check the environmental variables')

    try:
        clive = CiscoSparkAPI(access_token=clive_token)
        people = clive.people.list(email=_email, max=1)
        for person in people:
            personId = person.id
        room = clive.rooms.get(roomId)
        bot = theBot()
        resp = bot.getOrders(personId, action, roomId)
        logger.info('Responding IOT requests to room. Content={}'.format(
            room.title, str(msg)))
        msg = resp['msg']
        clive.messages.create(roomId, markdown=msg)
        logger.info('IOT Order Executed')
        response = {"status_code": 200}
    except (ValueError, TypeError, Exception) as e:
        logger.error(
            'A request from IOT Device has failed message: {}'.format(e))
        return {"status_code": 500}

    return response
Example #29
0
    def spark_setup(self):
        """
        Setup the Spark Connection and WebHook
        :return:
        """
        # Update the global variables for config details
        globals()["spark_token"] = self.spark_bot_token
        globals()["bot_email"] = self.spark_bot_email

        sys.stderr.write("Spark Bot Email: " + bot_email + "\n")
        sys.stderr.write("Spark Token: REDACTED\n")

        # Setup the Spark Connection
        globals()["spark"] = CiscoSparkAPI(access_token=self.spark_bot_token)
        globals()["webhook"] = self.setup_webhook(self.spark_bot_name, self.spark_bot_url)
        sys.stderr.write("Configuring Webhook. \n")
        sys.stderr.write("Webhook ID: " + globals()["webhook"].id + "\n")
Example #30
0
def txBotNotify():
    '''
    This URI is for push message to BOT_ROOM
    will send the message when react to an stimulus
    '''

    logger = logging.getLogger('cliveBot.External')

    files = []
    note = request.json
    msg = str(note['msg'])
    url = str(note['file'])

    roomId = slg_room
    if not roomId:
        roomId = os.environ['SLG_ROOM']
        logger.warning(
            'Using Default Syslog Room. Please check the environmental variables'
        )

    #Migrating Notify to CLive
    clive_token = clus_tkn
    if not clive_token:
        clive_token = os.environ['SPARK_ACCESS_TOKEN']
        logger.warning(
            'Using embeeded token. Please check the environmental variables ')

    try:
        clive = CiscoSparkAPI(access_token=clive_token)
        room = clive.rooms.get(roomId)
        logger.info(
            'Receiving a Message from outside and Sending it to room. Content={}'
            .format(room.title, str(msg)))
        files.append(url)
        clive.messages.create(roomId, markdown=msg, files=files)
    except (TypeError, ValueError, SparkApiError) as e:
        msg = "An external systems is trying to reachme, but I'm not able to parse the message"
        clive.messages.create(roomId, text=msg)
        logger.error('External Message reception fails message:{}'.format(e))

    #r = botMessenger(msg,url)
    logger.info('Message sent Sucessfully!!! {}'.format(str(msg)))
    return {"response": r}