Exemple #1
0
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("--auth",
                        choices=["rsa", "cert"],
                        default="rsa",
                        help="Authentication method to use")
    parser.add_argument("--config", help="Config json file to be used")

    args = parser.parse_args()

    # Configure log
    configure_logging()

    # Cert Auth flow: pass path to certificate config.json file
    if args.config is None:
        config_path = os.path.join(os.path.dirname(__file__), "..",
                                   "resources", "config.json")
    else:
        config_path = args.config

    configure = SymConfig(config_path, config_path)
    configure.load_config()

    if args.auth == "rsa":
        auth = SymBotRSAAuth(configure)
    elif args.auth == "cert":
        auth = Auth(configure)
    else:
        raise ValueError("Unexpected value for auth: " + args.auth)

    auth.authenticate()

    # Initialize SymBotClient with auth and configure objects
    bot_client = SymBotClient(auth, configure)

    # Initialize datafeed service
    datafeed_event_service = bot_client.get_async_datafeed_event_service()

    # Initialize listener objects and append them to datafeed_event_service
    # Datafeed_event_service polls the datafeed and the event listeners
    # respond to the respective types of events
    im_listener_test = AsyncIMListenerImp(bot_client)
    datafeed_event_service.add_im_listener(im_listener_test)
    room_listener_test = AsyncRoomListenerImp(bot_client)
    datafeed_event_service.add_room_listener(room_listener_test)

    # This is just a function to demonstrate the non-blocking nature of the async datafeed
    async def timed_ringer(period_in_seconds, message):
        while True:
            await asyncio.sleep(period_in_seconds)
            print(message)

    # Create and read the datafeed
    print('Starting datafeed')
    loop = asyncio.get_event_loop()
    awaitables = asyncio.gather(timed_ringer(2, "Ding"),
                                timed_ringer(5, "Dong"),
                                datafeed_event_service.start_datafeed())
    loop.run_until_complete(awaitables)
def main():
    print('Python Client runs using Cert authentication')

    # Configure log
    configure_logging()

    # Cert Auth flow: pass path to certificate config.json file
    configure = SymConfig('../resources/config.json')
    configure.load_config()
    auth = Auth(configure)
    auth.authenticate()

    # Initialize SymBotClient with auth and configure objects
    bot_client = SymBotClient(auth, configure)

    # Initialize datafeed service
    datafeed_event_service = bot_client.get_datafeed_event_service()

    # Initialize listener objects and append them to datafeed_event_service
    # Datafeed_event_service polls the datafeed and the event listeners
    # respond to the respective types of events
    im_listener_test = IMListenerTestImp(bot_client)
    datafeed_event_service.add_im_listener(im_listener_test)
    room_listener_test = RoomListenerTestImp(bot_client)
    datafeed_event_service.add_room_listener(room_listener_test)

    # Create and read the datafeed
    print('Starting datafeed')
    datafeed_event_service.start_datafeed()
    def setUp(self):
        configure = SymConfig(
            get_path_relative_to_resources_folder('./bot-config.json'))
        configure.load_config()
        configure.data['datafeedVersion'] = 'v2'

        bot_client = SymBotClient(SymBotRSAAuth(configure), configure)

        self.datafeed_client = bot_client.get_datafeed_client()
    def setUp(self):
        try:
            conf, auth = load_from_env_var("SYMPHONY_TEST_CONFIG")
            self.configure = conf
            self.auth = auth
        except ValueError:
            #RSA Auth flow:
            self.configure = SymConfig(
                'sym_api_client_python/resources/config.json')
            self.configure.load_config()
            auth = SymBotRSAAuth(self.configure)
            auth.authenticate()

        # Initialize SymBotClient with auth and configure objects
        self.bot_client = SymBotClient(auth, self.configure)
    def setUp(self):
        try:
            conf, auth = load_from_env_var("SYMPHONY_TEST_CONFIG")
            self.configure = conf
            self.auth = auth
        except ValueError:
            #RSA Auth flow:
            self.configure = SymConfig('sym_api_client_python/resources/config.json')
            self.configure.load_config()
            auth = SymBotRSAAuth(self.configure)
            auth.authenticate()

        # Initialize SymBotClient with auth and configure objects
        self.bot_client = SymBotClient(self.auth, self.configure)
        self.streamId = 'qfC1jCKzQ0ELq96TMs58dX___o_kveOkdA'
        self.user_id = '349026222344902'
Exemple #6
0
def main():
    global loopCount

    parser = argparse.ArgumentParser()
    parser.add_argument("--auth",
                        choices=["rsa", "cert"],
                        default="rsa",
                        help="Authentication method to use")
    parser.add_argument("--config", help="Config json file to be used")

    args = parser.parse_args()

    # Configure log
    configure_logging()

    configure = SymConfig(_configPath, _configPath)
    configure.load_config()

    if args.auth == "rsa":
        auth = SymBotRSAAuth(configure)
    elif args.auth == "cert":
        auth = Auth(configure)
    else:
        raise ValueError("Unexpected value for auth: " + args.auth)

    auth.authenticate()

    # Initialize SymBotClient with auth and configure objects
    bot_client = SymBotClient(auth, configure)

    # Initialize datafeed service
    datafeed_event_service = bot_client.get_async_datafeed_event_service()

    # Initialize listener objects and append them to datafeed_event_service
    # Datafeed_event_service polls the datafeed and the event listeners
    # respond to the respective types of events
    im_listener_test = AsyncIMListenerImp(bot_client)
    datafeed_event_service.add_im_listener(im_listener_test)
    room_listener_test = AsyncRoomListenerImp(bot_client)
    datafeed_event_service.add_room_listener(room_listener_test)

    # Create and read the datafeed
    logging.debug('Starting datafeed')
    logging.info('Datafeed started - bot is ready')
    loop = asyncio.get_event_loop()
    awaitables = asyncio.gather(datafeed_event_service.start_datafeed())
    loop.run_until_complete(awaitables)
Exemple #7
0
    def setUp(self):
        try:
            conf, auth = load_from_env_var("SYMPHONY_TEST_CONFIG")
            self.configure = conf
            self.auth = auth
        except ValueError:
            #RSA Auth flow:
            self.configure = SymConfig('sym_api_client_python/resources/config.json')
            self.configure.load_config()
            auth = SymBotRSAAuth(self.configure)
            auth.authenticate()

        #initialize SymBotClient with auth and configure objects
        self.bot_client = SymBotClient(self.auth, self.configure)
        self.streamId = 'ychiFHXta__zF7YqoLOnN3___pBQNr6mdA'
        self.messageId = 'g05bspw5c5E7Aq2SMZjIJX___o_KIUG2bQ'
        self.test_message = dict(message = '<messageML><hash tag="reed"/></messageML>')
        self.params = {"text" : "hi", "streamId" : "ychiFHXta__zF7YqoLOnN3___pBQNr6mdA"}
Exemple #8
0
def main():
    print('Python Client runs using RSA authentication')

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="Config json file to be used")

    args = parser.parse_args()

    # Configure log
    configure_logging()

    # Cert Auth flow: pass path to certificate config.json file
    if args.config is None:
        config_path = os.path.join(os.path.dirname(__file__), "..",
                                   "sym_api_client_python", "resources",
                                   "rsa_config.json")
    else:
        config_path = args.config

    # RSA Auth flow: pass path to rsa config.json file)
    configure = SymConfig(config_path, __file__)
    configure.load_config()
    #auth = SymBotRSAAuth(configure)
    auth = SymBotRSAAuth(configure)
    auth.authenticate()

    # Initialize SymBotClient with auth and configure objects
    bot_client = SymBotClient(auth, configure)

    # Initialize datafeed service
    datafeed_event_service = bot_client.get_datafeed_event_service()

    # Initialize listener objects and append them to datafeed_event_service
    # Datafeed_event_service polls the datafeed and the event listeners
    # respond to the respective types of events
    im_listener_test = IMListenerTestImp(bot_client)
    datafeed_event_service.add_im_listener(im_listener_test)
    room_listener_test = RoomListenerTestImp(bot_client)
    datafeed_event_service.add_room_listener(room_listener_test)

    # Create and read the datafeed
    print('Starting datafeed')
    datafeed_event_service.start_datafeed()
 def setUp(self):
     logging.debug('hi')
     #RSA Auth flow:
     configure = SymConfig(
         'sym_api_client_python/resources/rsa_config.json')
     configure.load_rsa_config()
     auth = SymBotRSAAuth(configure)
     auth.authenticate()
     #initialize SymBotClient with auth and configure objects
     self.botClient = SymBotClient(auth, configure)
Exemple #10
0
def main():
    print('Python Client runs using RSA authentication')

    # Configure log
    configure_logging()

    # RSA Auth flow: pass path to rsa config.json file
    configure = SymConfig('../resources/config.json')
    configure.load_config()
    auth = SymBotRSAAuth(configure)
    auth.authenticate()

    # Initialize SymBotClient with auth and configure objects
    bot_client = SymBotClient(auth, configure)
    df = DataFeedClient2(bot_client)
    bot_client.datafeed_client = df

    # Initialize datafeed service
    datafeed_event_service = bot_client.get_datafeed_event_service()

    # Initialize listener objects and append them to datafeed_event_service
    # Datafeed_event_service polls the datafeed and the event listeners
    # respond to the respective types of events
    null_response = mvc.NullResponse()

    controllers = mvc.Controllers()

    controllers.add(info.Controller(null_response, info.View()))
    cc = summary.Controller(null_response, summary.View())
    c = tweets.Controller(tweets.Response(bot_client, cc), tweets.View())
    controllers.add(c)
    controllers.add(
        create.Controller(create.Response(bot_client, c), create.View()))

    room_listener_test = GeneralRoomListener(bot_client, controllers)
    datafeed_event_service.add_room_listener(room_listener_test)
    elements_listener_test = GeneralElementsListener(bot_client, controllers)
    datafeed_event_service.add_elements_listener(elements_listener_test)

    # Create and read the datafeed
    print('Starting datafeed')
    datafeed_event_service.start_datafeed()
def main():
        configure_logging()
        configure = SymConfig('./config.json')
        configure.load_config()
        bot_env = load_env('./environment.json')
        auth = SymBotRSAAuth(configure)
        auth.authenticate()
        # Initialize SymBotClient with auth and configure objects
        bot_client = SymBotClient(auth, configure)
        bot_client.bot_id = bot_env['bot_id']
        # Initialize datafeed service
        datafeed_event_service = bot_client.get_datafeed_event_service()
        # Add Listeners to datafeed event service
        im_listener_test = IMListenerTestImp(bot_client)
        datafeed_event_service.add_im_listener(im_listener_test)
        element_listener_test = ElementsListenerTestImp(bot_client)
        datafeed_event_service.add_elements_listener(element_listener_test)
        # Create and read the datafeed
        print('Starting datafeed')
        datafeed_event_service.start_datafeed()
Exemple #12
0
 def __init__(self,
              bot=None,
              *,
              threads=None,
              debug=False,
              symphony_config="symphony.json",
              symphony_log="symphony.log",
              **kwargs):
     """
     Parameters
     ----------
     bot : minette.Minette, default None
         Instance of Minette.
         If None, create new instance of Minette by using `**kwargs`
     symphony_config : str, default 'symphony.json'
         Config file for Symphony SDK
     symphony_log : str, defautl 'symphony.log'
         Log file of Symphony SDK
     threads : int, default None
         Max number of worker threads. If None, number of processors on the machine, multiplied by 5
     debug : bool, default False
         Debug mode
     """
     super().__init__(bot=bot, threads=threads, debug=debug, **kwargs)
     # setup root logger (used internally in symphony libraries)
     logging.basicConfig(
         filename=symphony_log,
         format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
         filemode="w",
         level=logging.DEBUG)
     # set logging level for urllib3 used in symphony libraries
     logging.getLogger("urllib3").setLevel(logging.WARNING)
     # configure and authenticate
     config = SymConfig(symphony_config)
     config.load_config()
     auth = SymBotRSAAuth(config)
     auth.authenticate()
     # initialize SymBotClient with auth and configure objects
     self.bot_client = SymBotClient(auth, config)
     self.datafeed_client = self.bot_client.get_datafeed_client()
class TestUsers(unittest.TestCase):
    def setUp(self):
        try:
            conf, auth = load_from_env_var("SYMPHONY_TEST_CONFIG")
            self.configure = conf
            self.auth = auth
        except ValueError:
            #RSA Auth flow:
            self.configure = SymConfig(
                'sym_api_client_python/resources/config.json')
            self.configure.load_config()
            auth = SymBotRSAAuth(self.configure)
            auth.authenticate()

        # Initialize SymBotClient with auth and configure objects
        self.bot_client = SymBotClient(auth, self.configure)

    #pass
    def test_getUserFromUsername(self):
        print('testing get_user_from_user_name function')
        username = self.configure.data["botUsername"]
        self.assertTrue(
            self.bot_client.get_user_client().get_user_from_user_name(
                username))

    #pass
    def test_getUserFromEmail(self):
        print('testing get_user_from_email function')
        email = self.configure.data["botEmailAddress"]
        self.assertTrue(
            self.bot_client.get_user_client().get_user_from_email(email))

    #pass
    def test_getUserFromId(self):
        print('testing get_user_from_id function')
        self.assertTrue(self.bot_client.get_user_client().get_user_from_id(
            '344147139494909'))

    #pass
    def test_getUsersFromIdList(self):
        print('testing get_users_from_id_list function')
        self.assertTrue(
            self.bot_client.get_user_client().get_users_from_id_list(
                ['344147139494862', '344147139494909']))

    #pass
    def test_getUsersFromEmailList(self):
        print('testing get_users_from_email_list function')
        self.assertTrue(
            self.bot_client.get_user_client().get_users_from_email_list(
                ['*****@*****.**', '*****@*****.**']))

    #pass
    def test_searchUsers(self):
        print('testing search users function')
        username = self.configure.data["botUsername"]
        # Make a search string by taking the first half of the username
        search_string = username[:int(len(username) / 2)]
        self.assertTrue(
            self.bot_client.get_user_client().search_users(search_string))
def main():
        global loopCount

        # Configure log
        configure_logging()

        # Cert Auth flow: pass path to certificate config.json file
        config_path = os.path.join(os.path.dirname(__file__), "../resources", "config.json")
        
        configure = SymConfig(config_path, config_path)
        configure.load_config()

        auth = SymBotRSAAuth(configure)
        auth.authenticate()

        # Initialize SymBotClient with auth and configure objects
        bot_client = SymBotClient(auth, configure)

        # add rss instance to bot
        mr = reader.RssReader('../resources/state.json')
        bot_client.reader = mr

        # Initialize datafeed service
        datafeed_event_service = bot_client.get_async_datafeed_event_service()

        # Initialize listener objects and append them to datafeed_event_service
        # Datafeed_event_service polls the datafeed and the event listeners
        # respond to the respective types of events
        im_listener = AsyncIMListenerImp(bot_client)
        datafeed_event_service.add_im_listener(im_listener)

        room_listener = AsyncRoomListenerImp(bot_client)
        datafeed_event_service.add_room_listener(room_listener)

        # Create and read the datafeed
        logging.info('Datafeed started - bot is ready')
        loop = asyncio.get_event_loop()
        awaitables = asyncio.gather(datafeed_event_service.start_datafeed())
        loop.run_until_complete(awaitables)
Exemple #15
0
def main():
        # Configure log
        configure_logging()

        # Load configuration
        configure = SymConfig('../resources/config.json')
        configure.load_config()

        # Authenticate based on authType in config
        if ('authType' not in configure.data or configure.data['authType'] == 'rsa'):
            print('Python Client runs using RSA authentication')
            auth = SymBotRSAAuth(configure)
        else:
            print('Python Client runs using certificate authentication')
            auth = Auth(configure)
        auth.authenticate()

        # Initialize SymBotClient with auth and configure objects
        bot_client = SymBotClient(auth, configure)

        # Initialize datafeed service
        datafeed_event_service = bot_client.get_async_datafeed_event_service()

        # Initialize listener objects and append them to datafeed_event_service
        # Datafeed_event_service polls the datafeed and the event listeners
        # respond to the respective types of events
        datafeed_event_service.add_im_listener(IMListenerImpl(bot_client))
        datafeed_event_service.add_room_listener(RoomListenerImpl(bot_client))
        datafeed_event_service.add_elements_listener(ElementsListenerImpl(bot_client))

        # Create and read the datafeed
        print('Starting datafeed')
        try:
            loop = asyncio.get_event_loop()
            loop.run_until_complete(datafeed_event_service.start_datafeed())
        except (KeyboardInterrupt, SystemExit):
            None
        except:
            raise
    def setUpClass(cls):
        logging.debug('testing health_check file:')
        try:
            conf, auth = load_from_env_var("SYMPHONY_TEST_CONFIG")
            cls.configure = conf
            cls.auth = auth
        except ValueError:
            #RSA Auth flow:
            cls.configure = SymConfig(
                'sym_api_client_python/resources/config.json')
            cls.configure.load_config()
            cls.auth = SymBotRSAAuth(cls.configure)
            cls.auth.authenticate()

        # Initialize SymBotClient with auth and configure objects
        cls.bot_client = SymBotClient(cls.auth, cls.configure)
    def setUpClass(cls):
        logging.debug('testing synchronous datafeed')
        try:
            conf, auth = load_from_env_var("SYMPHONY_TEST_CONFIG")
            cls.configure = conf
            cls.auth = auth
        except ValueError:
            logging.error("Unable to find config from environment variables")
            #RSA Auth flow:
            cls.configure = SymConfig(
                'sym_api_client_python/resources/config.json')
            cls.configure.load_config()
            cls.auth = SymBotRSAAuth(cls.configure)
            cls.auth.authenticate()

        # Initialize SymBotClient with auth and configure objects
        cls.bot_client = SymBotClient(cls.auth, cls.configure)
Exemple #18
0
def main():
    global loopCount

    # Configure log
    configure_logging()

    # Cert Auth flow: pass path to certificate config.json file

    config_path = os.path.join(os.path.dirname(__file__), "../resources",
                               "config.json")

    configure = SymConfig(config_path, config_path)
    configure.load_config()

    auth = SymBotRSAAuth(configure)
    auth.authenticate()

    # Initialize SymBotClient with auth and configure objects
    bot_client = SymBotClient(auth, configure)

    # add rss instance to bot

    #bot_client.reader = mr

    stream = 'JjRqq6OBIa7s5wkdNI1b8n___otjgHfIdA'

    count = 0
    while True:
        logging.debug('XXXX Loop stream ' + stream)
        count = count + 1
        display = "<card accent='tempo-bg-color--blue' iconSrc=''><body><h1>LOOP: " + str(
            count) + "</h1></body></card>"
        bot_client.get_message_client().send_msg(
            stream,
            dict(message="""<messageML>""" + display + """</messageML>"""))
        time.sleep(3)
        display = "<card accent='tempo-bg-color--blue' iconSrc=''><body>"
        mr = reader.RssReader('../resources/state.json')
        feeds = mr.checkrss()
        if len(feeds) == 0:
            display += "No Feeds"
        for topic in feeds:
            for feed in feeds[topic]:
                logging.debug('adding feeed to show')
                display += "<p><a href='" + feed['link'] + "'>" + feed[
                    'title'] + "</a></p>"
        display += "</body></card>"
        print(display)
        bot_client.get_message_client().send_msg(
            stream,
            dict(message="""<messageML>""" + display + """</messageML>"""))
def main():
        parser = argparse.ArgumentParser()
        parser.add_argument("--auth", choices=["rsa", "cert"], default="rsa",
            help="Authentication method to use")
        parser.add_argument("--config", help="Config json file to be used")
        args = parser.parse_args()
        # Cert Auth flow: pass path to certificate config.json file
        config_path = args.config
        configure = SymConfig(config_path, config_path)
        configure.load_config()
        if args.auth == "rsa":
            auth = SymBotRSAAuth(configure)
        elif args.auth == "cert":
            auth = Auth(configure)
        else:
            raise ValueError("Unexpected value for auth: " + args.auth)
        auth.authenticate()
        # Initialize SymBotClient with auth and configure objects
        bot_client = SymBotClient(auth, configure)
        print('successfully authenticated')
        run_import(bot_client)
        print('successfully imported')
Exemple #20
0
class SymphonyAdapter(Adapter):
    """
    Adapter for LINE Messaging API

    Attributes
    ----------
    bot : minette.Minette
        Instance of Minette
    bot_client : SymBotClient
        Symphony chatbot client
    datafeed_client : DataFeedClient
        Datafeed client using long polling
    config : minette.Config
        Configuration
    timezone : pytz.timezone
        Timezone
    logger : logging.Logger
        Logger
    threads : int
        Number of worker threads to process requests
    executor : ThreadPoolExecutor
        Thread pool of workers
    debug : bool
        Debug mode
    """
    def __init__(self,
                 bot=None,
                 *,
                 threads=None,
                 debug=False,
                 symphony_config="symphony.json",
                 symphony_log="symphony.log",
                 **kwargs):
        """
        Parameters
        ----------
        bot : minette.Minette, default None
            Instance of Minette.
            If None, create new instance of Minette by using `**kwargs`
        symphony_config : str, default 'symphony.json'
            Config file for Symphony SDK
        symphony_log : str, defautl 'symphony.log'
            Log file of Symphony SDK
        threads : int, default None
            Max number of worker threads. If None, number of processors on the machine, multiplied by 5
        debug : bool, default False
            Debug mode
        """
        super().__init__(bot=bot, threads=threads, debug=debug, **kwargs)
        # setup root logger (used internally in symphony libraries)
        logging.basicConfig(
            filename=symphony_log,
            format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
            filemode="w",
            level=logging.DEBUG)
        # set logging level for urllib3 used in symphony libraries
        logging.getLogger("urllib3").setLevel(logging.WARNING)
        # configure and authenticate
        config = SymConfig(symphony_config)
        config.load_config()
        auth = SymBotRSAAuth(config)
        auth.authenticate()
        # initialize SymBotClient with auth and configure objects
        self.bot_client = SymBotClient(auth, config)
        self.datafeed_client = self.bot_client.get_datafeed_client()

    def start_datafeed(self):
        """
        Start datafeed to read and process events from Symphony

        """
        # get datafeed id
        datafeed_id = self.datafeed_client.create_datafeed()
        self.logger.info("Datafeed client is ready")
        # datafeed loop forever
        while True:
            try:
                # read datafeed by datafeed_id (30 sec long polling)
                data = self.datafeed_client.read_datafeed(datafeed_id)
                if data:
                    # api returns list of events but SDK nest it to array.(I don't know why...)
                    events = data[0]
                    for event in events:
                        if event["initiator"]["user"][
                                "userId"] != self.bot_client.get_bot_user_info(
                                )["id"]:
                            if self.executor:
                                self.executor.submit(self.handle_event, event)
                            else:
                                self.handle_event(event)
            except Exception as ex:
                self.logger.error("Error occured in datafeed loop: " +
                                  str(ex) + "\n" + traceback.format_exc())

    def handle_event(self, event):
        """
        Handle event and reply message

        Parameters
        ----------
        event : Event
            Event data from Symphony
        """
        channel_messages, stream_id = super().handle_event(event)
        if channel_messages:
            for msg in channel_messages:
                self.logger.info("Minette> {}".format(
                    msg["message"] if "message" in msg else msg))
                self.bot_client.get_message_client().send_msg(stream_id, msg)

    def _extract_token(self, event):
        """
        Extract token from event

        Parameters
        ----------
        event : Event
            Event from LINE Messaging API

        Returns
        -------
        message : Message
            Request message object
        """
        return event["payload"]["messageSent"]["message"]["stream"]["streamId"]

    def _to_minette_message(self, event):
        """
        Convert Symphony Event object to Minette Message object

        Parameters
        ----------
        event : Event
            Event from Symphony. See the url below for information
            https://developers.symphony.com/restapi/docs/real-time-events

        Returns
        -------
        message : minette.Message
            Request message object
        """
        if self.debug:
            self.logger.info(event)
        msg = Message(type=event["type"],
                      channel="Symphony",
                      channel_detail="",
                      channel_user_id=str(
                          event["initiator"]["user"]["userId"]),
                      channel_message=event)
        if msg.type == "MESSAGESENT":
            m = event["payload"]["messageSent"]["message"]
            msg.token = m["stream"]["streamId"]
            msg.text = lxml.html.fromstring(m["message"]).text_content()
            if m["stream"]["streamType"] == "ROOM":
                msg.group = Group(id=m["stream"]["streamId"], type="ROOM")
            if "attachments" in m:
                for a in m["attachments"]:
                    if len(a["images"]) > 0:
                        content_type = "image"
                    else:
                        content_type = "file"
                    msg.payloads.append(
                        Payload(content_type=content_type, content=a))
        return msg

    @staticmethod
    def _to_channel_message(message):
        """
        Convert Minette Message object to Symphony message dict

        Parameters
        ----------
        message : Message
            Response message object

        Returns
        -------
        response : dict
            Message dict for Symphony
        """
        return {"message": "<messageML>{}</messageML>".format(message.text)}
 def setUp(self):
     self.config = SymConfig(
         get_path_relative_to_resources_folder('./bot-config.json'))
     self.config.load_config()
     self.client = SymBotClient(None, self.config)
     self.ran = False
class TestStreams(unittest.TestCase):

    # run before each test function
    def setUp(self):
        try:
            conf, auth = load_from_env_var("SYMPHONY_TEST_CONFIG")
            self.configure = conf
            self.auth = auth
        except ValueError:
            #RSA Auth flow:
            self.configure = SymConfig('sym_api_client_python/resources/config.json')
            self.configure.load_config()
            auth = SymBotRSAAuth(self.configure)
            auth.authenticate()

        # Initialize SymBotClient with auth and configure objects
        self.bot_client = SymBotClient(self.auth, self.configure)
        self.streamId = 'qfC1jCKzQ0ELq96TMs58dX___o_kveOkdA'
        self.user_id = '349026222344902'

    #always passes
    # def test_facts(self):
    #     self.assertEqual(1,1)
    #pass
    def test_createIM(self):
        print('testing CreateIm function')
        self.assertTrue(self.bot_client.get_stream_client().create_im([self.user_id]))

    #pass but will fail if you pass data thats already been used like name and description
    def test_createRoom(self):
        print('testing create_room function')
        self.assertTrue(self.bot_client.get_stream_client().create_room())

    #pass: make sure that bot or user that is making update_room call is owner of room
    def test_updateRoom(self):
        print('testing update_room function')

        self.assertTrue(self.bot_client.get_stream_client().update_room(self.room_id))

    #pass
    def test_roomInfo(self):
        print('testing roomInfo function')

        self.assertTrue(self.bot_client.get_stream_client().get_room_info(self.streamId))

    #pass
    def test_activateRoom(self):
        print('testing activate_room function')
        active = False

        self.assertTrue(self.bot_client.get_stream_client().activate_room(self.streamId))

    #pass
    def test_getRoomMembers(self):

        self.assertTrue(self.bot_client.get_stream_client().get_room_members(self.streamId))

    #pass
    def test_addMember(self):
        print('testing addmember function')

        userId = '344147139494862'
        self.assertTrue(self.bot_client.get_stream_client().add_member_to_room(self.streamId, self.user_id))

    #pass
    def test_shareRoom(self):
        print('testing share_room function')

        self.assertTrue(self.bot_client.get_stream_client().share_room(self.stream_id))

    #pass
    def test_removeMemberFromRoom(self):
        print('testing remove Member function')

        userId = '344147139494862'
        self.assertTrue(self.bot_client.get_stream_client().remove_member_from_room(self.stream_id, self.user_id))

    #pass
    def test_promoteUserToOwner(self):
        print('testing promote owner function')

        userId = '344147139494862'
        self.assertTrue(self.bot_client.get_stream_client().promote_user_to_owner(self.stream_id, self.user_id))

    #pass
    def test_demoteUserFromOwner(self):
        print('testing demote owner function')

        userId = '344147139494862'
        self.assertTrue(self.bot_client.get_stream_client().demote_user_from_owner(self.stream_id, self.user_id))

    #pass
    def test_searchRooms(self):
        print('testing roomSearch function')
        self.assertTrue(self.bot_client.get_stream_client().search_rooms())

    #pass
    def test_getUserStreams(self):
        print('testing listUserStreams fucntion')
        self.assertTrue(self.bot_client.get_stream_client().get_user_streams())

    #pass
    def test_getRoomInfo(self):
        print('testing streamInfo function')

        self.assertTrue(self.bot_client.get_stream_client().get_room_info(self.room_id))

    #pass
    def test_streamInfo(self):
        print('testing streamInfo V2 function')

        self.assertTrue(self.bot_client.get_stream_client().streamInfo(self.room_id))

    #pass
    def test_listStreamsEnterprise(self):
        print('testing list streams enterprise function')
        self.assertTrue(self.bot_client.get_stream_client().list_streams_enterprise())

    #DOESNOTPASS
    def test_listStreamsEnterpriseV2(self):
        print('testing list streamsV2 enterprise function')
        self.assertTrue(self.bot_client.get_stream_client().list_streams_enterprise_v2())

    #DOESNOTPASS --> 405: verify if endpoint is still live
    def test_getStreamMembers(self):
        print('testing getstreamMembers function')
        self.assertTrue(self.bot_client.get_stream_client().get_stream_members(self.streamId))
Exemple #23
0
class TestMessages(unittest.TestCase):

    def setUp(self):
        try:
            conf, auth = load_from_env_var("SYMPHONY_TEST_CONFIG")
            self.configure = conf
            self.auth = auth
        except ValueError:
            #RSA Auth flow:
            self.configure = SymConfig('sym_api_client_python/resources/config.json')
            self.configure.load_config()
            auth = SymBotRSAAuth(self.configure)
            auth.authenticate()

        #initialize SymBotClient with auth and configure objects
        self.bot_client = SymBotClient(self.auth, self.configure)
        self.streamId = 'ychiFHXta__zF7YqoLOnN3___pBQNr6mdA'
        self.messageId = 'g05bspw5c5E7Aq2SMZjIJX___o_KIUG2bQ'
        self.test_message = dict(message = '<messageML><hash tag="reed"/></messageML>')
        self.params = {"text" : "hi", "streamId" : "ychiFHXta__zF7YqoLOnN3___pBQNr6mdA"}

    def test_createMessage(self):
        print('testing create messages function')
        message = self.test_message
        self.assertTrue(self.bot_client.get_message_client().send_msg(self.streamId, message))

    def test_create_message_async(self):
        asyncio.get_event_loop().run_until_complete(
            self.bot_client.get_message_client().send_msg_async(self.streamId, self.test_message)
            )

    def test_getMessageFromStream(self):
        print('testing get_msg_from_stream function')
        self.assertTrue(self.bot_client.get_message_client().get_msg_from_stream(self.streamId, 0))

    def test_get_message_from_stream_async(self):
        asyncio.get_event_loop().run_until_complete(
            self.bot_client.get_message_client().get_msg_from_stream_async(self.streamId, 0)
            )

    def test_create_message_attachment(self):
        fp = __file__
        self.bot_client.get_message_client().send_msg_with_attachment(
            self.streamId, self.test_message["message"], "testfilename.txt", fp
            )

    def test_create_message_attachment_iostream(self):
        file_like_object = io.StringIO("This is a test")
        self.bot_client.get_message_client().send_msg_with_attachment(
            self.streamId, self.test_message["message"], "testfilename.txt", file_like_object
            )

    def test_create_message_attachment_async(self):
        file_like_object = io.StringIO("This is a test")
        asyncio.get_event_loop().run_until_complete(
            self.bot_client.get_message_client().send_msg_with_attachment_async(
                self.streamId, self.test_message["message"], "testfilename.txt", file_like_object
            )
        )
    def test_create_message_attachment_iostream_async(self):
        file_like_object = io.StringIO("This is a test")
        asyncio.get_event_loop().run_until_complete(
            self.bot_client.get_message_client().send_msg_with_attachment_async(
                self.streamId, self.test_message["message"], "testfilename.txt", file_like_object
            )
        )
    def test_getMessageAttachments(self):
        pass

    def test_importMessage(self):
        pass

    #this function returns a 200 but its empty
    def test_postMessageSearch(self):
        print('testing post Message search function')
        self.assertTrue(self.bot_client.get_message_client().post_msg_search(self.params))

    def test_getMessageSearch(self):
        print('testing getMessage Search function')
        self.assertTrue(self.bot_client.get_message_client().get_msg_search({'streamId' : self.streamId, 'text'}))

    def test_getMessageStatus(self):
        print('testing getMessage Status function')
        self.assertTrue(self.bot_client.get_message_client().get_msg_status(self.messageId))

    def test_getSupportedAttachmentTypes(self):
        print('testing getAttachmentType function')
        self.assertTrue(self.bot_client.get_message_client().get_supported_attachment_types())