示例#1
0
    def __conditioning(cls, user_id, message_text, location=False):
        if user_id is None or message_text is None:
            ErrorHandler.error_logger("blood group or location, none value",
                                      user_id, "__temporary_conditioning")
        blood_group = ['AB+', 'AB-', 'A+', 'A-', 'B+', 'B-', 'O+', 'O-']
        message_text = message_text.split(" ")

        for words in message_text:
            if words in blood_group:
                Utility.print_fucking_stuff("User id " + str(user_id) +
                                            " and blood group " + str(words))
                # blood group.
                # This will open a new status code in the flow control for this user.
                MessageReply.quick_reply_text(
                    user_id,
                    ConversationCodes.CONVERSATION_ASK_BLD_GRP_AFFIRMATION +
                    str(words), [
                        ConversationCodes.CONVERSATION_YES,
                        ConversationCodes.CONVERSATION_NO
                    ], [
                        PostbackCodes.POSTBACK_BLOOD_GROUP_YES,
                        PostbackCodes.POSTBACK_BLOOD_GROUP_NO
                    ])
                ## Update function flow status here to Pending.
                return True
        return False
示例#2
0
 def __parse_user_id(cls, response_text):
     Utility.print_fucking_stuff("__parse_user_id")
     try:
         return str(response_text['sender']['id'])
     except ValueError as error:
         ErrorHandler.error_logger(
             "Error ::: " + str(error) + " || Response text ::: " +
             str(response_text), None, "__parse_user_id")
         return None
     except BaseException as error:
         ErrorHandler.error_logger(
             "Base Exception ::: " + str(error) + " || Response text ::: " +
             str(response_text), None, "__parse_user_id")
         return None
示例#3
0
    def quick_reply_text(cls, user_id, response_text, choices, postbacks):
        """
        general function to handle quick reply in text format.
        :param user_id: str
        :param response_text: str
        :param choices: list
        :param postbacks: list
        :return:
        """
        try:
            Utility().print_fucking_stuff("quick_reply_text -- > " +
                                          str(response_text))
            if MessageReply().__typing_on(user_id) != 0:
                ## On success, it will return 0.
                Utility().print_fucking_stuff(
                    "An error occurred inside __typing_on!")
                return
            quick_replies = []
            for i in range(0, 2):
                payload = {
                    TAG_CONTENT_TYPE_TEXT: 'text',
                    TAG_TITLE: choices[i],
                    TAG_PAYLOAD: postbacks[i]
                }
                quick_replies.append(payload)

            response_payload = MessageReply().__create_basic_recipient(user_id)
            message = {
                TAG_TEXT: str(response_text),
                TAG_QUICK_REPLIES: quick_replies
            }
            response_payload[TAG_MESSAGE] = message

            status = requests.post(REPLY_URL, json=response_payload)

            if status.status_code == 200:
                Utility().print_fucking_stuff(
                    "------------------------------\n" + str(status) +
                    "\n-------------------------------")
            else:
                ErrorHandler().error_logger(
                    "status code " + str(status.status_code) + " , payload is "
                    "" + str(response_payload), user_id,
                    "quick_reply_text - Message Reply")
        except BaseException as error:
            ErrorHandler().error_logger("Base exception : " + str(error),
                                        user_id,
                                        "quick_reply_text - Message Reply")
示例#4
0
    def __typing_on(cls, user_id):
        """
        private function, turns on typing function, sleep 3s before doing anything else.
        :param user_id:
        :return:
        """
        try:
            payload = MessageReply().__create_basic_recipient(user_id)
            payload[TAG_SENDER_ACTION] = TAG_TYPING_ON
            status = requests.post(REPLY_URL, json=payload)

            if status.status_code == 200:
                Utility().print_fucking_stuff(
                    "------------------------------\n" + str(status) +
                    "\n-------------------------------")
                time.sleep(1.5)
                return 0
            else:
                ErrorHandler().error_logger(
                    "status code " + str(status.status_code) + " , payload is "
                    "" + str(payload), user_id,
                    "echo_response - Message Reply")
                return -1
        except BaseException as error:
            ErrorHandler().error_logger("Base exception : " + str(error),
                                        user_id, "typing_on - Message Reply")
            return -1
示例#5
0
    def error_logger(cls,
                     error_message,
                     facebook_id,
                     error_position,
                     error_code=-1,
                     error_subcode=-1,
                     error_type=-1):
        Utility.print_fucking_stuff("$$$$$$$ Error occurred : " +
                                    str(error_message) + " | Error pos : " +
                                    str(error_position) +
                                    " | for facebook_id : " +
                                    str(facebook_id) + " $$$$$$$")

        request_query = ErrorLogger.objects.all()
        error_counter = request_query.count() + 1
        del request_query

        payload = {
            TAG_ERROR_INSTANCE_NO:
            str((binascii.hexlify(os.urandom(25))).decode("utf-8")),
            TAG_ERROR_COUNTER:
            error_counter,
            TAG_USER_ID:
            facebook_id,
            TAG_ERROR_MESSAGE:
            error_message,
            TAG_ERROR_CODE:
            error_code,
            TAG_ERROR_SUBCODE:
            error_subcode,
            TAG_ERROR_TYPE:
            error_type,
            TAG_ERROR_PLACE:
            error_position
        }
        serialized_data = LoggerSerializer(data=payload)
        if serialized_data.is_valid():
            serialized_data.save()
            if facebook_id is not None:
                ErrorHandler().__generic_error_reply(
                    facebook_id, Utility.__GENERIC_ERROR_MESSAGE__)
            return 1
        else:
            Utility().print_fucking_stuff(
                "$$$$$$$ error logging error! oh crap! " +
                str(serialized_data.error_messages) + " $$$$$$$")
            return -1
示例#6
0
    def echo_response(cls, user_id, response):
        """
        echo back the given message without any consequence
        :param user_id: account holder user id
        :param response: response sring that has to be sent
        :return: void
        """
        try:
            Utility().print_fucking_stuff("echo_response()-- > " +
                                          str(response))
            if MessageReply().__typing_on(user_id) != 0:
                ## On success, it will return 0.
                Utility().print_fucking_stuff(
                    "An error occurred inside __typing_on!")
                return

            payload = {
                TAG_RECIPIENT: {
                    TAG_ID: user_id
                },
                TAG_MESSAGE: {
                    TAG_TEXT: response
                }
            }
            status = requests.post(REPLY_URL, json=payload)

            if status.status_code == 200:
                Utility().print_fucking_stuff(
                    "------------------------------\n" + str(status) +
                    "\n-------------------------------")
            else:
                ErrorHandler().error_logger(
                    "status code " + str(status.status_code) + " , payload is "
                    "" + str(payload), user_id,
                    "echo_response - Message Reply")
        except BaseException as error:
            ErrorHandler().error_logger("Base exception : " + str(error),
                                        user_id,
                                        "echo_response - Message Reply")
示例#7
0
    def quick_reply_donate(cls, user_id):
        ## check user status and unique user first
        ## find missing information
        ## ask those.
        Utility.print_fucking_stuff("QUICK_REPLY_DONATE " + str(user_id))

        message_reply = MessageReply
        db_handler = DB_HANDLER

        message_reply.echo_response(user_id, "Great :) Lets get started!")
        user_status = db_handler.check_user_status(user_id)
        if user_status < 0:
            return HttpResponse(status=200)
        del user_status
        ## user is either fresh or have some missing information.
        missing_information_status = db_handler.check_user_information(user_id)

        if missing_information_status < 0:
            # error occurred there and it has already been reported.
            return None
        ## find the missing information
        if missing_information_status == 100:
            #missing blood group
            MessageReply.echo_response(
                user_id, "I'll need to register your blood group."
                " Can you tell me what is your blood group?")

            # A new status is opened for this user.
            DB_HANDLER.flow_controller_insert(
                user_id, ConversationCodes.CONVERSATION_BLOOD_GROUP_ASK_TAG, 1,
                ConversationCodes.CONVERSATION_BLOOD_GROUP_STATUS_OPENED)
        elif missing_information_status == 101:
            #missing location. GET THEM
            MessageReply.echo_response(user_id, "Register Location later.")
        elif missing_information_status == 200:
            ## TODO : all information complete. Do stuff here.
            Utility.print_fucking_stuff("All information completto")
        return None
示例#8
0
def facebook_message(incoming_message):
    for entry in incoming_message['entry']:
        if 'messaging' in entry:
            for message in entry['messaging']:
                if 'message' in message:
                    if 'is_echo' in message['message']:
                        Parser().is_echo(message)
                        return HttpResponse(status=200)
                    elif 'quick_reply' in message['message']:
                        Parser().quick_reply(message)
                        return HttpResponse(status=200)
                    else:
                        Parser().basic_reply(message)
                        return HttpResponse(status=200)
                elif 'delivery' in message:
                    Parser().delivery_result(message)
                    return HttpResponse(status=200)
                elif 'read' in message:
                    Parser().message_read(message)
                    return HttpResponse(status=200)
                elif 'postback' in message:
                    Parser().postback_response(message)
                    return HttpResponse(status=200)
                else:
                    Utility().print_fucking_stuff(
                        "Unknown handler box inside entry['messaging']")
                    Parser().unknown_handle(message)
                    return HttpResponse(status=200)
        elif 'standby' in entry:
            Parser().standby(str(entry))
            return HttpResponse(status=200)
        else:
            Utility().print_fucking_stuff("Unknown totally box")
            Parser().unknown_handle(str(entry))
            return HttpResponse(status=200)
    return HttpResponse(status=200)
示例#9
0
    def quick_reply(cls, message_data):
        Utility.print_fucking_stuff("Quick Reply box " + str(message_data))
        db_hanlder = DB_HANDLER()
        user_id = None
        try:
            user_id = Parser.__parse_user_id(message_data)
            if user_id is None:
                Utility.print_fucking_stuff(
                    "USER_ID came NONE. Parsing Error occurred! Parser.QUICK_REPLY"
                )
                return HttpResponse(status=200)

            if db_hanlder.unique_user_check(user_id):
                return_val = db_hanlder.user_table_insertion(user_id)
                Utility.print_fucking_stuff(
                    "return_value user table insertion " + str(return_val))

            if 'payload' in message_data['message']['quick_reply']:
                status = Utility.check_quick_reply_keys(
                    str(message_data['message']['quick_reply']['payload']))
                if status == 1:
                    # donor
                    Parser.quick_reply_donate(user_id)
                elif status == 2:
                    ## emergency
                    Parser.quick_reply_emergency_blood(user_id)

            ## NOTHING TO Parse anymore.
        except ValueError as error:
            ErrorHandler.error_logger("Error: " + str(error), user_id,
                                      "quick_reply")
        except BaseException as error:
            ErrorHandler.error_logger("Base exception Error: " + str(error),
                                      user_id, "quick_reply")
        finally:
            return HttpResponse(status=200)
示例#10
0
 def is_echo(cls, message_data):
     Utility.print_fucking_stuff("Echo Box")
     return HttpResponse(status=200)
示例#11
0
    def facebook_nlp(cls, user_id, message_data):
        """
        checks and parse facebook's nlp data, if more than 0.85 (except Location) it handles it here.
        :param user_id: account holder user id.
        :param message_data: nlp message data.
        :return: boolean
        """
        Utility.print_fucking_stuff("Facebook's NLP box")
        payload = [False, 0]
        message_reply = MessageReply()
        try:
            if 'bye' in message_data["nlp"]['entities']:
                bye_val = float(
                    message_data["nlp"]['entities']['bye'][0]['confidence'])
            else:
                bye_val = 0.0

            if 'thanks' in message_data["nlp"]['entities']:
                thanks_val = float(
                    message_data["nlp"]['entities']['thanks'][0]['confidence'])
            else:
                thanks_val = 0.0

            if 'greetings' in message_data["nlp"]['entities']:
                greetings_val = float(message_data["nlp"]['entities']
                                      ['greetings'][0]['confidence'])
            else:
                greetings_val = 0.0

            if 'location' in message_data["nlp"]['entities']:
                location_val = float(message_data["nlp"]['entities']
                                     ['location'][0]['confidence'])
            else:
                location_val = 0.0

            if bye_val > thanks_val and bye_val > greetings_val and bye_val > location_val:
                if bye_val >= 0.85:
                    ## Bye will cut all running processing for this user for a while.
                    message_reply.echo_response(user_id, "Bye :)")
                    payload[0] = True
                    payload[1] = 101
            elif thanks_val > bye_val and thanks_val > greetings_val and thanks_val > location_val:
                if thanks_val >= 0.85:
                    ## Thanks will do nothing.
                    message_reply.echo_response(user_id, "Thanks :)")
                    payload[0] = True
                    payload[1] = 102
            elif greetings_val > bye_val and greetings_val > thanks_val and greetings_val > location_val:
                if greetings_val >= 0.85:
                    message_reply.echo_response(user_id, "Hello :)")
                    payload[0] = True
                    payload[1] = 100
            else:
                pass  ## passing on location for now.
        except ValueError as error:
            Utility().print_fucking_stuff(str(error) + " Inside facebook_nlp")
            ErrorHandler().error_logger(str(error), user_id, "facebook_nlp")
        except BaseException as error:
            Utility().print_fucking_stuff(str(error) + " Inside facebook_nlp")
            ErrorHandler().error_logger(str(error), user_id, "facebook_nlp")
        finally:
            return payload
示例#12
0
    def basic_reply(cls, message_data):
        Utility.print_fucking_stuff("Basic Reply box")
        db_handler = DB_HANDLER()
        user_id = None
        try:
            # insert_queue(message_data)  # insert data to database.
            user_id = str(message_data['sender']['id'])
            return_val = db_handler.user_table_insertion(user_id)

            if return_val < 0:
                # An error occurred during user table insertion. System exit.
                return HttpResponse(status=200)
            else:
                ## all good. returnVal came 1.
                ### Find the user's current status here.
                user_status = db_handler.check_user_status(user_id)
                if user_status is None:
                    Utility.print_fucking_stuff("user status came null")
                    ErrorHandler.error_logger(
                        "user status is none, closing service!", user_id,
                        "basic_reply_if user_status is None:")
                    return HttpResponse(status=200)

            if 'text' not in message_data['message']:
                ## unknown type came like attachment
                ErrorHandler().error_logger(
                    "text not available --> " + str(message_data), user_id,
                    "basic_reply")
                return HttpResponse(status=200)

            if 'nlp' in message_data['message']:
                # handle nlp data function from here
                status = Parser().facebook_nlp(user_id,
                                               message_data['message'])
            else:
                status = [False, 0]

            if user_status is not None:
                if user_status == 100 and status[1] == 100:
                    MessageReply.quick_reply_text(
                        user_id, Utility.__INTRO_MESSAGE_QUICK_REPLY_FRESH__, [
                            Utility.__INTRO_OPTION_DONOR_QUICK_REPLY_FRESH__,
                            Utility.__INTRO_OPTION_PATIENT_QUICK_REPLY_FRESH__
                        ], Utility.get_postback_keys_fresh())
                    return HttpResponse(status=200)
                print("Current user id --> " + str(user_id) +
                      " result is --> " + str(user_status))

            #TODO: check the flow condition here for future references. Insert blood group where In Database?
            conditioning_status = Parser().__conditioning(
                user_id,
                str(message_data['message']['text']).upper())

            ## status object might be important. Its a list.
            # TODO --------------------------------------------------------------
            # TODO --------------------------------------------------------------
            # TODO -> this echo back reply is not necessary on future references.
            # TODO --------------------------------------------------------------
            # TODO --------------------------------------------------------------
            if not status[0] and not conditioning_status:
                ## Parse message for location, blood group and emergency blood needed from here
                MessageReply().echo_response(
                    user_id,
                    str(message_data['message']['text']).lower())
            return HttpResponse(status=200)
        except ValueError as error:
            Utility().print_fucking_stuff("Error occurred in basic reply " +
                                          str(error) + "\n" +
                                          "message data --> " +
                                          str(message_data))
            ErrorHandler().error_logger(str(error), user_id, "basic reply")
            return HttpResponse(status=200)
        except BaseException as error:
            Utility().print_fucking_stuff(
                "Broad exception handling (basic reply) " + str(error) + "\n" +
                "message data --> " + str(message_data))
            ErrorHandler().error_logger(
                "Broad exception handling " + str(error), user_id,
                "basic reply")
            return HttpResponse(status=200)
示例#13
0
 def standby(cls, entry):
     Utility.print_fucking_stuff("Standby box")
     return HttpResponse(status=200)
示例#14
0
 def postback_response(cls, message_data):
     Utility.print_fucking_stuff("Postback box")
     return HttpResponse(status=200)