コード例 #1
0
ファイル: tasks.py プロジェクト: yeolpyeong/practicalML
def response(message):
    if message["type"] == "message":
        ReplyToActivity(fill=message, text=reply(message)).send()
コード例 #2
0
ファイル: tasks2.py プロジェクト: robin521111/deeplearning
def synchronous_response(message):
    if message["type"] == "message":
        if 'synchronous' in message["text"] and 'asynchronous' not in message[
                'text']:
            ReplyToActivity(fill=message,
                            channelData=None,
                            text='Synchronous Test: {}'.format(
                                message["text"])).send()

        elif 'config' in message["text"]:
            config = Config()
            ReplyToActivity(fill=message,
                            text='Config: {}'.format(config.config)).send()

        elif 'simple history' in message['text']:
            state = get_state()
            ReplyToActivity(
                fill=message,
                text=json.dumps({
                    'allHistory':
                    state.get_activities(3, simple=True),
                    'conversationHistory':
                    state.get_activities(
                        3,
                        simple=True,
                        conversation_id=message['conversation']['id'])
                })).send()

        elif 'history' in message['text']:
            state = get_state()
            ReplyToActivity(
                fill=message,
                text=json.dumps({
                    'allHistory':
                    state.get_activities(3),
                    'conversationHistory':
                    state.get_activities(
                        3, conversation_id=message['conversation']['id'])
                })).send()

        elif "members" in message['text']:
            conversation_response = GetConversationMembers(fill=message).send()
            activity_response = GetActivityMembers(fill=message).send()

            response_text = 'Conversation: {}; Activity: {}'.format(
                conversation_response.text, activity_response.text)
            personal_message(message, response_text)

        elif "image" in message['text']:
            content_url = 'https://imgflip.com/s/meme/Cute-Cat.jpg'
            ReplyToActivity(fill=message,
                            attachments=[{
                                'contentType': 'image/jpeg',
                                'contentUrl': content_url,
                                'name': 'cute cat.jpg',
                            }]).send()

        elif 'delete' in message['text']:
            response_info = ReplyToActivity(fill=message,
                                            text='Delete Test: {}'.format(
                                                message["text"])).send()

            sleep(2)

            activity_id = response_info.json()['id']
            DeleteActivity(fill=message, activityId=activity_id).send()

        elif 'personal' in message['text']:
            personal_message(message,
                             'Personal Message: {}'.format(message['text']))

        elif 'asynchronous' not in message["text"]:
            ReplyToActivity(fill=message, text='Nothing was queried').send()
コード例 #3
0
ファイル: tasks.py プロジェクト: uvacw/CART
def echo_response(message):
    conditionid = None
    participantid = None
    # CONTACT RELATION UPDATE: Agent is added to Skype
    if message["type"] == "contactRelationUpdate":
        if 'action' in message.keys():
            if message['action'] == 'add':
                resp_speech = '[STANDARDWELCOMEMESSAGE]'
                resp_speech = check_rephrase(resp_speech)

                log_response(db, message, resp_speech, resp_speech)
                if 'channelData' in message.keys():
                    del message['channelData']['clientActivityID']
                ReplyToActivity(fill=message, text=resp_speech).send()
                return

    # MESSAGE: Default type of conversation
    if message["type"] == "message":
        if 'text' not in message.keys():
            message['text'] = '-'

        message['text'] = str(message['text']).replace("'", '‘')
        conversationid = message['conversation']['id']
        conversationid_trunc = conversationid[0:35]

        resp_speech = None

        resp = detect_intent_texts(conversationid_trunc, str(message['text']))

        try:
            # resp_speech = resp_dialogflow.query_result.fulfillment_text
            resp_speech = resp['fulfillmentText']
        except:
            resp_speech = 'ERROR: ' + str(resp_dialogflow)

        if not resp_speech:
            try:
                resp_speech = resp['result']['fulfillment']['speech']
            except:
                resp_speech = resp['result']['fulfillment']['messages'][0][
                    'speech']

        conversation_status, conversation_code, conditionid, participantid = get_conversation_status(
            db, conversationid, message, resp)
        print(conversation_code, conditionid, conversation_status)

        message = log_message(db, message, participantid=participantid)
        override = check_override(message['text'])

        ## Performing manual connection if intents in DialogFlow
        connect_intent = None
        # If the conversation_status is considered invalid (due to invalid participant id)
        if conversation_status == 'conditionid_invalid':
            override_invalid_participantid = get_participantid_invalid()
            if override_invalid_participantid:
                connect_intent = '[' + str(
                    override_invalid_participantid) + ']'
                log_response(db,
                             message,
                             connect_intent,
                             conversation_status,
                             participantid=participantid)

        # If the response in DialogFlow needs to connect manually to a new intent
        elif 'connect_intents' in cfg.keys():
            for source_intent, target_intent in cfg['connect_intents'].items():
                if resp_speech == '[' + str(source_intent) + ']':
                    print('check 1:', source_intent)
                    connect_intent = '[' + str(target_intent) + ']'
                    log_response(db,
                                 message,
                                 connect_intent,
                                 conversation_status,
                                 participantid=participantid)

        if connect_intent:
            ai = apiai.ApiAI(cfg['other']['dialogflow_access_token'])
            request = ai.text_request()
            request.lang = 'en'  # optional, default value equal 'en'
            request.session_id = conversationid_trunc
            request.query = connect_intent

            respAPI = request.getresponse()
            resp = respAPI.read().decode('utf-8')
            resp = json.loads(resp)
            try:
                resp_speech = resp['result']['fulfillment']['speech']
            except:
                resp_speech = resp['result']['fulfillment']['messages'][0][
                    'speech']

            resp_speech = check_rephrase(resp_speech,
                                         conversation_code=conversation_code,
                                         conditionid=conditionid)
            log_response(db,
                         message,
                         resp_speech,
                         resp,
                         participantid=participantid)
            if 'channelData' in message.keys():
                del message['channelData']['clientActivityID']
            ReplyToActivity(fill=message, text=resp_speech).send()

        elif override['override'] == True:
            resp_speech = check_rephrase(override['resp_speech'],
                                         conversation_code=conversation_code)
            reason_override = override['reason']
            log_response(db,
                         message,
                         resp_speech,
                         reason_override,
                         participantid=participantid)
            ReplyToActivity(fill=message, text=resp_speech).send()

        else:
            resp_speech = check_rephrase(resp_speech,
                                         conversation_code=conversation_code,
                                         conditionid=conditionid)
            message['textFormat'] = 'markdown'
            log_response(db,
                         message,
                         resp_speech,
                         resp,
                         participantid=participantid)
            #override for disappearing messages
            if 'channelData' in message.keys():
                del message['channelData']['clientActivityID']
            ReplyToActivity(fill=message, text=resp_speech).send()
コード例 #4
0
ファイル: tasks.py プロジェクト: thetwoj/gvobot
def activity_handler(activity):
    if activity['type'] == 'message':
        message = activity['text']
        response = _message_handler(message)
        ReplyToActivity(fill=activity, text=response).send()
コード例 #5
0
ファイル: tasks.py プロジェクト: anjyzplace/chatbot
def guide(sentenceClass, message):
    guideMessage = "I am LifeBot. I can give healthy "+ sentenceClass +" recommendations."
    ReplyToActivity(fill=message,
            text=guideMessage).send()
コード例 #6
0
ファイル: tasks.py プロジェクト: DamiJeongTab/tabbot
def echo_response(message):
    if message["type"] == "message":
        ReplyToActivity(fill=message, text=message["text"]).send()
コード例 #7
0
ファイル: tasks.py プロジェクト: KimJoonHeeC/lovelybot
def echo_response(message):
    print(message)

    if message["type"] == "message":
        if "bitcoin" in message["text"] or "비트코인" in message[
                "text"] or "ethereum" in message["text"] or "이더리움" in message[
                    "text"]:
            r_bit = requests.get(
                "https://api.korbit.co.kr/v1/ticker?currency_pair=btc_krw")
            r_etc = requests.get(
                "https://api.korbit.co.kr/v1/ticker?currency_pair=etc_krw")
            r_eth = requests.get(
                "https://api.korbit.co.kr/v1/ticker?currency_pair=eth_krw")
            bitcoin_price = r_bit.json()["last"]
            eclassic_price = r_etc.json()["last"]
            ethe_price = r_eth.json()["last"]
            current_time = datetime.fromtimestamp(
                r_bit.json()['timestamp'] / 1000).strftime('%Y-%m-%d %H:%M:%S')
            msg = "at %s, \nbitcoin price is %s won. " \
                  "\nethereum classic price is %s won. \nethereum price is %s won." \
                  % (current_time, bitcoin_price, eclassic_price, ethe_price)
            print(msg)
            ReplyToActivity(fill=message, text=msg).send()

        elif "ㅇㅇ" in message["text"]:
            djn_reply = "그래그래 ㅇㅇ"
            ReplyToActivity(fill=message, text=djn_reply).send()

        elif "ㅠㅠ" in message["text"] or "ㅜㅜ" in message["text"]:
            yor_reply = "우쮸쮸쮸 ㅇㅇ..."
            ReplyToActivity(fill=message, text=yor_reply).send()

        else:
            data = {
                "documents": [{
                    "language": "en",
                    "id": "1",
                    "text": message["text"]
                }]
            }
            headers = {
                'Ocp-Apim-Subscription-Key':
                '4cfe6f744f1b486db3fa83d874bafdd9',
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            }

            r = requests.post(
                "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment",
                data=json.dumps(data),
                headers=headers)
            emo_score = r.json()["documents"][0]["score"]
            msg = "emotion score is %s\n" % emo_score

            if emo_score > 0.5:
                msg = msg + "You look happy!"

            elif emo_score == 0.5:
                msg = msg + "I'm not sure how you feel."

            else:
                msg = msg + "You look unhappy.."

            print(msg)
            ReplyToActivity(fill=message, text=msg).send()
コード例 #8
0
ファイル: tasks.py プロジェクト: arousselot/hellopyazure
def echo_response(message):
    if message["type"] == "message":
        # answer=ai.get_response(message["text"], message["from"]["name"],dbs)
        ReplyToActivity(fill=message, text="hello world!").send()
コード例 #9
0
ファイル: actions.py プロジェクト: mrklees/Escher
 def act(self, bot, message):
     ReplyToActivity(fill=message,
                     text=f"Please provide the {self.name}.  We're " +
                     f"expecting a {str(self.dtype)}").send()
コード例 #10
0
def response(message):
    if message["attachments"][0]["contentType"] == "image/jpeg":
        ReplyToActivity(fill=message, text=classify(message)).send()
コード例 #11
0
def respond_to_conversation_update(message):
    if message["type"] == "conversationUpdate":
        message_response = 'Have fun with the Microsoft Bot Framework'
        ReplyToActivity(fill=message,
                        text=message_response).send()
コード例 #12
0
def echo_test(message):
    if message["text"] == "Hallo":
        ReplyToActivity(fill=message, text='Hallo Noé').send()
コード例 #13
0
ファイル: tasks.py プロジェクト: yongjun823/lovelybot
def echo_response(message):
    if message["type"] == "message":
        key_list = list(message.keys())

        if key_list.count('attachments'):
            attach_data = message['attachments'][0]

            print(attach_data)
            ext_type = {'image/jpeg': '.jpg', 'image/png': '.png'}

            temp_file_name = datetime.datetime.now().strftime(
                '%Y-%m-%d-%H-%M-%S') + ext_type[attach_data['contentType']]

            urllib.request.urlretrieve(attach_data['contentUrl'],
                                       temp_file_name)

            # file size check
            if os.path.getsize(temp_file_name) >> 20 >= 2:
                os.remove('./' + temp_file_name)
                ReplyToActivity(fill=message,
                                text='파일이 너무 큽니다. 2MB 이하만 가능합니다.').send()
                return

            # naver celebrity
            # https://developers.naver.com/docs/clova/face/reference/#celebrity-응답예시
            client_id = "a1RZIb1p59TLbq3iu_un"
            client_secret = "yzvyDMQvAL"
            url = "https://openapi.naver.com/v1/vision/celebrity"
            files = {'image': open(temp_file_name, 'rb')}
            headers = {
                'X-Naver-Client-Id': client_id,
                'X-Naver-Client-Secret': client_secret
            }
            response = requests.post(url, files=files, headers=headers)
            rescode = response.status_code
            files.clear()

            os.remove('./' + temp_file_name)

            temp_str = ''

            if rescode == 200:
                print(response.text)
                faces = json.loads(response.text)['faces']

                if not len(faces):
                    temp_str = '해당하는 연예인을 찾을 수 없습니다.'

                for idx, face_data in enumerate(faces):
                    temp_str += str(
                        idx +
                        1) + ' 순위 : ' + face_data['celebrity']['value'] + '\n'

            else:
                temp_str = '통신 오류'

            ReplyToActivity(fill=message, text=temp_str).send()

        # bit coin price
        # https://apidocs.korbit.co.kr/ko/#최종-체결-가격
        if key_list.count('text'):
            if message['text'] == '비트 코인 시세':
                url = "https://api.korbit.co.kr/v1/ticker"

                response = requests.request("GET", url)

                jj = json.loads(response.text)

                time_s = datetime.datetime.fromtimestamp(
                    jj['timestamp'] // 1000).strftime('%Y-%m-%d %H:%M:%S')

                result_text = '최종 시간: %s\n 최종 가격: %s \n' % (time_s, jj['last'])
                print(result_text)

                ReplyToActivity(fill=message, text=result_text).send()
            else:
                r = message['text'] + ' @_@'
                ReplyToActivity(fill=message, text=r).send()
コード例 #14
0
ファイル: tasks2.py プロジェクト: robin521111/deeplearning
def asynchronous_response(message):
    if message["type"] == "message":
        if "asynchronous" in message['text']:
            ReplyToActivity(fill=message,
                            text='Asynchronous Test: {}'.format(
                                message["text"])).send()
コード例 #15
0
ファイル: tasks.py プロジェクト: anjyzplace/chatbot
def botresponse(message):
    print(message)
    if(message["type"] == "conversationUpdate"):
        if(message["membersAdded"][0]["name"] == "Bot"):
            print("")
        elif message["membersAdded"][0]["name"] != "Bot":
                name = message["from"]["name"]
                ReplyToActivity(fill=message,
                                text="Welcome, " + name).send()
                ReplyToActivity(fill=message,
                                text="I am LifeBot. I can give healthy recommendations.").send()
    elif(matcher(message["text"]) == True):
        user_id = message["from"]["id"]
        interest = message["text"]
        sententenceclass = sentenceClass(interest)
        storeInterestwithClass(user_id, "personal", sententenceclass, Trimmer(interest))
        ReplyToActivity(fill=message,
            text='Great, I have made a note of that.').send()
    elif message["text"] == "None":
        offset =3
        info = chathistory.DataStore()
        lastchats = info.get_lastnumberofchats(offset)
        intentId = lastchats[0]["_id"]
        print(intentId)
        print(lastchats)
        sentence = lastchats[0]["activity"]["text"]
        if(sentence == "None"):
            offset = offset + 2
            lastchats = info.get_lastnumberofchats(offset)
            print('Fetching {0} messages'.format(offset))
            print(lastchats)
            sentence = lastchats[0]["activity"]["text"]
        sententenceclass = sentenceClass(sentence)

        responder(sententenceclass, message)
    elif message["type"] == "message":
        botreply = sendResponse(message["text"])
        sententenceclass = sentenceClass(message["text"])
        input = message["text"]
        print('The input is {0}'.format(input))
        user_id = message["from"]["id"]
        if sententenceclass == "food":
            if(wordCounter(message["text"])>=3):
                if(suggestPersonal("personal",sententenceclass, user_id) != None):
                    jsonToPython = json.loads(suggestPersonal("personal",sententenceclass, user_id))
                    ReplyToActivity(fill=message,
                            text="Which of the following would you consider ?", inputHint="acceptingInput", suggestedActions=jsonToPython).send()
                else:
                    jsonToPython = json.loads(suggest('food'))
                    ReplyToActivity(fill=message,
                            text="Which of the following would you consider ?", inputHint="acceptingInput", suggestedActions=jsonToPython).send()        
            else:
                guide(sententenceclass, message)
        elif sententenceclass == "breakfast":
            if(wordCounter(message["text"])>=3):
                if(suggestPersonal("personal",sententenceclass, user_id)):
                    jsonToPython = json.loads(suggestPersonal("personal",sententenceclass, user_id))
                else:
                    jsonToPython = json.loads(foodTypesSuggest('breakfast'))
                ReplyToActivity(fill=message,
                            text="Which of the following would you consider ?", \
                            inputHint="acceptingInput", suggestedActions=jsonToPython).send()  
            else:
                guide(sententenceclass, message) 
        elif sententenceclass == "lunch":
            if(wordCounter(message["text"])>=3):
                jsonToPython = json.loads(foodTypesSuggest('lunch'))
                ReplyToActivity(fill=message,
                            text="Which of the following would you consider ?", inputHint="acceptingInput", suggestedActions=jsonToPython).send()  
            else:
                guide(sententenceclass, message) 
        elif sententenceclass == "dinner":
            if(wordCounter(message["text"])>=3):
                jsonToPython = json.loads(foodTypesSuggest('dinner'))
                ReplyToActivity(fill=message,
                            text="Which of the following would you consider ?", inputHint="acceptingInput", suggestedActions=jsonToPython).send()  
            else:
                guide(sententenceclass, message)                                 
        elif sententenceclass == "drink":
            if(wordCounter(message["text"])>=3):
                jsonToPython = json.loads(suggest('drinks'))
                ReplyToActivity(fill=message,
                            text="Which of the following would you consider ?", inputHint="acceptingInput", suggestedActions=jsonToPython).send()  
            else:
                guide(sententenceclass, message)                                                     
        elif sententenceclass == "exercise":
            if(wordCounter(message["text"])>=3):           
                jsonToPython = json.loads(suggest('exercise'))
                ReplyToActivity(fill=message,
                            text="Which of the following would you consider ?", inputHint="acceptingInput", suggestedActions=jsonToPython).send()
            else:
                guide(sententenceclass, message)                            
        elif sententenceclass == "blood-sugar":
            sentence = message["text"]
            if(wordCounter(sentence)>=3):
                if("status" in sentence or "profile" in sentence):
                    result_pre = lastPremealBloodResult("./app/blood_sugar_five.json")  
                    result_after = lastAfterMealBloodResult("./app/blood_sugar_five.json")   
                    status = profile(result_pre, result_after)
                    templateStatus = "Your last blood result is {0} mg/dL, which mean your status is {1} ".format(result_pre, status)                              
                    ReplyToActivity(fill=message,
                        text=templateStatus).send()
                elif("lastest" in sentence or "result" in sentence or "five" in sentence):                        
                    before = averageBloodSugarin5DaysBeforeMeal("./app/blood_sugar_five.json")
                    after = averageBloodSugarin5DaysAfterMeal("./app/blood_sugar_five.json")
                    templateBefore = "Your average pre meal blood sugar in the last 5 days is {0} mg/dL".format(before)
                    ReplyToActivity(fill=message,
                        text=templateBefore).send()                                           
                    templateAfter = "Your average post meal blood sugar in the last 5 days is {0} mg/dL".format(after)
                    ReplyToActivity(fill=message,
                        text=templateAfter).send()
                else:
                    before = averageBloodSugarin5DaysBeforeMeal("./app/blood_sugar_five.json")
                    after = averageBloodSugarin5DaysAfterMeal("./app/blood_sugar_five.json")                                          
                    template = "Your average blood sugar in the last 5 days is Fasting {0} mg/dL, random: {1} mg/dL ".format(before, after)
                    ReplyToActivity(fill=message,
                        text=template).send()                                 
        elif sententenceclass == "goodbye":
                name = message["from"]["name"]
                jsonToPython = None
                messagetosend = botreply + ", " + name
                ReplyToActivity(fill=message,
                            text=messagetosend, inputHint="acceptingInput", suggestedActions=jsonToPython).send()
        else:
                jsonToPython = None
                ReplyToActivity(fill=message,
                            text=botreply, inputHint="acceptingInput", suggestedActions=jsonToPython).send()
コード例 #16
0
    def respond(self, message):
        """Response Logic.

        This function implaments a goal-based response logic.  It is of fairly
        general design and should work for many situations.

        The logic maintains two stacks for goals and actions.  User intents are
        the primary way goals are added to the stack. Each goal corresponds
        to a set of a few actions.

        We will use LUIS to match intents with goals to add and entities to
        pull out the desired values when prompting the user.
        """
        if message["type"] == "message":
            # DEBUG logging of cureent goal/action stacks
            print(f"Goal Stack: {self.goal_stack}")
            print(f"Action Stack: {self.action_stack}")
            if self.prompting:
                print("Prompting is true, saving next message")
                # This is the highest priority channel, and is set
                # by certain actions which are trying to collect input
                self.current_action.process_response(self, message)
                # Then revert prompting to false
                self.prompting = False
                # Since the message has been used, we'll null the
                # text.  This reduces the noise sent to LUIS.
                message["text"] = ""
                # Finally, since it is likely that we want to do something
                # with the input, we'll trigger another pass through the
                # response logic
                self.respond(message)

            elif self.action_stack != []:
                print("Actions on stack, executing...")
                # If there are any actions on the stack, then we want
                # to resolve those before adding any new goals.
                while (self.action_stack != []) and (not self.prompting):
                    # We typically want to execute several actions in series
                    # without user input inbetween.  This logic processes
                    # actions until we encounter a prompt.  The prompt is
                    # then resolved before clearing the rest of the actions.
                    self.current_action = self.action_stack.pop()
                    print("The state of the current action stack is" +
                          f"{self.action_stack}")
                    # Process input in preprogrammed way
                    self.current_action.act(self, message)
                    # Set prompting state if current action needs it
                    self.prompting = self.current_action.prompt

            elif self.goal_stack != []:
                print("Goal on stack, exectuing...")
                # If we multiple goals loaded on the stack, this step will
                # pop the next.
                self.current_goal = self.goal_stack.pop()
                print(f"The current goal is {self.current_goal.name}")
                # Extract the actions from that goal and reverse the list
                queue_actions = self.current_goal.actions
                queue_actions.reverse()
                # Add the actions to the stack
                self.action_stack += queue_actions
                # Since we've just added actions, we'll want to get them
                # started without user input
                self.respond(message)

            else:
                # With no goal/action to process it is safe to assume that
                # we are trying to determine a new goal.
                print("No goals on stack, processing intent...")
                # Send message to LUIS to process intent
                res = self.make_request(message['text'])
                # Grab top scoring intent
                top_intent = res.get_top_intent().get_name()
                print(f"Intent is {top_intent}")

                if top_intent in self.goal_intents.keys():
                    # Intents in our dictionary have specified goals attached
                    # so we load that to the stack
                    self.goal_stack.append(self.goal_intents[top_intent])
                    # We'll now want to process the goal without user input
                    self.respond(message)

                elif top_intent in self.action_intents.keys():
                    self.action_intents[top_intent].act(self, message)

                else:
                    ReplyToActivity(fill=message,
                                    text="Sorry, but I either don't understand\
                                            what you want or I don't support  \
                                            that action yet").send()
コード例 #17
0
 def act(self, bot, message):
     # Always good to be cordial!
     ReplyToActivity(fill=message, text="Hi!! I'm a chatbot").send()