Example #1
0
    def __handle_message_activity(self, activity):
        self.send_response(200)
        self.end_headers()
        credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
        connector = ConnectorClient(credentials, base_url=activity.service_url)
        #######################
        if sum_bot.state < 0:
            if 'no' in activity.text.lower():
                new_text = 'As you like...., Would you like to start over (yes/no) ?'
                reply = BotRequestHandler.__create_reply_activity(
                    activity, new_text)
            else:
                new_text = sum_bot.update_state_reply(activity.text)
                reply = BotRequestHandler.__create_reply_activity(
                    activity, new_text)
                reply.attachments = [self.create_adaptive_card_attachment()]
        else:
            new_text = sum_bot.update_state_reply(activity.text)
            reply = BotRequestHandler.__create_reply_activity(
                activity, new_text)

        #######################
        # reply = BotRequestHandler.__create_reply_activity(activity, 'You said: %s' % activity.text)
        connector.conversations.send_to_conversation(reply.conversation.id,
                                                     reply)
    def test_conversations_update_activity_invalid_conversation_id_fails(self):
        activity = Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            text="Updating activity...",
        )

        activity_update = Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            text="Activity updated.",
        )

        with pytest.raises(ErrorResponseException) as excinfo:
            connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
            response = connector.conversations.send_to_conversation(
                CONVERSATION_ID, activity)
            activity_id = response.id
            connector.conversations.update_activity("INVALID_ID", activity_id,
                                                    activity_update)

        assert excinfo.value.error.error.code == "ServiceError"
        assert "Invalid ConversationId" in str(
            excinfo.value.error.error.message)
Example #3
0
    def __send(self, text, conversation, mentions=None):
        logger.info(f"Sending message: {text}")
        entities = list()
        if mentions is None:
            mentions = list()
        for name in mentions:
            user_id = self._user_map.get(name)
            if not user_id:
                logger.info("User not found: %s" % name)
                continue
            mention = Mention(mentioned=ChannelAccount(id=user_id, name=name), text="<at>%s</at>" % name,
                              type="mention")
            entities.append(mention)

        credentials = MicrosoftAppCredentials(self._app_id, self._app_password)
        connector = ConnectorClient(credentials, base_url=self._service_url)

        reply = Activity(
            type=ActivityTypes.message,
            channel_id=self._current_channel,
            conversation=conversation,
            from_property=ChannelAccount(id=self._current_bot_id["id"], name=self._current_bot_id["name"]),
            entities=entities,
            text=text,
            service_url=self._service_url)

        response = connector.conversations.send_to_conversation(reply.conversation.id, reply)
        logger.info(response)
Example #4
0
 def send_rich_activity(self, activity, text, attachment):
     reply = self.create_reply_activity(activity, ActivityTypes.message,
                                        text, attachment)
     connector = ConnectorClient(self.credentials,
                                 base_url=reply.service_url)
     return connector.conversations.send_to_conversation(
         reply.conversation.id, reply)
Example #5
0
async def send_execsum(req: Request) -> Response:
    try:
        credentials = MicrosoftAppCredentials(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
        client = ConnectorClient(credentials, 'https://smba.trafficmanager.net/fr/')
        teams_client = TeamsConnectorClient(credentials, 'https://smba.trafficmanager.net/fr/')
        teams_channels = teams_client.teams.get_teams_channels('19:[email protected]')
        general_channel = next(channel for channel in teams_channels.conversations if channel.name is None)
        conversation_parameters = ConversationParameters(
            is_group=True,
            channel_data={"channel": {"id": general_channel.id}},
            activity=MessageFactory.attachment(
                CardFactory.adaptive_card({
                    "type": "AdaptiveCard",
                    "version": "1.0",
                    "body": [
                        {
                            "type": "TextBlock",
                            "text": "[email protected] sent an execsum",
                        },
                    ],
                    "actions": [
                        {
                            "type": "Action.OpenUrl",
                            "title": "View execsum",
                            "url": "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
                        }
                    ]
                })
            ),
        )
        client.conversations.create_conversation(conversation_parameters)
        return Response(status=HTTPStatus.OK)
    except Exception:
        traceback.print_exc()
Example #6
0
 async def send_typing_activity(self, activity):
     reply = await self.create_reply_activity(activity,
                                              ActivityTypes.typing)
     connector = ConnectorClient(self.credentials,
                                 base_url=reply.service_url)
     return connector.conversations.send_to_conversation(
         reply.conversation.id, reply)
    def __handle_message_activity(self, activity):
        self.send_response(200)
        self.end_headers()
        credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
        connector = ConnectorClient(credentials, base_url=activity.service_url)
        a = ''
        b = ''
        res = ''
        res = activity.text
        p1 = Person(activity.text)
        a = p1.getIntent()
        b = p1.getEntity()
        if (a == "review" or a == "rating"):
            r = Scrap(b, a)
            res = r.getAnswer()
        elif (a == "crew"):
            r = Scrap2(b, a)
            res = r.getAnswer()

        #res=a+" "+b

        #here databse comes into role where movie name matches with the reviews

        reply = BotRequestHandler.__create_reply_activity(
            activity, 'movie bot: %s' % res)
        print(activity.text)
        connector.conversations.send_to_conversation(reply.conversation.id,
                                                     reply)
    def test_conversations_update_activity(self):
        activity = Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            text="Updating activity...",
        )

        activity_update = Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            text="Activity updated.",
        )

        connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
        response = connector.conversations.send_to_conversation(
            CONVERSATION_ID, activity)
        activity_id = response.id
        response = connector.conversations.update_activity(
            CONVERSATION_ID, activity_id, activity_update)

        assert response is not None
        assert response.id == activity_id
Example #9
0
 def __handle_message_activity(self, activity):
     self.send_response(200)
     self.end_headers()
     credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
     connector = ConnectorClient(credentials, base_url=activity.service_url)
     # reply = BotRequestHandler.__create_reply_activity(activity, 'You said: %s' % activity.text)
     params['q'] = activity.text
     try:
         r = requests.get(
             'https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/f3059921-7e30-4730-a349-09e37e46cd6e',
             headers=headers,
             params=params)
         data = r.json()
         print(data)
         main_query = "None"
         subject = "None"
         sec_query = "None"
     except Exception as e:
         print("[Errno {0}] {1}".format(e.errno, e.strerror))
     for entity in data['entities']:
         t = entity['type']
         if t == 'Query::Main Query':
             main_query = entity['entity']
         elif t == 'Subject':
             subject = entity['entity']
         elif t == 'Query::Secondary Query':
             sec_query = entity['entity']
     # print(main_query)
     reply = BotRequestHandler.__create_reply_activity(
         activity, "The main query is: " + main_query +
         ", the subject is: " + subject)
     connector.conversations.send_to_conversation(reply.conversation.id,
                                                  reply)
Example #10
0
 def __handle_message_activity(self, activity):
     self.send_response(200)
     self.end_headers()
     credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
     connector = ConnectorClient(credentials, base_url=activity.service_url)
     reply = BotRequestHandler.__create_reply_activity(activity, 'You said: %s' % activity.text)
     connector.conversations.send_to_conversation(reply.conversation.id, reply)
    def test_conversations_reply_to_activity(self):
        activity = Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            text="Thread activity",
        )

        child_activity = Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            text="Child activity.",
        )

        connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
        response = connector.conversations.send_to_conversation(
            CONVERSATION_ID, activity)
        activity_id = response.id
        response = connector.conversations.reply_to_activity(
            CONVERSATION_ID, activity_id, child_activity)

        assert response is not None
        assert response.id != activity_id
Example #12
0
    def __handle_message_activity(self, activity):
        self.send_response(200)
        self.end_headers()
        credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
        connector = ConnectorClient(credentials, base_url=activity.service_url)
        resmsg = ''
        if (activity.text == "btc"):
            resmsg = kb.filldedorder(activity.text + "_krw")
        elif (activity.text == "bch"):
            resmsg = kb.filldedorder(activity.text + "_krw")
        elif (activity.text == "etc"):
            resmsg = kb.filldedorder(activity.text + "_krw")
        elif (activity.text == "xrp"):
            resmsg = kb.filldedorder(activity.text + "_krw")
        elif (activity.text == "bch orders"):
            resmsg = resmsg + "Asks\n"
            resmsg = resmsg + kb.orderbookasks("bch_krw")
            resmsg = resmsg + "Bids\n"
            resmsg = resmsg + kb.orderbookbids("bch_krw")
        elif (activity.text == "btc orders"):
            resmsg = resmsg + "Asks\n"
            resmsg = resmsg + kb.orderbookasks("btc_krw")
            resmsg = resmsg + "Bids\n"
            resmsg = resmsg + kb.orderbookbids("btc_krw")
        else:
            resmsg = "Didn't catch that, try bch or bch orders"

        reply = BotRequestHandler.__create_reply_activity(
            activity, '%s' % resmsg)
        connector.conversations.send_to_conversation(reply.conversation.id,
                                                     reply)
    def test_conversations_send_to_conversation_with_attachment(self):
        card1 = HeroCard(
            title='A static image',
            text='JPEG image',
            images=[
                CardImage(
                    url=
                    'https://docs.com/en-us/bot-framework/media/designing-bots/core/dialogs-screens.png'
                )
            ])

        card2 = HeroCard(
            title='An animation',
            subtitle='GIF image',
            images=[CardImage(url='http://i.giphy.com/Ki55RUbOV5njy.gif')])

        activity = Activity(
            type=ActivityTypes.message,
            channel_id=CHANNEL_ID,
            recipient=ChannelAccount(id=RECIPIENT_ID),
            from_property=ChannelAccount(id=BOT_ID),
            attachment_layout=AttachmentLayoutTypes.list,
            attachments=[
                Attachment(content_type='application/vnd.card.hero',
                           content=card1),
                Attachment(content_type='application/vnd.card.hero',
                           content=card2),
            ])

        connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
        response = connector.conversations.send_to_conversation(
            CONVERSATION_ID, activity)

        assert response is not None
Example #14
0
    def test_conversations_update_activity_invalid_conversation_id_fails(self):
        activity = Activity(type=ActivityTypes.message,
                            channel_id=CHANNEL_ID,
                            recipient=ChannelAccount(id=RECIPIENT_ID),
                            from_property=ChannelAccount(id=BOT_ID),
                            text='Updating activity...')

        activity_update = Activity(type=ActivityTypes.message,
                                   channel_id=CHANNEL_ID,
                                   recipient=ChannelAccount(id=RECIPIENT_ID),
                                   from_property=ChannelAccount(id=BOT_ID),
                                   text='Activity updated.')

        with pytest.raises(ErrorResponseException) as excinfo:
            connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
            response = self.loop.run_until_complete(
                connector.conversations.send_to_conversation_async(
                    CONVERSATION_ID, activity))
            activity_id = response.id
            self.loop.run_until_complete(
                connector.conversations.update_activity(
                    'INVALID_ID', activity_id, activity_update))

        assert excinfo.value.error.error.code == 'ServiceError'
        assert ('Invalid ConversationId'
                in str(excinfo.value.error.error.message))
    def test_conversations_get_conversation_members(self):
        connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
        members = connector.conversations.get_conversation_members(
            CONVERSATION_ID)

        assert len(members) == 2
        assert members[0].name == BOT_NAME
        assert members[0].id == BOT_ID
Example #16
0
 def __handle_conversation_update_activity(self, activity):
     self.send_response(202)
     self.end_headers()
     if activity.members_added[0].id != activity.recipient.id:
         credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
         reply = BotRequestHandler.__create_reply_activity(activity, 'Hello and welcome to the echo bot!')
         connector = ConnectorClient(credentials, base_url=reply.service_url)
         connector.conversations.send_to_conversation(reply.conversation.id, reply)
Example #17
0
 def test_conversations_get_conversation_members(self):
     connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
     members = self.loop.run_until_complete(
         connector.conversations.get_conversation_members_async(
             CONVERSATION_ID))
     assert len(members) == 2
     assert members[0].name == BOT_NAME
     assert members[0].id == BOT_ID
Example #18
0
 def replyFunction(replyText):
     credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
     connector = ConnectorClient(credentials,
                                 base_url=activity.service_url)
     reply = BotRequestHandler.__create_reply_activity(
         activity, replyText)
     connector.conversations.send_to_conversation(
         reply.conversation.id, reply)
Example #19
0
    def test_attachments_get_attachment_view_with_invalid_attachment_id_fails(
            self):
        with pytest.raises(msrest.exceptions.HttpOperationError) as excinfo:
            connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
            connector.attachments.get_attachment('bt13796-GJS4yaxDLI',
                                                 'original')

        assert ('Not Found' in str(excinfo.value))
    def test_attachments_get_info_invalid_attachment_id_fails(self):
        with pytest.raises(ErrorResponseException) as excinfo:
            connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
            self.loop.run_until_complete(
                connector.attachments.get_attachment_info_async(
                    'bt13796-GJS4yaxDLI'))

        assert ('Not Found' in str(excinfo.value))
 async def update_activity(self, activity: Activity):
     try:
         connector_client = ConnectorClient(self._credentials,
                                            activity.service_url)
         return connector_client.conversations.update_activity(
             activity.conversation.id, activity.conversation.activity_id,
             activity)
     except BaseException as e:
         raise e
Example #22
0
 def __handle_message_activity(self, activity):
     self.send_response(200)
     self.end_headers()
     credentials = MicrosoftAppCredentials(bot_app_id, bot_app_password)
     connector = ConnectorClient(credentials, base_url=activity.service_url)
     response = BotRequestHandler.process_message(activity.text)
     reply = BotRequestHandler.__create_reply_activity(activity, response)
     connector.conversations.send_to_conversation(reply.conversation.id,
                                                  reply)
    def test_conversations_delete_activity_with_invalid_conversation_id_fails(
            self):
        with pytest.raises(ErrorResponseException) as excinfo:
            connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
            connector.conversations.delete_activity("INVALID_ID", "INVALID_ID")

        assert excinfo.value.error.error.code == "ServiceError"
        assert "Invalid ConversationId" in str(
            excinfo.value.error.error.message)
    def test_conversations_get_conversation_members_invalid_id_fails(self):
        with pytest.raises(ErrorResponseException) as excinfo:
            connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
            connector.conversations.get_conversation_members("INVALID_ID")

        assert excinfo.value.error.error.code == "ServiceError"
        assert "cannot send messages to this id" in str(
            excinfo.value.error.error.message
        ) or "Invalid ConversationId" in str(excinfo.value.error.error.message)
Example #25
0
 def create_connector_client(self, service_url: str) -> ConnectorClient:
     """
     Allows for mocking of the connector client in unit tests.
     :param service_url:
     :return:
     """
     client = ConnectorClient(self._credentials, base_url=service_url)
     client.config.add_user_agent(USER_AGENT)
     return client
 async def delete_activity(self,
                           conversation_reference: ConversationReference):
     try:
         connector_client = ConnectorClient(
             self._credentials, conversation_reference.service_url)
         connector_client.conversations.delete_activity(
             conversation_reference.conversation.id,
             conversation_reference.activity_id)
     except BaseException as e:
         raise e
Example #27
0
    def test_conversations_get_conversation_members_invalid_id_fails(self):
        with pytest.raises(ErrorResponseException) as excinfo:
            connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
            members = self.loop.run_until_complete(
                connector.conversations.get_conversation_members_async(
                    'INVALID_ID'))

        assert excinfo.value.error.error.code == 'ServiceError'
        assert ('cannot send messages to this id' in str(
            excinfo.value.error.error.message) or 'Invalid ConversationId'
                in str(excinfo.value.error.error.message))
Example #28
0
    def test_conversations_delete_activity_with_invalid_conversation_id_fails(
            self):
        with pytest.raises(ErrorResponseException) as excinfo:
            connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
            self.loop.run_until_complete(
                connector.conversations.delete_activity_async(
                    'INVALID_ID', 'INVALID_ID'))

        assert excinfo.value.error.error.code == 'ServiceError'
        assert ('Invalid ConversationId'
                in str(excinfo.value.error.error.message))
Example #29
0
 def __handle_message_activity(self, activity):
     self.send_response(200)
     self.end_headers()
     credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
     connector = ConnectorClient(credentials, base_url=activity.service_url)
     new_str = re.findall(r"(\d+)\s*(\+|-|\*|\/)\s*(\d+)", activity.text)
     result = eval(''.join(new_str[0]))
     reply = BotRequestHandler.__create_reply_activity(
         activity, 'It is: %s' % result)
     connector.conversations.send_to_conversation(reply.conversation.id,
                                                  reply)
    def test_conversations_send_to_conversation(self):
        activity = Activity(type=ActivityTypes.message,
                            channel_id=CHANNEL_ID,
                            recipient=ChannelAccount(id=RECIPIENT_ID),
                            from_property=ChannelAccount(id=BOT_ID),
                            text='Hello again!')

        connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
        response = connector.conversations.send_to_conversation(
            CONVERSATION_ID, activity)

        assert response is not None