Ejemplo n.º 1
0
async def quick_replies(sender_id, headers, params, state, **kwargs):
    print("quick_replies---------------------------")
    db = orm.SessionLocal()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
    print(user.state_id, 'inner------')
    sub_states = db.query(
        orm.State).filter(orm.State.parent_id == user.state_id).all()
    if sub_states:
        data = {
            "recipient": {
                "id": user.fb_id
            },
            "messaging_type": "RESPONSE",
            "message": {
                "text":
                state.prompt or state.label,
                "quick_replies": [{
                    "content_type": "text",
                    "title": sub_state.label,
                    "payload": sub_state.name,
                } for sub_state in sub_states]
            }
        }
        db.close()
        requests.post('https://graph.facebook.com/v10.0/me/messages',
                      headers=headers,
                      params=params,
                      json=data)
Ejemplo n.º 2
0
async def is_select_user_identify(sender_id, headers, params, **kwargs):
    db = orm.SessionLocal()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()

    data = {
        "recipient": {
            "id": user.fb_id
        },
        "messaging_type": "RESPONSE",
        "message": {
            "text":
            "您的身份是?",
            "quick_replies": [{
                "content_type": "text",
                "title": "教職員",
                "payload": "EMPLOYEE",
            }, {
                "content_type": "text",
                "title": "學生",
                "payload": "STUDENT",
            }]
        }
    }
    requests.post('https://graph.facebook.com/v10.0/me/messages',
                  headers=headers,
                  params=params,
                  json=data)

    state = db.query(
        orm.State).filter(orm.State.name == 'USER_IDENTIFY').one_or_none()
    user.state_id = state.id
    db.add(user)
    db.commit()
Ejemplo n.º 3
0
async def show_phone(sender_id, headers, params, **kwargs):
    print("called---------------------------------")
    db = orm.SessionLocal()
    contact = db.query(
        orm.Contact).filter(orm.Contact.fb_id == sender_id).order_by(
            orm.Contact.id.desc()).first()
    phone = contact.contact

    phone_result = phone
    if len(phone) > 10:
        phone_result = phone[-9:]
        phone_result.append({
            "title":
            "沒有找到你想要的嗎?",
            "image_url":
            "https://i.imgur.com/DjboxZ7.jpeg",
            "buttons": [{
                "type": "postback",
                "title": "點我看更多",
                "payload": "MORE_CONTACT"
            }]
        })
        contact.contact = phone[:len(phone) - 9]
        db.add(contact)
        db.commit()
    else:
        contact.contact = []

    if contact.contact:
        user = db.query(
            orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
        state = db.query(orm.State).filter(
            orm.State.name == "REAL_NAME_SEARCH").one_or_none()
        user.state_id = state.id
        db.add(user)
        db.commit()

    data = {
        "recipient": {
            "id": sender_id
        },
        "message": {
            "attachment": {
                "type": "template",
                "payload": {
                    "template_type": "generic",
                    "elements": phone_result,
                }
            }
        }
    }

    db.close()

    requests.post('https://graph.facebook.com/v2.6/me/messages',
                  headers=headers,
                  params=params,
                  json=data)
Ejemplo n.º 4
0
async def user_identify(sender_id, headers, params, name, **kwargs):
    db = orm.SessionLocal()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
    role = db.query(orm.Role).filter(orm.Role.name == name).one_or_none()
    user.role_id = role.id
    db.add(user)
    db.commit()

    await create_formated_activities(sender_id, headers, params)
Ejemplo n.º 5
0
def schedule_user_activity():
    result_activity = []
    db = orm.SessionLocal()

    users = db.query(orm.User).all()
    items = db.query(orm.Activity).all()

    for user in users:
        print("fb_id: ", user.fb_id)
        print("subcribed: ", user.subscribed)
        if user.subscribed:
            role = db.query(
                orm.Role).filter(orm.Role.id == user.role_id).one_or_none()

            for item in items:
                identify = {'STUDENT': '學生', 'EMPLOYEE': '教職'}.get(role.name)
                if identify in item.apply_qualification_list:
                    if item.apply_start_date == date.today():
                        loop = asyncio.new_event_loop()
                        asyncio.set_event_loop(loop)
                        coroutine = object_as_dict(item)
                        activity = loop.run_until_complete(coroutine)

                        activity_id = activity['activity_id']
                        activity_name = activity['activity_name']
                        start_date = activity['post_start_time'].date()
                        start_time = activity['activity_period_list'][0][
                            'ActivityStartTime']
                        start_time = start_time.split('T')[1]
                        start_time = start_time[:5]
                        end_date = activity['post_end_time'].date()
                        end_time = activity['activity_period_list'][0][
                            'ActivityEndTime']
                        end_time = end_time.split('T')[1]
                        end_time = end_time[:5]
                        location = activity['activity_period_list'][0][
                            'Location']

                        text = f"{start_date} {start_time}-{end_date} {end_time}\n活動地點:{location}"
                        url = f"https://signupactivity.ntub.edu.tw/activity/activityDetail/{activity_id}"

                        result_activity.append({
                            "title":
                            f"{activity_name}",
                            "image_url":
                            "https://i.imgur.com/QAcuOst.jpeg",
                            "subtitle":
                            text,
                            "buttons": [{
                                "type": "web_url",
                                "title": "我要報名",
                                "url": url
                            }]
                        })
        print(result_activity)
        result_activity.clear()
        db.close()
Ejemplo n.º 6
0
async def create_formated_activities(sender_id, headers, params, **kwargs):
    activities = []
    db = orm.SessionLocal()
    items = db.query(orm.Activity).all()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()

    if not user.role_id:
        await is_select_user_identify(sender_id, headers, params)
        return

    role = db.query(orm.Role).filter(orm.Role.id == user.role_id).one_or_none()

    for item in items:
        print("TYPE", role.name, type(item), item.apply_qualification_list)
        identify = {'STUDENT': '學生', 'EMPLOYEE': '教職員'}.get(role.name)
        if identify in item.apply_qualification_list:
            activity = await object_as_dict(item)
            activity_id = activity['activity_id']
            activity_name = activity['activity_name']
            start_date = activity['post_start_time'].date()
            start_time = activity['activity_period_list'][0][
                'ActivityStartTime']
            start_time = start_time.split('T')[1]
            start_time = start_time[:5]
            end_date = activity['post_end_time'].date()
            end_time = activity['activity_period_list'][0]['ActivityEndTime']
            end_time = end_time.split('T')[1]
            end_time = end_time[:5]
            location = activity['activity_period_list'][0]['Location']

            text = f"{start_date} {start_time}-{end_date} {end_time}\n活動地點:{location}"
            url = f"https://signupactivity.ntub.edu.tw/activity/activityDetail/{activity_id}"

            activities.append({
                "title":
                f"{activity_name}",
                "image_url":
                "https://i.imgur.com/QAcuOst.jpeg",
                "subtitle":
                text,
                "buttons": [{
                    "type": "web_url",
                    "title": "我要報名",
                    "url": url
                }]
            })

    user_activity = orm.UserActivity()
    user_activity.fb_id = sender_id
    user_activity.activity = activities
    db.add(user_activity)
    db.commit()

    await show_activity(sender_id, headers, params)
    db.close()
Ejemplo n.º 7
0
async def feedback(sender_id, headers, params, **kwargs):
    text = "您的意見是UB醬前進的動力,請問有什麼建議給UB醬的嗎?可以在對話框直接留言唷~"
    bot.send_text_message(sender_id, text)

    db = orm.SessionLocal()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
    state = db.query(
        orm.State).filter(orm.State.name == 'SEND_FEEDBACK').one_or_none()
    user.state_id = state.id
    db.add(user)
    db.commit()
Ejemplo n.º 8
0
async def finish_phone(sender_id, headers, params, **kwargs):
    db = orm.SessionLocal()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
    state = db.query(
        orm.State).filter(orm.State.name == 'QUICK_REPLY').one_or_none()
    user.state_id = state.id
    db.add(user)
    db.commit()
    db.close()

    await quick_replies(sender_id, headers, params, state)
Ejemplo n.º 9
0
async def link_result(sender_id=None, name=None, headers=None, params=None, **kwargs):
    print("called")
    link_list = []
    db = orm.SessionLocal()
    links = db.query(orm.Link).filter(
        orm.Link.name == name
    ).all()

    for link in links:
        print("link: ", link.img_url)
        datum = {
            "title": link.title,
            "image_url": link.img_url,
            "subtitle": link.discription,
            "default_action": {
                "type": "web_url",
                "url": link.url,
                "messenger_extensions": False,
                "webview_height_ratio": "tall",
            },
            "buttons": [
                {
                    "type": "web_url",
                    "url": link.url,
                    "title": link.button_label
                }
            ]
        }

        link_list.append(datum)

    data = {
        "recipient": {
            "id": sender_id
        },
        "message": {
            "attachment": {
                "type": "template",
                "payload": {
                    "template_type": "generic",
                    "elements": link_list,
                }
            }
        }
    }

    response = requests.post(
        'https://graph.facebook.com/v2.6/me/messages',
        headers=headers,
        params=params,
        json=data
    )
    print(response.content)
    db.close()
Ejemplo n.º 10
0
async def research_phone(sender_id, headers, params, **kwargs):
    db = orm.SessionLocal()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
    state = db.query(
        orm.State).filter(orm.State.name == 'SEARCH_PHONE').one_or_none()
    user.state_id = state.id
    db.add(user)
    db.commit()
    print(user.fb_id, state.name, '----------- is me research phone')

    await quick_replies(sender_id, headers, params, state)
    db.close()
Ejemplo n.º 11
0
async def show_result(sender_id, headers, params, result_responses, **kwargs):
    phone_list = []
    db = orm.SessionLocal()

    if not result_responses.json():
        user = db.query(
            orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
        state = db.query(
            orm.State).filter(orm.State.name == "NO_SEARCH").one_or_none()
        user.state_id = state.id
        db.add(user)
        db.commit()

        await none_search(sender_id, headers, params)
        return

    for result_response in result_responses.json():
        phone = "+88634506333"

        if result_response['ext'][0] != '8':
            phone = "0233222777"
        phone = phone + "," + result_response['ext']
        email = result_response['staff']['user']['email']

        datum = {
            "title":
            result_response['staff']['user']['chineseFullName'],
            "image_url":
            "https://i.imgur.com/DjboxZ7.jpeg",
            "buttons": [{
                "type": "web_url",
                "title": "撥打電話",
                "url": f'{ngrok}/phone?phone_number={phone}'
            }, {
                "type": "web_url",
                "title": "撰寫信件",
                "url": f'{ngrok}/email?email={email}'
            }]
        }

        phone_list.append(datum)

    contact = orm.Contact()
    contact.fb_id = sender_id
    contact.contact = phone_list
    db.add(contact)
    db.commit()
    db.close()

    await show_phone(sender_id, headers, params)
Ejemplo n.º 12
0
async def search_name_text(sender_id, **kwargs):
    db = orm.SessionLocal()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()

    state = db.query(
        orm.State).filter(orm.State.name == 'REAL_NAME_SEARCH').one_or_none()
    if state.label:
        sending_text = state.label
        bot.send_text_message(sender_id, sending_text)

    user.state_id = state.id
    db.add(user)
    db.commit()
    db.close()
Ejemplo n.º 13
0
async def subscribed_activity(sender_id, headers, params, **kwargs):
    db = orm.SessionLocal()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()

    if not user.role_id:
        await is_select_user_identify(sender_id, headers, params)
        return

    user.subscribed = True
    user.state_id = sqlalchemy.sql.null()
    db.add(user)
    db.commit()

    bot.send_text_message(sender_id, "訂閱成功!")
    db.close()
Ejemplo n.º 14
0
async def activity_crawling():
    response = requests.get(
        "https://b-signupactivity.ntub.edu.tw/api/Activity/TestGetActivity")

    contents = response.text
    contents = json.loads(contents)
    # print(contents)

    db = orm.SessionLocal()

    # delete all row in specific table
    db.query(orm.Activity).delete()

    nowTime = int(time.time())

    for item in contents:
        # print(item)
        activity = orm.Activity()

        start_struct_date = time.strptime(item['ApplyStartDate'],
                                          "%Y-%m-%dT%H:%M:%S")
        start_time_stamp = int(time.mktime(start_struct_date))
        stop_struct_time = time.strptime(item['ApplyEndDate'],
                                         "%Y-%m-%dT%H:%M:%S")
        stop_time_stamp = int(time.mktime(stop_struct_time))
        # print(item['ApplyQualificationList'], '學生' in item['ApplyQualificationList'])
        # print(nowTime > start_time_stamp, nowTime < stop_time_stamp, nowTime, start_time_stamp, stop_time_stamp)
        if nowTime > start_time_stamp and nowTime < stop_time_stamp:
            # print(item['IsInApply'] and item['IsOutApply'] is False)
            if item['IsInApply'] and item['IsOutApply'] is False:
                activity.activity_id = item['ActivityID']
                activity.activity_name = item['ActivityName']
                activity.unit_name = item['UnitName']
                activity.apply_qualification_list = item[
                    'ApplyQualificationList']
                activity.apply_start_date = item['ApplyStartDate']
                activity.apply_start_time = item['ApplyStartTime']
                activity.apply_end_date = item['ApplyEndDate']
                activity.apply_end_time = item['ApplyEndTime']
                activity.post_start_time = item['PostStartTime']
                activity.post_end_time = item['PostEndTime']
                activity.activity_period_list = item['ActivityPeriodList']

                db.add(activity)
                db.commit()
    print("start crawling")
Ejemplo n.º 15
0
async def send_feedback(sender_id, headers, params, name, **kwargs):
    message = MessageSchema(subject="UB 醬意見回饋",
                            recipients=Settings().RECEPI_EMAIL,
                            body=name,
                            subtype="html")

    fm = FastMail(conf)
    await fm.send_message(message)

    text = "感謝您的留言,UB醬將會盡快給您回復~"
    bot.send_text_message(sender_id, text)

    db = orm.SessionLocal()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
    user.state_id = sqlalchemy.sql.null()
    db.add(user)
    db.commit()
Ejemplo n.º 16
0
async def show_form(message, sender_id, headers, params, **kwargs):
    db = orm.SessionLocal()
    links = db.query(orm.Link).all()
    results = {}
    max_val = 0
    max_score_name = ""

    message = await change_pinyin(message)

    for link in links:
        if "課程科目表" not in link.button_label and "配置圖" not in link.button_label and "行事曆" not in link.button_label:
            print(link.button_label)
            pinyin_link_button_label = await change_pinyin(link.button_label)
            score = fuzz.ratio(pinyin_link_button_label, message)
            print(link.name, " ", score)
            results[link.name] = score

    for item in results:
        if results[item] > max_val:
            max_val = results[item]
            max_score_name = item

    print("max_score_name", max_score_name)

    if max_score_name:
        name = max_score_name
        print("The max_score_name is ", name)

        await link_result(sender_id, name, headers, params)
        db.close()
        return

    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
    state = db.query(
        orm.State).filter(orm.State.name == 'QUICK_REPLY').one_or_none()
    user.state_id = state.id
    db.add(user)
    db.commit()

    bot.send_text_message(sender_id, "找不到相關資訊,可以使用下方快速搜尋你想要的資料喔~")

    await quick_replies(sender_id, headers, params, state)
    db.close()
Ejemplo n.º 17
0
async def set_subscribe(message, sender_id, headers, params, **kwargs):
    letters = ['huodong']
    message = await change_pinyin(message)

    for letter in letters:
        score = fuzz.ratio(letter, message)

        if score >= 50:
            await subscribed_activity(sender_id, headers, params)
        else:
            db = orm.SessionLocal()
            user = db.query(
                orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
            state = db.query(orm.State).filter(
                orm.State.name == 'QUICK_REPLY').one_or_none()
            user.state_id = state.id
            db.add(user)
            db.commit()

            bot.send_text_message(sender_id, "找不到相關資訊,可以使用下方快速搜尋你想要的資料喔~")

            await quick_replies(sender_id, headers, params, state)
            db.close()
Ejemplo n.º 18
0
async def show_contact(message,
                       sender_id,
                       headers,
                       params,
                       flag=None,
                       **kwargs):
    db = orm.SessionLocal()
    contactlist = db.query(orm.ContactList).all()

    print("called show_contect")

    for item in contactlist:
        message = await change_pinyin(message)
        key = await change_pinyin(item.name)
        if key in message:
            name = item.name
            print("use contactlist------------")
            print("name = ", name)
            await search_contact(sender_id, headers, params, name)
            db.close()
            return

    contactnamelist = db.query(orm.ContactNameList).order_by(
        orm.ContactNameList.id.desc()).all()
    for item in contactnamelist:
        if item.name in message:
            name = item.name
            print("use contactnamelist------------")
            await search_contact(sender_id, headers, params, name)
            db.close()
            return

    if flag:
        return True

    await show_result(sender_id, headers, params, result_responses=None)
Ejemplo n.º 19
0
async def search_subject(message, sender_id, headers, params, **kwargs):
    years = [
        '100', '101', '102', '103', '104', '105', '106', '107', '108', '109'
    ]
    systems = {
        'wuzhuan': 'FIVE',
        'erji': 'TWO',
        'siji': 'FOUR',
        'shuoshi': 'MASTER_DEGREE',
        'boshi': 'PHD'
    }
    results = {}
    max_val = 0
    max_score_name = ""

    pinyin_message = await change_pinyin(message)

    for year in years:
        if year in pinyin_message:
            search_year = year
            message = message.replace(year, "")
            for system in systems:
                if system in pinyin_message:
                    search_system = systems.get(system)
                    message = await change_pinyin(message)
                    db = orm.SessionLocal()
                    links = db.query(orm.Link).all()

                    for link in links:
                        if search_year in link.name and search_system in link.name:
                            title = link.title
                            title = title[8:]
                            title = await change_pinyin(title)
                            results[title] = link.name

                    for item in results:
                        score = fuzz.ratio(item, message)
                        print(item, results[item], score)
                        if score > max_val:
                            max_val = score
                            max_score_name = results[item]

                    if max_score_name:
                        print(max_score_name)
                        name = max_score_name

                        await link_result(sender_id, name, headers, params)
                        db.close()
                        return

            state_name = search_year + "_class"
            state = db.query(
                orm.State).filter(orm.State.name == state_name).one_or_none()
            user = db.query(
                orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
            user.state_id = state.id
            db.add(user)
            db.commit()

            await quick_replies(sender_id, headers, params, state)
            db.close()

    db = orm.SessionLocal()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
    state = db.query(
        orm.State).filter(orm.State.name == 'QUICK_REPLY').one_or_none()
    user.state_id = state.id
    db.add(user)
    db.commit()

    bot.send_text_message(sender_id, "找不到相關資訊,可以使用下方快速搜尋你想要的資料喔~")

    await quick_replies(sender_id, headers, params, state)
    db.close()
Ejemplo n.º 20
0
async def show_newest_activity(message, sender_id, headers, params, **kwargs):
    if message:
        print("Get into ai search message")
        db = orm.SessionLocal()
        result_activities = []
        items = db.query(orm.Activity).all()
        search_activity = await change_pinyin(message)
        for item in items:
            if message in item.activity_name:
                activity = await object_as_dict(item)
                activity_id = activity['activity_id']
                activity_name = activity['activity_name']
                start_date = activity['post_start_time'].date()
                start_time = activity['activity_period_list'][0][
                    'ActivityStartTime']
                start_time = start_time.split('T')[1]
                start_time = start_time[:5]
                end_date = activity['post_end_time'].date()
                end_time = activity['activity_period_list'][0][
                    'ActivityEndTime']
                end_time = end_time.split('T')[1]
                end_time = end_time[:5]
                location = activity['activity_period_list'][0]['Location']

                text = f"{start_date} {start_time}-{end_date} {end_time}\n活動地點:{location}"
                url = f"https://signupactivity.ntub.edu.tw/activity/activityDetail/{activity_id}"
                result_activities.append({
                    "title":
                    f"{activity_name}",
                    "image_url":
                    "https://i.imgur.com/QAcuOst.jpeg",
                    "subtitle":
                    text,
                    "buttons": [{
                        "type": "web_url",
                        "title": "我要報名",
                        "url": url
                    }]
                })
        if not result_activities:
            for item in items:
                pinyin_activity = await change_pinyin(item.activity_name)
                score = fuzz.ratio(pinyin_activity, search_activity)
                print(item.activity_name, score)
                if score > 20:
                    activity = await object_as_dict(item)
                    activity_id = activity['activity_id']
                    activity_name = activity['activity_name']
                    start_date = activity['post_start_time'].date()
                    start_time = activity['activity_period_list'][0][
                        'ActivityStartTime']
                    start_time = start_time.split('T')[1]
                    start_time = start_time[:5]
                    end_date = activity['post_end_time'].date()
                    end_time = activity['activity_period_list'][0][
                        'ActivityEndTime']
                    end_time = end_time.split('T')[1]
                    end_time = end_time[:5]
                    location = activity['activity_period_list'][0]['Location']

                    text = f"{start_date} {start_time}-{end_date} {end_time}\n活動地點:{location}"
                    url = f"https://signupactivity.ntub.edu.tw/activity/activityDetail/{activity_id}"
                    result_activities.append({
                        "title":
                        f"{activity_name}",
                        "image_url":
                        "https://i.imgur.com/QAcuOst.jpeg",
                        "subtitle":
                        text,
                        "buttons": [{
                            "type": "web_url",
                            "title": "我要報名",
                            "url": url
                        }]
                    })
        print(result_activities)

        user_activity = orm.UserActivity()
        user_activity.fb_id = sender_id
        user_activity.activity = result_activities
        db.add(user_activity)
        db.commit()
        db.close()
        await show_activity(sender_id, headers, params, **kwargs)
    else:
        await create_formated_activities(sender_id, headers, params)
Ejemplo n.º 21
0
async def process_postback(messaging, postback):
    # 1. user
    # 2. state
    # 3. get all sub states
    # 4. compare postback in sub states
    # 5. response
    global headers, params
    db = orm.SessionLocal()

    user_fb_id = messaging['sender']['id']
    user = db.query(
        orm.User).filter(orm.User.fb_id == user_fb_id).one_or_none()
    if user is None:
        db_user = orm.User()
        db_user.fb_id = user_fb_id
        db.add(db_user)
        db.commit()
        await init_menu(user_fb_id, headers, params)
        user = db_user

    payload = postback['payload']
    print("process_postback's payload is :", payload)
    if payload == 'QUICK_REPLY':
        user.state_id = sqlalchemy.sql.null()
        db.add(user)
        db.commit()

    sub_states = db.query(
        orm.State).filter(orm.State.parent_id == user.state_id).all()
    print("process postback's sub_state is :", sub_states)
    if not sub_states:
        state_function = db.query(
            orm.State).filter(orm.State.name == payload).one_or_none()
        if state_function:
            print("process_postback's function is: ", state_function.function)
            function = mapping.get(state_function.function)
            await function(sender_id=user.fb_id,
                           headers=headers,
                           params=params)
            db.close()
            return
    sub_state_names = [sub_state.name for sub_state in sub_states]
    print("sub_state_names: ", sub_state_names, payload)
    if payload in sub_state_names:
        # Change user state to input state
        state = db.query(orm.State).filter(orm.State.name == payload).first()
        user.state_id = state.id
        db.add(user)
        db.commit()
        # Execute state function
        print(state.function)
        if state.function:
            if not db.query(orm.State).filter(
                    orm.State.parent_id == user.state_id).all():
                user.state_id = sqlalchemy.sql.null()
            db.add(user)
            db.commit()
            function = mapping.get(state.function)
            await function(sender_id=user.fb_id,
                           headers=headers,
                           params=params,
                           name=payload)
            db.close()
            return
        sub_states = db.query(
            orm.State).filter(orm.State.parent_id == user.state_id).all()
        print(sub_states)
        # Find next states
        data = {
            "recipient": {
                "id": user.fb_id
            },
            "messaging_type": "RESPONSE",
            "message": {
                "text":
                state.prompt or state.label,
                "quick_replies": [{
                    "content_type": "text",
                    "title": sub_state.label,
                    "payload": sub_state.name,
                } for sub_state in sub_states]
            }
        }
        print(data)
        resp = requests.post('https://graph.facebook.com/v10.0/me/messages',
                             headers=headers,
                             params=params,
                             json=data)
        print(resp, resp.content.decode('utf-8'))
    db.close()
Ejemplo n.º 22
0
async def show_activity(sender_id, headers, params, **kwargs):
    show_activity = []
    db = orm.SessionLocal()
    items = db.query(
        orm.UserActivity).filter(orm.UserActivity.fb_id == sender_id).order_by(
            orm.UserActivity.id.desc()).first()
    activity = items.activity

    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()

    if len(activity) > 10:
        show_activity = activity[-9:]
        show_activity.append({
            "title":
            "沒有找到你想要的嗎?",
            "image_url":
            "https://i.imgur.com/QAcuOst.jpeg",
            "buttons": [{
                "type": "postback",
                "title": "點我看更多",
                "payload": "MORE_ACTIVITY"
            }]
        })

        items.activity = activity[:len(activity) - 9]
        db.add(items)
        db.commit()
    else:
        show_activity = items.activity
        items.activity = []

    if items.activity:
        user = db.query(
            orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
        state = db.query(orm.State).filter(
            orm.State.name == "NEWEST_ACTIVITY").one_or_none()
        user.state_id = state.id
        db.add(user)
        db.commit()

    data = {
        "recipient": {
            "id": sender_id
        },
        "message": {
            "attachment": {
                "type": "template",
                "payload": {
                    "template_type": "generic",
                    "elements": show_activity,
                }
            }
        }
    }
    print(data)

    response = requests.post('https://graph.facebook.com/v2.6/me/messages',
                             headers=headers,
                             params=params,
                             json=data)
    print(response.content)
    db.close()
Ejemplo n.º 23
0
async def detect_action(message, sender_id, headers, params, **kwargs):
    # 1. 判斷功能
    # 2. 拿掉功能關鍵字
    # 3. 跑對應的 funcion
    action_list = [{
        "keys": ["打電話", "打給", "撥打", "撥給", "電話", "號碼"],
        "function": show_contact,
    }, {
        "keys": ["email", "寫信", "信箱", "郵件", "寄信", "郵箱"],
        "function": show_contact,
    }, {
        "keys": ["地圖", "校園地圖", "在哪裡", "怎麼去", "教室"],
        "function": show_map,
    }, {
        "keys": ["學分", "課程科目表", "課程", "課表"],
        "function": search_subject,
    }, {
        "keys": ["訂閱", "訂閱活動"],
        "function": set_subscribe,
    }, {
        "keys": ["最新活動", "活動"],
        "function": show_newest_activity,
    }, {
        "keys": ["行事曆"],
        "function": show_calendar,
    }, {
        "keys": ["表單", "表單連結", "連結"],
        "function": show_form,
    }]

    if message is not None:
        for action in action_list:
            for key in action["keys"]:
                if key in message:
                    message = message.replace(key, "")
                    print("message ", message)
                    print("function ", action["function"])
                    await action["function"](message, sender_id, headers,
                                             params)
                    return

        print("call show_contact with teacher name")
        none_contact = await show_contact(message,
                                          sender_id,
                                          headers,
                                          params,
                                          flag=True)
        if none_contact:
            bot.send_text_message(sender_id, "找不到相關資訊,可以使用下方快速搜尋你想要的資料喔~")

        db = orm.SessionLocal()
        user = db.query(
            orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
        state = db.query(
            orm.State).filter(orm.State.name == 'QUICK_REPLY').one_or_none()
        user.state_id = state.id
        db.add(user)
        db.commit()

        await quick_replies(sender_id, headers, params, state)
        db.close()
Ejemplo n.º 24
0
async def process_message(messaging, message):
    # 1. user
    # 2. state
    # 3. get all sub states
    # 4. compare message in sub states
    # 5. response
    global headers, params
    db = orm.SessionLocal()
    user_fb_id = messaging['sender']['id']
    user = db.query(
        orm.User).filter(orm.User.fb_id == user_fb_id).one_or_none()
    if user is None:
        db_user = orm.User()
        db_user.fb_id = user_fb_id
        db.add(db_user)
        db.commit()
        await init_menu(user_fb_id, headers, params)
        user = db_user
    sub_states = db.query(
        orm.State).filter(orm.State.parent_id == user.state_id).all()
    if not sub_states:
        print(message)
        if 'text' in message:
            payload = message['text']

    sub_state_names = [sub_state.name for sub_state in sub_states[::-1]]
    # NTUB_ROOM_LOCATION
    payload = None
    if 'quick_reply' in message:
        payload = message['quick_reply']['payload']
        label = message['text']
    elif 'text' in message:
        payload = message['text']

    state = db.query(
        orm.State).filter(orm.State.id == user.state_id).one_or_none()
    if payload in sub_state_names:
        state = db.query(orm.State).filter(orm.State.name == payload).first()
        # Change user state to input state
        user.state_id = state.id
        db.add(user)
        db.commit()
        # Execute state function
        print(state.function)
        if state.function:
            if not db.query(orm.State).filter(
                    orm.State.parent_id == user.state_id).all():
                user.state_id = sqlalchemy.sql.null()
            db.add(user)
            db.commit()
            function = mapping.get(state.function)
            await function(sender_id=user.fb_id,
                           headers=headers,
                           params=params,
                           name=payload,
                           label=label)
            db.close()
            return
        # Find next states
        await quick_replies(user.fb_id, headers, params, state)
    elif state and state.is_input and state.function:
        print('in ', state, state.is_input, state.function)
        function = mapping.get(state.function)
        await function(sender_id=user.fb_id,
                       headers=headers,
                       params=params,
                       name=payload)
        if not db.query(
                orm.State).filter(orm.State.parent_id == user.state_id).all():
            user.state_id = sqlalchemy.sql.null()
        db.add(user)
        db.commit()
        db.close()
        return
    else:
        message = payload
        print("call main.py--------------------")
        print("message", message)
        await detect_action(message,
                            sender_id=user.fb_id,
                            headers=headers,
                            params=params)
        return

    db.close()
Ejemplo n.º 25
0
        json=data
    )
    print(resp.json())
    print("finished init menu")

print(__name__)
if __name__ == '__main__':
    headers = {
        'Content-Type': 'application/json',
    }
    params = (
        ('access_token', PAGE_ACCESS_TOKEN),
    )
    data = '{ "get_started": {"payload": "Hi I am UB jun"} }'

    db = orm.SessionLocal()
    users = db.query(orm.User).all()

    for user in users:
        psid = user.fb_id
        print("psid: ", psid)
        requests.delete(
            f'https://graph.facebook.com/v10.0/me/custom_user_settings?psid={psid}&'
            f'params=[%22persistent_menu%22]&access_token={PAGE_ACCESS_TOKEN}')

        response = requests.post(
            'https://graph.facebook.com/v2.6/me/messenger_profile',
            headers=headers,
            params=params,
            data=data)