Пример #1
0
def update_db(*date_from, **kwargs):
    """Updates the sms in the database starting from the date_from specified (at time midnight)
    no param = updates the sms feedback in database with all message entries
    analyze feedback when sms is sent

    Args:
        date_from (Date): a specified date, where we update db with sms sent after this date
        update_from (str): an optional argument. This should be "test" if messages are not coming from
        twilio, but from the test_fb_data file

    Returns:
        res(int): 1 on success. 0 on error

    Throws:
        SystemError: When the Twilio Client cannot be started. Possibly invalid account_sid or
        auth_token
    """

    if (kwargs):
        if(kwargs["update_from"]):
            if(kwargs['update_from'] == "test"):
                if date_from == ():
                    messages = test_sms_data(5, datetime(2016, 3, 25))
                else:
                    date_from = date_from[0]
                    if (date_from > datetime.now()):
                        return 0
                    else:
                        messages = test_sms_data(5, date_from)
                messages = test_sms_data(5, datetime(2016, 3, 25))
            elif(kwargs['update_from'] == "autogen"):
                if date_from == ():
                    messages = auto_generate_sms_data()
                else:
                    date_from = date_from[0]
                    if (date_from > datetime.now()):
                        return 0
                    else:
                        messages = auto_generate_sms_data(date_from=date_from)
            else:
                return 0
        else:
            return 0
    else:
        try:
            client = Client(account_sid,auth_token)
            messages = client.messages.list(to=restaurant_phone_number)
            process_incoming_sms()
            if date_from == ():
                messages = client.messages.list(to=restaurant_phone_number) # this may have a long random string first
            else:
                date_from = date_from[0]
                if (date_from > datetime.now()):
                    #raise ValueError
                    return 0
                messages = client.messages.list(date_sent=date_from,to=restaurant_phone_number)
        except:
            if date_from==():
                messages = auto_generate_sms_data()
            else:
                date_from = date_from[0]
                if (date_from > datetime.now()):
                    return 0
                else:
                    messages = auto_generate_sms_data(date_from=date_from)
            #raise SystemError
    for message in messages:
        try:
            sms = Sms.get(message.sid == Sms.sid)
            if (sms.invalid_field == True):
                #pass
                print('deleting ' + sms.body)
                delete_twilio_feedback(sms.sid)
            else:
                pass
        except:
            try:
                if message.date_sent != None:
                    date_tmp = message.date_sent - timedelta(hours=4)
                    sms_str = date_tmp.strftime("%Y-%m-%d %H:%M:%S")
                    date_tmp= datetime.strptime(sms_str, "%Y-%m-%d %H:%M:%S")
                else:
                    date_tmp = None
                sms_tmp = Sms(sid=message.sid,
                    submission_time=date_tmp,
                    body=message.body,
                    phone_num=message.from_,
                    )
                res2 = feedback_analysis(sms_tmp.body)
                sms_tmp.pos_flag = res2[0]
                sms_tmp.neg_flag = res2[1]
                sms_tmp.exception_flag = res2[2]
                sms_tmp.food_flag = res2[3]
                sms_tmp.service_flag = res2[4]
                sms_tmp.invalid_field = False
                try:
                    err = sms_tmp.save()
                except IntegrityError:
                    pass
            except IntegrityError:
                err = 0
                #print("Duplicate Sms Entry " + sms_tmp.body)
    return 1
Пример #2
0
def process_incoming_sms(*one):
    """Updates SMS table in database with the incoming SMS. Checks for the unique key to invalidate
    SMS or keep it. 
    
    Only for processing SMS in real time.

    - Precondition: A Twilio POST request is received.

    TODO: Fix error with twilio, where the most recent message does not have a submission timep

    Args:
        *one(int): optional argument

    Returns:
        res(int): 1 on success. 0 on error

    Throws:
        SystemError: When the Twilio Client cannot be started. Possibly invalid account_sid or
        auth_token
    """
    tabss = Tabs.select()
    valid_keys = []
    for tab in tabss:
        key = tab.fb_key
        if key == "~~~~~~~~~~":
            continue
        else:
            valid_keys.append(key)
    try:
        client = Client(account_sid,auth_token)
        messages = client.messages.list(to=restaurant_phone_number)
    except:
        raise SystemError

    if (one):
        messages = client.messages.list(to=restaurant_phone_number)
        message = messages[0] # get the first message
        message_key = []
        for key in valid_keys:
            if key in message.body[:len(key)]:
                new_body = message.body.replace(key,'')
                #remoev key
                tab = Tabs.update(fb_key="~~~~~~~~~~").where(Tabs.fb_key == key)
                message_key.append(key)

        if (message_key):
            #i can use the date time as now because feedback comes in immediately here
            sms_tmp = Sms(
                sid=message.sid,
                submission_time=datetime.now(),
                body=new_body,
                phone_num=message.from_)
            res2 = feedback_analysis(sms_tmp.body)
            sms_tmp.pos_flag = res2[0]
            sms_tmp.neg_flag = res2[1]
            sms_tmp.exception_flag = res2[2]
            sms_tmp.food_flag = res2[3]
            sms_tmp.service_flag = res2[4]
            sms_tmp.invalid_field = False
            try:
                err = sms_tmp.save()
            except IntegrityError:
                pass
        else:                
            try:
                i = message.body.index(' ')
            except ValueError:
                i = 7
                pass
            if (one):
                non_accept = "Your unique key {" + message.body[:i] + "} is not valid"
                client.messages.create(
                    to=message.from_,
                    from_=restaurant_phone_number,
                    body=non_accept,)
            
            sms_tmp = Sms(
                sid=message.sid,
                submission_time=datetime.now(),
                body=message.body,
                phone_num=message.from_)
            sms_tmp.invalid_field = True
            try:
                err = sms_tmp.save()
            except IntegrityError:
                pass
            #delete_twilio_feedback(message.sid)
    else:
        messages = client.messages.list(to=restaurant_phone_number, date_sent=datetime.today())
        for message in messages:
            message_key = []
            for key in valid_keys:
                if key in message.body[:len(key)]:
                    new_body = message.body.replace(key,'')
                    tab = Tabs.select().where(Tabs.fb_key == key)
                    tab.fb_key = "~~~~~~~~~~"
                    message_key.append(key)

            if (message_key):
                #i can use the date time as now because feedback comes in immediately here
                sms_tmp = Sms(
                    sid=message.sid,
                    submission_time=datetime.now(),
                    body=new_body,
                    phone_num=message.from_
                    )
                res2 = feedback_analysis(sms_tmp.body)
                sms_tmp.pos_flag = res2[0]
                sms_tmp.neg_flag = res2[1]
                sms_tmp.exception_flag = res2[2]
                sms_tmp.food_flag = res2[3]
                sms_tmp.service_flag = res2[4]
                sms_tmp.invalid_field = False
                try:
                    err = sms_tmp.save()
                except IntegrityError:
                    pass
            else:                
                try:
                    i = message.body.index(' ')
                except ValueError:
                    i = 7
                    pass
                if (one):
                    non_accept = "Your unique key {" + message.body[:i] + "} is not valid"
                    client.messages.create(
                        to=message.from_,
                        from_=restaurant_phone_number,
                        body=non_accept,)
                
                sms_tmp = Sms(
                    sid=message.sid,
                    submission_time=datetime.now(),
                    body=message.body,
                    phone_num=message.from_,
                    invalid_field=True
                    )
                try:
                    err = sms_tmp.save()
                except IntegrityError:
                    pass
                #delete_twilio_feedback(message.sid)
    return 1