Example #1
0
def is_data_complete(token,user_id):
    user = User.query.filter_by(username=user_id).first()
    if user.name == None:
        FB.show_typing(token, user_id, 'typing_on')
        intro = u"يبدو انك لم تستكمل بياناتك بعد، من فضلك استكملها لتساعدنا على تقديم افضل خدمة لك"
        FB.send_complete_data_button(token, user_id, intro, True)
        return True
    return False
def first_time_subscribe(user_id):
    offer1 = subscribe(user_id, 'daily')
    FB.send_message(app.config['PAT'], user_id, offer1)

    offer3 = "You can unsubscribe anytime in my Menu (next to the text input)"
    FB.send_message(app.config['PAT'], user_id, offer3)

    offer4 = "Here's your first daily update of HackerNews top stories :D"
    FB.send_message(app.config['PAT'], user_id, offer4)
    FB.show_typing(app.config['PAT'], user_id)

    stories = DB.get_daily_top_stories()
    FB.send_stories(app.config['PAT'], user_id, stories)
def send_daily_subscription():
	print "[Scheduled task] Send daily subscription"
	stories = DB.get_daily_top_stories()
	users = DB.get_subscribers_by_keyword('daily')
	
	try:
		for user_id in users:
			FB.send_message(config.PAT, user_id, "Here are today's top stories:")
			FB.send_stories(config.PAT, user_id, stories)

	except Exception, e:
		print(e)
		traceback.print_exc()
def handle_messages():
    payload = request.get_data()
    token = app.config['PAT']
    webhook_type = get_type_from_payload(payload)

    # Handle messages
    if webhook_type == 'postback':
        for sender_id, postback_payload in postback_events(payload):

            # Get user from DB
            user = DB.get_user(sender_id)
            response = None

            if postback_payload == 'HELP_PAYLOAD':
                handle_help(sender_id)

            elif postback_payload == 'GET_STARTED':
                handle_first_time_user(user)
                first_time_subscribe(sender_id)

            elif postback_payload == 'SUBSCRIBE_DAILY_PAYLOAD':
                response = subscribe(sender_id, 'daily')

            elif postback_payload == 'UNSUBSCRIBE_DAILY_PAYLOAD':
                response = unsubscribe(sender_id, 'daily')

            elif postback_payload[:15] == 'MORE_daily_top_':
                # Format: "MORE_%s_%s"%(story_type, offset)
                # Format: "MORE_daily_top_9"
                offset = int(postback_payload[15:])
                stories = DB.get_daily_stories()
                FB.send_stories(token, sender_id, stories, 'daily_top', offset)

            if response:
                FB.send_message(token, sender_id, response)

    elif webhook_type == 'message':
        for sender_id, message in messaging_events(payload):
            user = DB.get_user(sender_id)

            # Only process message in here
            if not message:
                return "ok"

            # Start processing valid requests
            try:
                returns = {}
                FB.show_typing(token, sender_id)
                thr = threading.Thread(target=processIncoming,
                                       args=(sender_id, message),
                                       kwargs={})
                thr.start()  # will run "processIncoming" asynchronously

            except Exception, e:
                print e
                traceback.print_exc()
                FB.send_message(app.config['PAT'], sender_id,
                                NLP.oneOf(NLP.error))
Example #5
0
def get_user(user_id):
    query = "SELECT * FROM users WHERE facebook_user_id=%s"
    args = (user_id, )
    try:
        conn = get_mysql_connection()
        cursor = conn.cursor()
        cursor.execute(query, args)

        row = cursor.fetchone()
        # Sample return (100, 1, u'21', u'2412', u'2', u'1', u'1', u'1', datetime.datetime(2017, 2, 10, 5, 21, 32), None)
        if row is None:
            user_fb = FB.get_user_fb(app.config['PAT'], user_id)
            create_user(user_id, user_fb)

        else:
            user_fb = {
                "facebook_user_id": row[1],
                "first_name": row[2],
                "last_name": row[3],
                "profile_pic": row[4],
                "locale": row[5],
                "timezone": row[6],
                "gender": row[7],
                "last_seen": row[8],  # datetime.strptime
                "created_at": row[9]
            }
        # Make this an object here --> user['first_name']
        return user_fb

    except Exception, e:
        print e
        traceback.print_exc()
def handle_help(user_id):
    intro = "I am your smart HackerNews bot"
    FB.send_message(app.config['PAT'], user_id, intro)

    offer2 = "You can Subscribe (in my Menu) to receive daily updates at 5PM (PST) - 8PM (EST)"
    FB.send_message(app.config['PAT'], user_id, offer2)

    offer3 = "Send me any text to search for it on HackerNews"
    FB.send_message(app.config['PAT'], user_id, offer3)

    offer4 = "Subscribing to a term will also be supported"
    FB.send_message(app.config['PAT'], user_id, offer4)
Example #7
0
def handle_messages():
    payload = request.get_data()

    # Handle messages
    for sender_id, message in messaging_events(payload):
        # Start processing valid requests
        try:
            response = processIncoming(sender_id, message)

            if response == 'postback':
                pass

            elif response is not None:
                FB.send_message(token, sender_id, response)

            else:
                FB.send_message(token, sender_id,
                                "Sorry I don't understand that")
        except Exception, e:
            print e
            traceback.print_exc()
Example #8
0
def quickReplyProcessing(user_id, quick_reply_payload):
    if SUGAR_TIMES_KEY in quick_reply_payload:
        FB.show_typing(token, user_id, 'typing_on')
        FB.send_message(token, user_id, 'Thanks :)')
        payload_id = quick_reply_payload.replace(SUGAR_TIMES_KEY, '')
        # add_new_record('bot_users', {user_id: {'sugar_times': payload_id}})
        update_record('bot_users', user_id,
                      {SUGAR_FIREBASE_KEY: payload_id
                       })  # use of update to be able to insert custom ids

    elif MEAL_TIMES_KEY in quick_reply_payload:
        FB.show_typing(token, user_id, 'typing_on')
        FB.send_message(token, user_id, 'Thanks :)')
        payload_id = quick_reply_payload.replace(MEAL_TIMES_KEY, '')
        # add_new_record('bot_users', {user_id: {'sugar_times': payload_id}})
        update_record('bot_users', user_id,
                      {MEAL_FIREBASE_KEY: payload_id
                       })  # use of update to be able to insert custom ids

    return 'postback'
def handle_first_time_user(user):
    user_id = user['facebook_user_id']
    token = app.config['PAT']

    hi = "%s %s, nice to meet you :)" % (NLP.sayHiTimeZone(user),
                                         user['first_name'])
    FB.send_message(token, user_id, hi)

    FB.send_picture(
        app.config['PAT'], user_id,
        'https://monosnap.com/file/I6WEAs2xvpZ5qTNmVauNguEzcaRrnI.png')

    handle_help(user_id)
    FB.send_message(app.config['PAT'], user_id,
                    "Next time just tell me \"help\" to view this again :D")
def send_daily_subscription():
    print "\n==========="
    print "[Scheduled task] Sending daily subscription"
    # ctx = app.test_request_context('https://2c85143c.ngrok.io/')
    ctx = app.test_request_context('https://hacker-news-bot.herokuapp.com/')
    ctx.push()

    top_stories = DB.get_daily_stories("top")
    best_stories = DB.get_daily_stories("best")
    users = DB.get_subscribers_by_keyword('daily')

    try:
        for user_id in users:
            FB.send_message(app.config['PAT'], user_id,
                            "Here are today's top stories:")
            FB.send_stories(app.config['PAT'], user_id, top_stories)
            FB.send_message(app.config['PAT'], user_id,
                            "Here are today's best stories:")
            FB.send_stories(app.config['PAT'], user_id, best_stories)

    except Exception, e:
        print(e)
        traceback.print_exc()
def processIncoming(user_id, message):
    token = app.config['PAT']
    if message['type'] == 'text':
        message_text = message['data']
        if message_text.lower() == "news":
            FB.send_message(token, user_id,
                            "Just a sec, I'm fetching today's stories :D")
            FB.show_typing(token, user_id)
            stories = DB.get_daily_top_stories()
            FB.send_stories(token, user_id, stories)

        else:
            keyword = message_text.lower()
            FB.show_typing(token, user_id, 'typing_off')
            FB.send_message(
                token, user_id,
                "Just a sec, I'm looking \"%s\" up :D" % (message_text))
            FB.show_typing(token, user_id)
            stories = DB.get_stories_from_search(keyword, "top")  # top results

            if len(stories):
                FB.send_message(
                    token, user_id,
                    "Top stories related to \"%s\":" % (message_text))
                FB.send_stories(token, user_id, stories, keyword)

            stories_recent = DB.get_stories_from_search(
                keyword, "recent")  # recent-first results
            if len(stories_recent):
                FB.send_message(
                    token, user_id,
                    "Most recent stories related to \"%s\":" % (message_text))
                FB.send_stories(token, user_id, stories_recent, keyword)
            else:
                error = "Sorry, I can't find any result on HN for that :("
                FB.send_message(token, user_id, error)

    # ==/ END Text message type =====================================================

    # Location message type =========================================================
    elif message['type'] == 'location':
        response = "I've received location (%s,%s) (y)" % (message['data'][0],
                                                           message['data'][1])
        FB.send_message(token, user_id, response)

    # ==/ END Location message type ==================================================

    # Audio message type =========================================================
    elif message['type'] == 'audio':
        audNO_url = message['data']
        response = "I've received your voice message"  #%s"%(audio_url)
        FB.send_message(token, user_id, response)

    # ==/ End Audio message type ====================================================

    # Unrecognizable incoming, remove context and reset all data to start afresh
    else:
        error = "*scratch my head*"
        FB.send_message(token, user_id, error)
Example #12
0
def payloadProcessing(user_id, message_payload):
    if message_payload == 'Get_Started_Button':
        FBuser = FB.get_user_fb(token, user_id)
        msg = u" مرحبا بك يا "
        FB.send_message(token, user_id, FBuser.get('first_name') + msg)
        FB.show_typing(token, user_id, 'typing_on')
        intro = u"تعرف على ما يقدمه مظبوط من القائمه"
        FB.send_message(token, user_id, intro)

    elif message_payload == MENUE_QUESTION:
        FB.show_typing(token, user_id, 'typing_on')
        intro = u"يسعدنى الاجابه على اسئلتك :D تفضل بالسؤال"
        FB.send_message(token, user_id, intro)

    elif message_payload == MENUE_SUGAR:
        FB.show_typing(token, user_id, 'typing_on')
        intro = u"من فضلك ادخل قياس السكر"
        FB.send_message(token, user_id, intro)

    elif message_payload == MENUE_MEAL:
        FB.show_typing(token, user_id, 'typing_on')
        FB.send_meal_quick_replies(token, user_id)

    return 'postback'
Example #13
0
def completeData(user_id):
    if request.method == 'GET':
        MyData = request.args['mine']
        print MyData
        if MyData == 'True':
            user = User.query.filter_by(username=user_id).first()
            return render_template('complete-data.html',user_id=user_id,name=user.name)
        elif MyData == 'False':
            return render_template('complete-data.html', user_id='', name='')
    elif request.method == 'POST':
        print request.form
        if request.form['id'] != '':
            user = User.query.filter_by(username=request.form['id']).first()
            user.name = request.form['name']
            user_exist = User.query.filter_by(email=request.form['email']).first()
            if user_exist is not None and user_exist.username is not None:
                flash(u'هذا البريد الالكتروني تم استخدامه من قبل!!', 'error')
                return render_template('complete-data.html', user_id=user_id, name=user.name)
            elif user_exist is not None and user_exist.username is None:
                if user_exist.phone != request.form['phone']:
                    flash(u'هذا البريد الالكتروني تم استخدامه من قبل!!', 'error')
                    flash(u'هذا الرقم تم استخدامه من قبل!!', 'error')
                    return render_template('complete-data.html', user_id=user_id, name=user.name)
                elif user_exist.phone == request.form['phone']:
                    user.name = request.form['name']
                    user.email = request.form['email']
                    user.phone = request.form['phone']
                    user.age = request.form['age']
                    user.location = request.form['location']
                    db.session.delete(user_exist)
                    db.session.commit()
                    print 'useer2 ' + str(user_id)
                    FB.show_typing(token, user_id, 'typing_on')
                    FB.send_message(token, user_id, u"تم تسجيل بياناتك بنجاح")
                    FB.show_typing(token, user_id, 'typing_on')
                    FB.send_where_to_go_quick_replies(token, user_id, u"من فضلك اختر الى اين تريد الذهاب")
                    return u'تم التسجيل بنجاح يمكنك الأن اغلاق هذه الصفحة'
            user.email = request.form['email']
            user_exist = User.query.filter_by(phone=request.form['phone']).first()
            if user_exist is not None:
                flash(u'هذا الرقم تم استخدامه من قبل!!', 'error')
                return render_template('complete-data.html', user_id=user_id, name=user.name)
            user.phone = request.form['phone']
            user.age = request.form['age']
            user.location = request.form['location']
            db.session.commit()
            print 'useer1 '+ str(user_id)
            FB.show_typing(token, user_id, 'typing_on')
            FB.send_message(token,user_id,u"تم تسجيل البيانات بنجاح")
            FB.show_typing(token, user_id, 'typing_on')
            FB.send_where_to_go_quick_replies(token,user_id,u"من فضلك اختر الى اين تريد الذهاب")
            return u'تم التسجيل بنجاح يمكنك الأن اغلاق هذه الصفحة'
        elif request.form['id'] == '':
            user_exist = User.query.filter_by(email=request.form['email']).first()
            print user_exist
            if user_exist is not None:
                print user_exist.email
                flash(u'هذا البريد الالكتروني تم استخدامه من قبل!!', 'error')
                return render_template('complete-data.html', user_id='', name='')
            user_exist = User.query.filter_by(phone=request.form['phone']).first()
            if user_exist is not None:
                flash(u'هذا الرقم تم استخدامه من قبل!!', 'error')
                return render_template('complete-data.html', user_id='', name='')
            user = User(request.form['name'],None,request.form['email'],request.form['phone'],request.form['age'],request.form['location'])
            db.session.add(user)
            db.session.commit()
            print 'useer3 ' + str(user_id)
            FB.show_typing(token, user_id, 'typing_on')
            FB.send_message(token, user_id, u"تم تسجيل البيانات بنجاح")
            FB.show_typing(token, user_id, 'typing_on')
            FB.send_where_to_go_quick_replies(token, user_id, u"من فضلك اختر الى اين تريد الذهاب")
            return u'تم التسجيل بنجاح يمكنك الأن اغلاق هذه الصفحة'
Example #14
0
def quickReplyProcessing(user_id,quick_reply_payload):

    if quick_reply_payload == 'Complete_Person_Data_Request':
        FB.show_typing(token, user_id, 'typing_on')
        intro = u"من فضلك ادخل بيانات هذا الشخص لتساعدنا على تقديم افضل خدمة"
        FB.send_complete_data_button(token, user_id, intro,False)
    elif quick_reply_payload == "Choose_Who_To_Diagnose":
        FB.show_typing(token, user_id, 'typing_on')
        FB.send_whose_diagnoses(token, user_id, u"هل هذا التشخيص لك ام لشخص اخر ؟")
    elif quick_reply_payload.__contains__("Show_Parts_"):
        list_part_number = int(quick_reply_payload.replace('Show_Parts_', ''))
        parts = Part.query.all()
        parts_dict, num_of_iterates = parts_slicer(parts)
        parts_list = parts_dict['part_list_'+str(list_part_number)]
        # FB.show_typing(token, user_id, 'typing_on')
        # FB.send_message(token,user_id,u"من فضلك اختر العضو الذى تشكو منه")
        FB.show_typing(token, user_id, 'typing_on')
        FB.send_body_parts(token, user_id,parts_list)
        if list_part_number < num_of_iterates:
            FB.show_typing(token, user_id, 'typing_on')
            FB.send_more_body_parts_quick_replies(token, user_id,u"من فضلك اختر العضو الذى تشكو منه",list_part_number+1)
    elif quick_reply_payload.__contains__('body_part_'):
        pass
        
        # body_part = int(quick_reply_payload.replace('body_part_',''))
        # symptoms = Symptom.query.filter_by(part_id=body_part).all()
        # symptoms_dict, num_of_iterates = symptoms_slicer(symptoms)
        # symptoms_list = symptoms_dict['symptom_list_0']
        # FB.show_typing(token, user_id, 'typing_on')
        # if num_of_iterates > 0:
        #     FB.send_symptoms(token, user_id, symptoms_list,1)
        # else:
        #     FB.send_symptoms(token, user_id, symptoms_list,0)

    elif quick_reply_payload.__contains__('_Q&A_'):
        question_id_and_route = quick_reply_payload.split('_Q&A_')
        # if question_id_and_route[0] == '':
        #     q = Question.query.filter_by(parent_id=None).filter_by(route=int(question_id_and_route[1])).first()
        #     if q is not None:
        #         if len(q.childs) == 2:
        #             FB.show_typing(token, user_id, 'typing_on')
        #             FB.send_question_answer_quick_replies(token, user_id, q.id, q.question,2)
        #         elif len(q.childs) == 1:
        #             FB.show_typing(token, user_id, 'typing_on')
        #             FB.send_question_answer_quick_replies(token, user_id, q.id, q.question,q.childs[0].route)
        #         else:
        #             FB.send_message(token, user_id, q.question)
        # else:
        q = Question.query.filter_by(parent_id=question_id_and_route[0]).filter_by(route=int(question_id_and_route[1])).first()
        if q is not None:
            if len(q.childs) == 2:
                FB.show_typing(token, user_id, 'typing_on')
                FB.send_question_answer_quick_replies(token, user_id, q.id, q.question,2)
            elif len(q.childs) == 1:
                FB.show_typing(token, user_id, 'typing_on')
                FB.send_question_answer_quick_replies(token, user_id, q.id, q.question,q.childs[0].route)
            else:
                FB.send_message(token, user_id, q.question)

    return 'postback'
Example #15
0
def payloadProcessing(user_id,message_payload):
    print 'user_id is '+ str(user_id)
    if message_payload == 'Get_Started_Button':
        FBuser = FB.get_user_fb(token, user_id)
        if User.query.filter_by(username=user_id).first() is None:
            user = User(str(FBuser.get('first_name'))+' '+str(FBuser.get('last_name')),user_id,None,None,None,None)
            db.session.add(user)
            db.session.commit()
        msg = u" مرحبا بك يا "
        FB.send_message(token,user_id,FBuser.get('first_name') + msg)
        FB.show_typing(token,user_id,'typing_on')
        intro = u"يمكنك الأن استشارة الف سلامة بوت و ادخال الأعراض التى تشعر بها لتعرف حالتك و تطمئن على صحتك فى اسرع وقت"
        FB.send_message(token, user_id,intro)
        # FB.show_typing(token, user_id, 'typing_on')
        # intro = u"يبدو انك لم تستكمل بياناتك بعد، من فضلك استكملها لتساعدنا على تقديم افضل خدمة لك"
        # FB.send_complete_data_button(token, user_id, intro,True)
        is_data_complete(token, user_id)
    elif message_payload == "Help":
        FB.show_typing(token, user_id, 'typing_on')
        intro = u"يمكنك الأن استشارة الف سلامة بوت و ادخال الأعراض التى تشعر بها لتعرف حالتك و تطمئن على صحتك فى اسرع وقت"
        FB.send_message(token, user_id, intro)
        FB.show_typing(token, user_id, 'typing_on')
        FB.send_where_to_go_quick_replies(token, user_id, u"من فضلك اختر الى اين تريد الذهاب")
    elif message_payload == "Choose_Who_To_Diagnose":
        if is_data_complete(token,user_id) == False:
            FB.show_typing(token, user_id, 'typing_on')
            FB.send_whose_diagnoses(token, user_id, u"هل هذا التشخيص لك ام لشخص اخر ؟")
    elif message_payload.__contains__('Part_Id_'):
        body_part = int(message_payload.replace('Part_Id_', ''))
        symptoms = Symptom.query.filter_by(part_id=body_part).all()
        symptoms_dict, num_of_iterates = symptoms_slicer(symptoms)
        symptoms_list = symptoms_dict['symptom_list_0']
        FB.show_typing(token, user_id, 'typing_on')
        if num_of_iterates > 0:
            FB.send_symptoms(token, user_id, symptoms_list, 1,body_part)
        else:
            FB.send_symptoms(token, user_id, symptoms_list, 0,body_part)

    elif message_payload.__contains__('_More_Symptoms_'):
        part_id_and_symptom_num = message_payload.split('_More_Symptoms_')
        part_id = int(part_id_and_symptom_num[0])
        symptom_num = int(part_id_and_symptom_num[1])
        symptoms = Symptom.query.filter_by(part_id=part_id).all()
        symptoms_dict, num_of_iterates = symptoms_slicer(symptoms)
        symptoms_list = symptoms_dict['symptom_list_' + str(symptom_num)]
        FB.show_typing(token, user_id, 'typing_on')
        if num_of_iterates < (symptom_num+1):
            FB.send_more_symptoms(token, user_id, symptoms_list,symptom_num+1, part_id)
        else:
            FB.send_more_symptoms(token, user_id, symptoms_list, 0, part_id)


    elif message_payload.__contains__('_Q&A_'):
        question_id_and_route = message_payload.split('_Q&A_')
        # if question_id_and_route[0] == '':
        q = Question.query.filter_by(parent_id=None).filter_by(route=int(question_id_and_route[1])).first()
        if q is not None:
            if len(q.childs) == 2:
                FB.show_typing(token, user_id, 'typing_on')
                FB.send_question_answer_quick_replies(token, user_id, q.id, q.question,2)
            elif len(q.childs) == 1:
                FB.show_typing(token, user_id, 'typing_on')
                FB.send_question_answer_quick_replies(token, user_id, q.id, q.question,q.childs[0].route)
            else:
                FB.send_message(token, user_id, q.question)
        else:
        #     q = Question.query.filter_by(parent_id=question_id_and_route[0]).filter_by(route=int(question_id_and_route[1])).first()
        #     if q is not None:
        #         FB.show_typing(token, user_id, 'typing_on')
        #         FB.send_question_answer_quick_replies(token, user_id, q.id, q.question)
            q = Question.query.filter_by(parent_id=question_id_and_route[0]).filter_by(route=int(question_id_and_route[1])).first()
            if q is not None:
                if len(q.childs) == 2:
                    FB.show_typing(token, user_id, 'typing_on')
                    FB.send_question_answer_quick_replies(token, user_id, q.id, q.question, 2)
                elif len(q.childs) == 1:
                    FB.show_typing(token, user_id, 'typing_on')
                    FB.send_question_answer_quick_replies(token, user_id, q.id, q.question, q.childs[0].route)
                else:
                    FB.send_message(token, user_id, q.question)

    elif message_payload == 'Complete_Data':
        print 'من فضلك اختر شيئاً من القائمة'
        return 'من فضلك اختر شيئاً من القائمة'

    return 'postback'