Example #1
0
    async def on_message_activity(self, turn_context: TurnContext):
        TurnContext.remove_recipient_mention(turn_context.activity)
        text = turn_context.activity.text.strip().lower()

        if "mention me" in text:
            await self._mention_adaptive_card_activity(turn_context)
            return

        if "mention" in text:
            await self._mention_activity(turn_context)
            return

        if "update" in text:
            await self._send_card(turn_context, True)
            return

        if "message" in text:
            await self._message_all_members(turn_context)
            return

        if "who" in text:
            await self._get_member(turn_context)
            return

        if "delete" in text:
            await self._delete_card_activity(turn_context)
            return

        await self._send_card(turn_context, False)
        return
    async def on_message_activity(self, turn_context: TurnContext):
        TurnContext.remove_recipient_mention(turn_context.activity)
        text = turn_context.activity.text.strip().lower()

        if "mention" in text:
            await self._mention_activity(turn_context)
            return

        if "message" in text:
            await self._message_all_members(turn_context)
            return

        if "whoareyou" in text:
            await self._reveal_future(turn_context)
            return

        if "whoami" in text:
            await self._get_member(turn_context)
            return

        if "delete" in text:
            await self._delete_card_activity(turn_context)
            return

        await self._send_card(turn_context, False)
        return
Example #3
0
    async def on_message_activity(self, turn_context: TurnContext):
        print(f'Message activity detected.')
        pprint(f'activity: {turn_context.activity}')
        TurnContext.remove_recipient_mention(turn_context.activity)

        # Remove punctuation and spaces
        regex = re.compile('[%s]' % re.escape(string.punctuation))
        text = regex.sub('', turn_context.activity.text)
        text = text.strip()
        print(text)
    async def on_message_activity(self, turn_context: TurnContext):
        TurnContext.remove_recipient_mention(turn_context.activity)
        turn_context.activity.text = turn_context.activity.text.strip()

        if turn_context.activity.text == "MentionMe":
            await self._mention_activity(turn_context)
            return

        if turn_context.activity.text == "UpdateCardAction":
            await self._update_card_activity(turn_context)
            return

        if turn_context.activity.text == "MessageAllMembers":
            await self._message_all_members(turn_context)
            return

        if turn_context.activity.text == "TestA":
            await turn_context.send_activity(
                MessageFactory.text("Ending conversation from the skillA..."))
            return

        if turn_context.activity.text == "TestB":
            await turn_context.send_activity(
                MessageFactory.text("Ending conversation from the skillB..."))
            return

        if turn_context.activity.text == "Delete":
            await self._delete_card_activity(turn_context)
            return

        card = HeroCard(
            title="Welcome Card",
            text="Click the buttons to update this card",
            buttons=[
                CardAction(
                    type=ActionTypes.message_back,
                    title="Update Card",
                    text="UpdateCardAction",
                    value={"count": 0},
                ),
                CardAction(
                    type=ActionTypes.message_back,
                    title="Message all memebers",
                    text="MessageAllMembers",
                ),
            ],
        )
        await turn_context.send_activity(
            MessageFactory.attachment(CardFactory.hero_card(card)))
        return
    async def on_message_activity(self, turn_context: TurnContext):
        TurnContext.remove_recipient_mention(turn_context.activity)
        if turn_context.activity.text == "delete":
            for activity in self.activity_ids:
                await turn_context.delete_activity(activity)

            self.activity_ids = []
        else:
            await self._send_message_and_log_activity_id(
                turn_context, turn_context.activity.text)

            for activity_id in self.activity_ids:
                new_activity = MessageFactory.text(turn_context.activity.text)
                new_activity.id = activity_id
                await turn_context.update_activity(new_activity)
Example #6
0
    async def on_message_activity(self, turn_context: TurnContext):
        TurnContext.remove_recipient_mention(turn_context.activity)
        text = turn_context.activity.text.strip().lower()

        if "summarize" in text:
            await self._summarize(turn_context)
            return

        if "recording" in text:
            await self._openMeetingRecording(turn_context)
            return

        if "last" in text:
            await self._last_meeting(turn_context)
            return

        if "previous" in text:
            await self._previous_meeting(turn_context)
    async def process_command(self, context: TurnContext) -> Any:
        if context.activity.type == ActivityTypes.message and context.activity.text:

            original_text = context.activity.text
            TurnContext.remove_recipient_mention(context.activity)

            command = context.activity.text.strip().split(" ")
            if len(command
                   ) > 1 and command[0] == InspectionMiddleware._COMMAND:

                if len(command) == 2 and command[1] == "open":
                    await self._process_open_command(context)
                    return True

                if len(command) == 3 and command[1] == "attach":
                    await self.process_attach_command(context, command[2])
                    return True

            context.activity.text = original_text

        return False
Example #8
0
    def test_should_remove_at_mention_from_activity(self):
        activity = Activity(
            type="message",
            text="<at>TestOAuth619</at> test activity",
            recipient=ChannelAccount(id="TestOAuth619"),
            entities=[
                Mention(
                    type="mention",
                    text="<at>TestOAuth619</at>",
                    mentioned=ChannelAccount(name="Bot", id="TestOAuth619"),
                )
            ],
        )

        text = TurnContext.remove_recipient_mention(activity)

        assert text, " test activity"
        assert activity.text, " test activity"
    def test_should_remove_at_mention_with_regex_characters(self):
        activity = Activity(
            type="message",
            text="<at>Test (*.[]$%#^&?)</at> test activity",
            recipient=ChannelAccount(id="Test (*.[]$%#^&?)"),
            entities=[
                Entity().deserialize(
                    Mention(
                        type="mention",
                        text="<at>Test (*.[]$%#^&?)</at>",
                        mentioned=ChannelAccount(name="Bot",
                                                 id="Test (*.[]$%#^&?)"),
                    ).serialize())
            ],
        )

        text = TurnContext.remove_recipient_mention(activity)

        assert text == " test activity"
        assert activity.text == " test activity"
Example #10
0
    async def on_message_activity(self, turn_context: TurnContext):
        TurnContext.remove_recipient_mention(turn_context.activity)
        turn_context.activity.text = turn_context.activity.text.strip()

        await turn_context.send_activities(
            [Activity(type=ActivityTypes.typing)])

        # LUIS request
        request_query = "{}/apps/{}?staging=true&verbose=true&timezoneOffset=-180&subscription-key={}&q='{}'".format(
            CONFIG.LUIS_ENDPOINT, CONFIG.LUIS_APP_ID, CONFIG.LUIS_RUNTIME_KEY,
            turn_context.activity.text.lower())

        response = requests.get(request_query).json()

        print(request_query)
        print(response.get('topScoringIntent').get('intent'))

        intent = response.get('topScoringIntent').get('intent')

        if intent == 'Greeting':
            await self._greet_back(turn_context)
            return

        if intent == 'GetServiceStatus':
            for entity in response.get('entities'):
                if entity.get('role') == 'TargetServer':
                    target_server = entity.get('entity').replace(" ", "")
                if entity.get('role') == 'ServiceName':
                    service_name = entity.get('entity')

        #if target_server and service_name:
            if 'target_server' in locals() and 'service_name' in locals():

                request_ps_result = request_ps_expression(
                    target_server,
                    f"Get-Service -Name {service_name} | Select Name, DisplayName, Status | ConvertTo-Json -Compress",
                    turn_context.activity.from_property.aad_object_id,
                    turn_context.activity.from_property.name)
                #ps_result = powershell.invoke("Get-Service {} -ComputerName {}".format(service_name, target_server))
                if request_ps_result:
                    await turn_context.send_activity(
                        "O Serviço '{}' ({}) está com status: {}.".format(
                            request_ps_result.get("Name"),
                            request_ps_result.get("DisplayName"),
                            switchers.SERVICE_STATUS_SWITCHER.get(
                                request_ps_result.get("Status"))))
                else:
                    await turn_context.send_activity(
                        "Não encontrei nada sobre o serviço '{}' no host '{}'."
                        .format(service_name, target_server))
                    await turn_context.send_activity(
                        "Verifique se os nomes do serviço e host estão corretos."
                    )
            else:
                await turn_context.send_activity(
                    "Entendo que você precisa de informações sobre um serviço do Windows, porém preciso de mais informações."
                )
                await turn_context.send_activity(
                    "Preciso do nome do serviço e nome do servidor.")
            return

        if intent == 'GetADUserInfo':
            target_server = "asl-ad04"
            ps_command_tail = "-Properties DisplayName | Select Name, SamAccountName, DisplayName, UserPrincipalName, Enabled | ConvertTo-Json -Compress"
            for entity in response.get('entities'):
                if entity.get('role') == 'CPF':
                    identity = re.sub(r'\.|-| ', '', entity.get('entity'))
                    ps_command = f"Get-ADUser -Identity {identity} {ps_command_tail}"
                elif entity.get('role') == 'Email':
                    identity = re.replace(' ', '', entity.get('entity'))
                    ps_command = f"Get-ADUser -Filter {{UserPrincipalName -eq \"{identity}\"}} {ps_command_tail}"

            if ps_command:
                request_ps_result = request_ps_expression(
                    target_server, ps_command,
                    turn_context.activity.from_property.aad_object_id,
                    turn_context.activity.from_property.name)

                if request_ps_result:
                    await turn_context.send_activity(
                        "SamAccountName: {} - Nome: {} - Email: {} - Habilitado: {}"
                        .format(
                            request_ps_result.get("SamAccountName"),
                            request_ps_result.get("DisplayName"),
                            request_ps_result.get("UserPrincipalName"),
                            switchers.ADUSER_ENABLED_SWITCHER.get(
                                request_ps_result.get("Enabled"))))
                else:
                    await turn_context.send_activity("Não encontrei ninguém :("
                                                     )
                    await turn_context.send_activity(
                        "Verifique se os dados estão corretos. Pode ser que eu seja incompetente também."
                    )
            else:
                await turn_context.send_activity(
                    "Entendo que você gostaria de buscar por uma pessoa no AD, porém não consegui identificar as informações dela."
                )
                await turn_context.send_activity(
                    "Preciso de um CPF, Nome ou E-mail.")
            return

        if intent == 'AADConnectSyncResult':
            await turn_context.send_activity(
                "Você quer saber o resultado da sincronização do Office 365?")
            return

        if turn_context.activity.text.lower() == "michael!":
            await self._show_members(turn_context)
            return

        if turn_context.activity.text == "UpdateCardAction":
            await self._update_card_activity(turn_context)
            return

        if turn_context.activity.text == "Delete":
            await self._delete_card_activity(turn_context)
            return

        card = HeroCard(
            title="O que você quer?",
            text="Tenho algumas sugestões...",
            buttons=[
                CardAction(
                    type=ActionTypes.message_back,
                    title="Update Card",
                    text="UpdateCardAction",
                    value={"count": 0},
                )
            ],
        )
        await turn_context.send_activity(
            MessageFactory.attachment(CardFactory.hero_card(card)))
        return
Example #11
0
    async def on_message_activity(self, turn_context: TurnContext):
        """
        Respond to messages sent from the user.
        """
        self._add_conversation_reference(turn_context.activity)

        global trak_name
        global trak_allergy_url
        global trak_careProvider
        global trak_dob
        global trak_gender
        global trak_recordNumber
        global trak_url
        global gname
        global trak_lastUpdated
        global allergy_data
        global OAuth_url
        global r_name
        global r_urn
        global r_url
        global ob_url
        global r_sender
        global r_message

        # Get the state properties from the turn context.
        welcome_user_state = await self.user_state_accessor.get(
            turn_context, WelcomeUserState)

        if not welcome_user_state.did_welcome_user:
            welcome_user_state.did_welcome_user = True

            # Will be on first message from user
            await turn_context.send_activity("Welcome Back !")

            name = turn_context.activity.from_property.name
            gname = name
            await turn_context.send_activity(
                f"What can I help you with {name} ?")

        else:
            # removes mention from the user input in channels or group
            TurnContext.remove_recipient_mention(turn_context.activity)

            # Credentials for OAuth2
            authorize_url = "https://tcfhirsandbox.intersystems.com.au/oauth2/authorize"
            token_url = "https://tcfhirsandbox.intersystems.com.au/oauth2/token"
            state = 'asdasdasdasdasdasasd'
            scope = 'patient%2F*.read%20launch%2Fpatient'
            callback_uri = "x-argonaut-app://HealthProviderLogin/"
            my_redirect = "https://23deef16c21f.ngrok.io/api/auth_code"
            test_redirect = "https://www.intersystems.com"
            client_id = '6A605kYem9GmG38Vo6TTzh8IFnjWHZWtRn46K1hoxQY'
            r_client_id = "2rv9NDv0WFZVS19o3VTZbrMjqX8mjiCFrxab7dknSC0"
            client_secret = 'POrisHrcdMvUKmaR6Cea0b8jtx-z4ewVWrnaIXASO-H3tB3g5MgPV7Vqty7OP8aEbSGENWRMkeVuJJKZDdG7Pw'
            new_secret = "UcU7Kzo-6oYRfuCfcL0wUgsiEXQIT2kQOfCqir6wFRdSXjML1y80bJp29_4Q9GqYRXI-5vIswB1KVGIhIiNXjg"
            #OAuth_url = authorize_url + '?response_type=code&state=' + state + '&client_id=' + r_client_id + '&scope='+scope+'&redirect_uri=' + callback_uri
            OAuth_url = authorize_url + '?response_type=code&state=' + state + '&client_id=' + client_id + '&scope=' + scope + '&redirect_uri=' + callback_uri
            # Process data from teams to check if there is input via cards
            channelData = turn_context.activity.channel_data
            enter_val = turn_context.activity.value
            if enter_val != None or "postBack" in channelData:
                global token
                try:
                    val = json.dumps(turn_context.activity.value)
                    commandToken = json.loads(val)
                    authorization_code = commandToken['SimpleVal']
                    data = {
                        'grant_type': 'authorization_code',
                        'code': authorization_code,
                        'redirect_uri': callback_uri
                    }
                    access_token_response = requests.post(token_url,
                                                          data=data,
                                                          verify=True,
                                                          allow_redirects=True,
                                                          auth=(client_id,
                                                                client_secret))
                    tokens = json.loads(access_token_response.text)
                    access_token = tokens['access_token']
                    token = access_token
                    await turn_context.send_activity(f"Login successful !​​​​")
                    return None
                except:
                    await turn_context.send_activity(
                        f"Authorization Code is Invalid !")

            # makes the text in lower case and strips of any spaces
            text = turn_context.activity.text.lower().strip()
            # splits the user input and makes a list
            ltxt = text.split(" ")

            # Use this if cards dosen't work for you, token needs to be entered manually each time it expires.
            #token = 'IiU-3EAUcBTssUvwh7FcQuM1buLNhAq-Y52r_Bkiemo90m5LG6yx0R-XpWRPwX9bMPdJS4Vt1ynhBMAmsK_k0w'

            # header for reqesting data from FHIR
            call_header = {
                'accept': 'application/json',
                'Authorization': 'Bearer ' + token
            }

            # keywords that will be used by the bot to compare the user input and react accordingly
            if text in ("hello", "hi"):
                await turn_context.send_activity(
                    f"why would you say {text} again ?")

            elif text in ("help", "intro"):
                await self.__send_intro_card(turn_context)

            elif text in ("login"):
                await self.__send_oauth_card(turn_context)

            elif text == "delete":
                self.list_care_provider.clear()
                await turn_context.send_activity(
                    "The care provider list is empty now!")

            elif text == "standard channel":
                if turn_context.activity.channel_id == Channels.ms_teams:
                    try:
                        graph_token = get_graph_token()
                        standard_channel(graph_token)
                        await turn_context.send_activity(
                            "A standard channel created!")
                    except:
                        await turn_context.send_activity(
                            "This function is only supported in teams/channels!"
                        )

                else:
                    await turn_context.send_activity(
                        "This function is only supported in Microsoft Teams")

            elif text == "private channel":
                if turn_context.activity.channel_id == Channels.ms_teams:
                    try:
                        graph_token = get_graph_token()
                        members = all_team_members(graph_token)["value"]
                        ids = []
                        for provider in self.list_care_provider:
                            for member in members:
                                if member["displayName"] == provider['name']:
                                    ids.append(member["id"])
                        ls_member = []
                        count = 0
                        for id_number in ids:
                            if count == 0:
                                add = owner_object(id_number)
                            else:
                                add = member_object(id_number)
                            ls_member.append(add)
                            count = count + 1
                        if len(ls_member) == 0:
                            await turn_context.send_activity(
                                "No provider is received")
                        else:
                            private_channel(graph_token, ls_member)
                            await turn_context.send_activity(
                                "A private channel with the care providers created!"
                            )

                    except:
                        await turn_context.send_activity(
                            "This function is only supported in teams/channels!"
                        )

                else:
                    await turn_context.send_activity(
                        "This function is only supported in Microsoft Teams")

            elif text in ("patient"):
                await turn_context.send_activity(
                    'Please type the patient ID after patient. Eg: "patient 137"'
                )

            elif ltxt[0] == "patient":
                if ltxt[1] != "0":
                    url = "https://tcfhirsandbox.intersystems.com.au/fhir/dstu2/Patient/" + ltxt[
                        1]
                    response = requests.get(url,
                                            headers=call_header,
                                            verify=True)

                    if response.status_code == 404:
                        await turn_context.send_activity("Patient not found !")
                    elif response.status_code == 401:
                        await turn_context.send_activity(
                            "Your token has expired !")
                    elif response.status_code == 200:
                        r_dict = json.loads(response.text)

                        trak_url = (
                            f"https://tcfhirsandbox.intersystems.com.au/t2019grxx/csp/system.Home.cls#/Direct/AW.Direct.EPR?RegistrationNo={str(r_dict['identifier'][1]['value'])}"
                        )
                        ob_url = "https://www.google.com/"

                        try:
                            pat_name = (f"{r_dict['name'][0]['text']}")
                            trak_name = pat_name.upper()
                        except:
                            trak_name = "Couldn't find NAME in database"
                        try:
                            lastUpdated = (f"{r_dict['meta']['lastUpdated']}")
                            utc = (f"{lastUpdated[0:10]} {lastUpdated[12:19]}")
                            trak_lastUpdated = zone_convertor(utc)
                        except:
                            trak_lastUpdated = "No DATE found"
                        try:
                            trak_careProvider = (
                                f"{r_dict['careProvider'][0]['display']}")
                        except:
                            trak_careProvider = "Couldn't find CARE PROVIDER in database"
                        try:
                            trak_recordNumber = (
                                f"{r_dict['identifier'][1]['value']}")
                        except:
                            trak_recordNumber = "Couldn't find RECORD NUMBER in database"
                        try:
                            trak_dob = (f"{r_dict['birthDate']}")
                        except:
                            trak_dob = "Couldn't find DOB in database"
                        try:
                            trak_gender = (f"{r_dict['gender']}")
                        except:
                            trak_gender = "GENDER is not disclosed by the patient"

                        trak_allergy_url = (
                            f"https://tcfhirsandbox.intersystems.com.au/fhir/dstu2/Patient/{ltxt[1]}/AllergyIntolerance"
                        )

                        allergy_resposne = requests.get(trak_allergy_url,
                                                        headers=call_header,
                                                        verify=True)
                        a_dict = json.loads(allergy_resposne.text)
                        a_total = (f"{a_dict['total']}")

                        if a_total != "0":
                            count = int(a_total)
                            index = count - 1
                            allergy_name = ""
                            allergy_reaction = ""
                            allergy_severity = ""
                            allergy_recordedDate = ""

                            while count != 0:
                                try:
                                    allergy_name = allergy_name + (
                                        f"{a_dict['entry'][index]['resource']['substance']['text']}:"
                                    )
                                except:
                                    allergy_name = "Unknown"
                                try:
                                    allergy_reaction = allergy_reaction + (
                                        f"{a_dict['entry'][index]['resource']['reaction'][0]['manifestation'][0]['text']}:"
                                    )  # it is possible that there are more sublist under reaction and manifestation
                                except:
                                    allergy_reaction = "No record found"
                                try:
                                    allergy_severity = allergy_severity = allergy_severity + (
                                        f"{a_dict['entry'][index]['resource']['reaction'][0]['severity']}:"
                                    )
                                except:
                                    allergy_severity = "No record found"
                                try:
                                    utc_date = (
                                        f"{a_dict['entry'][index]['resource']['recordedDate']}|"
                                    )
                                    dt = utc_date.split("T")
                                    t = dt[1].split("+")
                                    dt_format = (f"{dt[0]} {t[0]}")
                                    allergy_recordedDate = allergy_recordedDate + zone_convertor(
                                        dt_format) + "|"
                                except:
                                    allergy_recordedDate = "Date Unknown"

                                index = index - 1
                                count = count - 1

                            list_name = allergy_name.split(":")
                            list_reaction = allergy_reaction.split(":")
                            list_severity = allergy_severity.split(":")
                            list_date = allergy_recordedDate.split("|")

                            allergy_data = ""
                            total_allergy = int(a_total)

                            list_index = 0
                            while list_index < total_allergy:
                                allergy_data = allergy_data + (
                                    f"Allergen : {list_name[list_index]}\n\nReaction : {list_reaction[list_index]}\n\nSeverity : {list_severity[list_index]}\n\nRecorded Date : {list_date[list_index]}\n\n-------------------------------------\n\n"
                                )
                                list_index += 1
                        else:
                            allergy_data = (
                                f"{trak_name} have no recorded allergies")

                        await self.__send_about_card(turn_context)

                    else:
                        await turn_context.send_activity(
                            "You are not logged in. Please type 'Login' to start your session !"
                        )

            elif ltxt[0] == "mrn":

                url = "https://tcfhirsandbox.intersystems.com.au/fhir/dstu2/Patient?identifier=" + ltxt[
                    1]
                response = requests.get(url, headers=call_header, verify=True)
                if response.status_code == 404:
                    await turn_context.send_activity("Patient not found !")
                elif response.status_code == 401:
                    await turn_context.send_activity("Your token has expired !"
                                                     )
                elif response.status_code == 200:
                    r_dict = json.loads(response.text)
                    trak_url = (
                        f"https://tcfhirsandbox.intersystems.com.au/t2019grxx/csp/system.Home.cls#/Direct/AW.Direct.EPR?RegistrationNo={ltxt[1]}"
                    )
                    ob_url = "https://www.google.com/"

                    try:
                        pat_name = (
                            f"{r_dict['entry'][0]['resource']['name'][0]['text']}"
                        )
                        trak_name = pat_name.upper()
                    except:
                        trak_name = "Couldn't find NAME in database"
                    try:
                        lastUpdated = (
                            f"{r_dict['entry'][0]['resource']['meta']['lastUpdated']}"
                        )
                        utc = (f"{lastUpdated[0:10]} {lastUpdated[12:19]}")
                        trak_lastUpdated = zone_convertor(utc)
                    except:
                        trak_lastUpdated = "No DATE found"
                    try:
                        trak_careProvider = (
                            f"{r_dict['entry'][0]['resource']['careProvider'][0]['display']}"
                        )
                    except:
                        trak_careProvider = "Couldn't find CARE PROVIDER in database"
                    try:
                        trak_recordNumber = (
                            f"{r_dict['entry'][0]['resource']['identifier'][1]['value']}"
                        )
                    except:
                        trak_recordNumber = "Couldn't find RECORD NUMBER in database"
                    try:
                        trak_dob = (
                            f"{r_dict['entry'][0]['resource']['birthDate']}")
                    except:
                        trak_dob = "Couldn't find DOB in database"
                    try:
                        trak_gender = (
                            f"{r_dict['entry'][0]['resource']['gender']}")
                    except:
                        trak_gender = "GENDER is not disclosed by the patient"

                    trak_allergy_url = (
                        f"https://tcfhirsandbox.intersystems.com.au/fhir/dstu2/Patient/{r_dict['entry'][0]['resource']['id']}/AllergyIntolerance"
                    )

                    allergy_resposne = requests.get(trak_allergy_url,
                                                    headers=call_header,
                                                    verify=True)
                    a_dict = json.loads(allergy_resposne.text)
                    a_total = (f"{a_dict['total']}")

                    if a_total != "0":
                        count = int(a_total)
                        index = count - 1
                        allergy_name = ""
                        allergy_reaction = ""
                        allergy_severity = ""
                        allergy_recordedDate = ""

                        while count != 0:
                            try:
                                allergy_name = allergy_name + (
                                    f"{a_dict['entry'][index]['resource']['substance']['text']}:"
                                )
                            except:
                                allergy_name = "Unknown"
                            try:
                                allergy_reaction = allergy_reaction + (
                                    f"{a_dict['entry'][index]['resource']['reaction'][0]['manifestation'][0]['text']}:"
                                )  # it is possible that there are more sublist under reaction and manifestation
                            except:
                                allergy_reaction = "No record found"
                            try:
                                allergy_severity = allergy_severity + (
                                    f"{a_dict['entry'][index]['resource']['reaction'][0]['severity']}:"
                                )
                            except:
                                allergy_severity = "No record found"
                            try:
                                utc_date = (
                                    f"{a_dict['entry'][index]['resource']['recordedDate']}|"
                                )
                                date_t = utc_date.split("T")
                                t = date_t[1].split("+")
                                dt_format = (f"{date_t[0]} {t[0]}")
                                allergy_recordedDate = allergy_recordedDate + zone_convertor(
                                    dt_format) + "|"
                            except:
                                allergy_recordedDate = "Date Unknown"
                            index = index - 1
                            count = count - 1

                        list_name = allergy_name.split(":")
                        list_reaction = allergy_reaction.split(":")
                        list_severity = allergy_severity.split(":")
                        list_date = allergy_recordedDate.split("|")
                        allergy_data = ""
                        total_allergy = int(a_total)
                        list_index = 0

                        while list_index < total_allergy:
                            allergy_data = allergy_data + (
                                f"Allergen : {list_name[list_index]}\n\nReaction : {list_reaction[list_index]}\n\nSeverity : {list_severity[list_index]}\n\nRecorded Date : {list_date[list_index]}\n\n-------------------------------------\n\n"
                            )
                            list_index += 1
                    else:
                        allergy_data = (
                            f"{trak_name} have no recorded allergies")

                    await self.__send_about_card(turn_context)

                else:
                    await turn_context.send_activity(
                        "You are not logged in. Please type 'Login' to start your session !"
                    )

            #list all providers
            elif text in ("provider", "mdt"):
                global cp_list
                cp_list = ""
                for provider in self.list_care_provider:
                    cp_list = cp_list + (
                        f"{provider['id']} - {provider['name']} \n\n")
                await self.__send_mdt_card(turn_context)

            #mention provider in the teams
            elif text in ("mention", "mention care providers"):
                if turn_context.activity.channel_id == Channels.ms_teams:
                    try:
                        members = await TeamsInfo.get_team_members(turn_context
                                                                   )
                        for provider in self.list_care_provider:
                            for member in members:
                                if member.name == provider['name']:
                                    mention = Mention(
                                        mentioned=member,
                                        text=f"<at>{member.name}</at>",
                                        type="mention",
                                    )
                                    reply_activity = MessageFactory.text(
                                        f"{mention.text}")
                                    reply_activity.entities = [
                                        Mention().deserialize(
                                            mention.serialize())
                                    ]
                                    await turn_context.send_activity(
                                        reply_activity)

                    except:
                        await turn_context.send_activity(
                            "This function is only supported in teams/channels!"
                        )

                else:
                    await turn_context.send_activity(
                        "This function is only supported in Microsoft Teams")

            elif text in ("result", "results"):
                r_name = self.dict_results['name']
                r_urn = self.dict_results['urn']
                r_url = self.dict_results['link']
                r_sender = self.dict_results['sender']
                r_message = self.dict_results['message']
                self.dict_results.clear()
                await self.__send_result_card(turn_context)

            else:
                await turn_context.send_activity(
                    "I am SORRY!, I don't understand that.")
    async def on_message_activity(self, turn_context: TurnContext):
        if turn_context.activity.text:
            TurnContext.remove_recipient_mention(turn_context.activity)
            turn_context.activity.text = turn_context.activity.text.strip(
            ).lower()
            text = turn_context.activity.text
            if text == "command:reset":
                await self._reset_bot(turn_context)
            elif text == "command:getsdkversions":
                await self._return_current_sdk_version(turn_context)
            elif text == "proactivent":
                await self._send_proactive_non_threaded_message(turn_context)
            elif text == "proactive":
                await self._send_proactive_threaded_message(turn_context)
            elif text == "delete":
                await self._delete_activity(turn_context)
            elif text == "update":
                await self._update_activity(turn_context)
            elif text == "1":
                await self._send_adaptive_card(turn_context, 1)
            elif text == "2":
                await self._send_adaptive_card(turn_context, 2)
            elif text == "3":
                await self._send_adaptive_card(turn_context, 3)
            elif text == "hero":
                await self._send_hero_card(turn_context)
            elif text == "thumbnail":
                await self._send_thumbnail_card(turn_context)
            elif text == "receipt":
                await self._send_receipt_card(turn_context)
            elif text == "signin":
                await self._send_signin_card(turn_context)
            elif text == "carousel":
                await self._send_carousel_card(turn_context)
            elif text == "list":
                await self._send_list_card(turn_context)
            elif text == "o365":
                await self._send_o365_card(turn_context)
            elif text == "file":
                filename = "teams-logo.png"
                file_path = "files/" + filename
                file_size = os.path.getsize(file_path)
                await self._send_file_card(turn_context, filename, file_size)
            elif text == "show members":
                await self._show_members(turn_context)
            elif text == "show channels":
                await self._show_channels(turn_context)
            elif text == "show details":
                await self._show_team_details(turn_context)
            elif text == "task module":
                await self._show_task_module(turn_context)
            elif text == "mention":
                await self._mention_activity(turn_context)
            elif text == "upload file":
                await self._show_upload_file(turn_context)
            else:
                await self._send_message_and_log_activity_id(
                    turn_context, f"You said: {turn_context.activity.text}")
        else:
            await turn_context.send_activity(
                MessageFactory.text("App sent a message with empty text"))
            if turn_context.activity.value:
                await self._send_message_and_log_activity_id(
                    turn_context,
                    f"but with value {json.dumps(turn_context.activity.value)}",
                )

        return
Example #13
0
    async def on_message_activity(self, turn_context: TurnContext):
        TurnContext.remove_recipient_mention(turn_context.activity)
        #turn_context.activity.text = turn_context.activity.text.strip()
        text = turn_context.activity.text.strip()
        print("text: "+ text)



        if text == "TestA":
            reply = "我是回覆測試A"        
            await turn_context.send_activity(
                MessageFactory.text(reply)
            )
            print(text)
            print(reply)
            return 


        if text == "TestB":     
            reply = "I'm test reply B"    
            await turn_context.send_activity(
                MessageFactory.text(reply)
            )
            print(text)
            print(reply)
            return 

##########***天氣預報***#########  

        if text == "!天氣預報":
            #content = "請輸入欲查詢地點\n(目前限台灣本島+離島)\n\n使用方式如下(已設有防呆):\n!台北市\n!臺北市\n!台北\n!臺北\n!taipei"
            await turn_context.send_activity(
                MessageFactory.text("請輸入欲查詢地點\n(目前限台灣本島+離島)\n\n使用方式如下(已設有防呆):\n!台北市\n!臺北市\n!台北\n!臺北\n!taipei")
            )
            return 0
        if text == "!台北市" or text == "!臺北市" or text == "!台北" or text == "!臺北" or text == "!taipei":
            content = weather(L=0)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!新北市" or text == "!新北" or text == "!new taipei":
            content = weather(L=1)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!桃園市" or text == "!taoyuan":
            content = weather(L=2)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!台中市" or text == "!臺中市" or text == "!台中" or text == "!臺中" or text == "!taichung":
            content = weather(L=3)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!台南市" or text == "!臺南市" or text == "!台南" or text == "!臺南" or text == "!tainan":
            content = weather(L=4)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!高雄市" or text == "!高雄" or text == "!kaohsiung":
            content = weather(L=5)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!基隆市" or text == "!基隆" or text == "!keelung":
            content = weather(L=6)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!新竹縣" or text == "!hsinchu county":
            content = weather(L=7)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!新竹市" or text == "!hsinchu city":
            content = weather(L=8)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!苗栗縣" or text == "!苗栗" or text == "!miaoli":
            content = weather(L=9)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!彰化縣" or text == "!彰化" or text == "!changhua":
            content = weather(L=10)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!南投縣" or text == "!南投" or text == "!nantou":
            content = weather(L=11)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!雲林縣" or text == "!雲林" or text == "!yunlin":
            content = weather(L=12)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!嘉義縣" or text == "!chiayi county":
            content = weather(L=13)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!嘉義市" or text == "!chiayi city":
            content = weather(L=14)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!屏東縣" or text == "!屏東" or text == "!pingtung":
            content = weather(L=15)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!宜蘭縣" or text == "!宜蘭" or text == "!ilan":
            content = weather(L=16)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!花蓮縣" or text == "!花蓮" or text == "!hualien":
            content = weather(L=17)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!臺東縣" or text == "!台東" or text == "!taitung":
            content = weather(L=18)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!澎湖縣" or text == "!澎湖" or text == "!penghu":
            content = weather(L=19)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!金門縣" or text == "!金門" or text == "!jinmen":
            content = weather(L=20)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0
        if text == "!連江縣" or text == "!連江" or text == "!lianjiang":
            content = weather(L=21)
            await turn_context.send_activity(
             MessageFactory.text(content)
            )
            return 0