Exemplo n.º 1
0
def handle_message(event):
    if event.source.type != 'group':
        return

    member_info, ratings_info = load_group_info(event)

    message_preprocess(member_info, event)

    app.logger.info(f"group: {event.source.group_id}, text: {event.message.text}")

    if '!도움' in event.message.text:
        message = help_message(event.message.text)
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message))
        return

    if ' vs. ' in event.message.text:
        do_versus(event)
        return

    demote_commands = (
        '!강등',
        '!불매', '!понижение', '!降等', '!降格', '!こうとう',
        '!저격', '!낙선', '!낙천', '!세무조사',
        '!기소', '!고소', '!하하하', '!멈춰')

    frequency_commands = ('!빈도', '!частота', '!頻度', '!ひんど')

    splitted = event.message.text.split()
    if splitted[0] == '!삭제':
        delete_entry(ratings_info, event)
    elif splitted[0] in frequency_commands:
        show_frequency(member_info, event)
    elif splitted[0] in demote_commands:
        adjust_ranking(ratings_info, member_info, 'demote', event)
    elif splitted[0] == '!탄핵':
        adjust_ranking(ratings_info, member_info, 'demote', event, 0)
    elif splitted[0] == '!초강등':
        adjust_ranking(ratings_info, member_info, 'super_demote', event)
    elif splitted[0] in ('!승급', '!공천'):
        adjust_ranking(ratings_info, member_info, 'promote', event)
    elif splitted[0] in ('!사면', '!특사'):
        adjust_ranking(ratings_info, member_info, 'special_promote', event)
    elif splitted[0] in ('!등급', '!ранг'):
        show_ranking(ratings_info, event)
    elif splitted[0] in ('!명언', '!망언', '!пословица'):
        show_today_message(member_info, event)
    elif splitted[0] in ('!형량예측', '!형량', '!항소', '!상고'):
        predict_verdict(event)
    elif splitted[0] == '!시세':
        tell_price(event)
    elif splitted[0] == '!roll':
        roll_dice(event)
    elif 'http' in event.message.text:
        process_link(member_info, event)
    elif event.message.text.startswith('힝') or event.message.text.endswith('힝'):
        text_message = TextSendMessage(text='어른스럽게 말해야지')
        messages = [text_message]
        line_bot_api.reply_message(event.reply_token, messages)

    save_group_info(member_info, ratings_info, event)
def handle_msg_sticker(event):
    '''
        ImageMessage auto upload to imgur and reply image url  
    '''
    make_static_tmp_dir()
    if isinstance(event.message, ImageMessage):
        ext = 'jpg'
    message_content = line_bot_api.get_message_content(event.message.id)
    with tempfile.NamedTemporaryFile(dir=static_tmp_path,
                                     prefix=ext + '-',
                                     delete=False) as tf:
        for chunk in message_content.iter_content():
            tf.write(chunk)
        tempfile_path = tf.name

    dist_path = tempfile_path + '.' + ext
    dist_name = os.path.basename(dist_path)
    os.rename(tempfile_path, dist_path)
    client = ImgurClient(client_id, client_secret, access_token, refresh_token)
    config = {
        'album': album_id,
        'name': 'Catastrophe!',
        'title': 'Catastrophe!',
        'description': 'Cute kitten being cute on '
    }
    path = os.path.join('static', 'tmp', dist_name)
    image = client.upload_from_path(path, config=config, anon=False)
    os.remove(path)
    print(path)
    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(
            text='You can find image here: {0}'.format(image['link'])))
Exemplo n.º 3
0
def show_frequency(member_info, event):
    message_frequency = OrderedDict()
    for user_id, user_info in member_info.items():
        group_id = event.source.group_id
        profile = line_bot_api.get_group_member_profile(group_id, user_id)
        message_frequency[profile.display_name] = user_info['n_message']

    sorted_users = sorted(message_frequency.items(), key=lambda m: m[1], reverse=True)

    sum_messages = sum((m[1] for m in sorted_users))

    message = '*오늘의 메시지 수({})*\n\n'.format(sum_messages)
    for i, (user_name, frequency) in enumerate(sorted_users):
        medals = {0: EMOJI_1ST, 1: EMOJI_2ND, 2: EMOJI_3RD}

        mod = do_calculate_mod(i, len(member_info))
        mod_str = ''
        if mod > 0:
            mod_str = '/+{}'.format(mod)
        elif mod < 0:
            mod_str = '/{}'.format(mod)

        if i in medals:
            message += '{} '.format(medals[i])
        message += '{0}: {1}회 ({2:.1f}%{3})\n'.format(
                user_name, frequency, frequency/sum_messages*100.0, mod_str)

    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message))
Exemplo n.º 4
0
def detect_duplicates(member_info, event):
    splits = event.message.text.split(' ')
    for split in splits:
        if split.startswith('http'):
            link = split
            break
    else:
        return False

    group_id, user_id = event.source.group_id, event.source.user_id
    rkey = '{}_{}'.format(group_id, link)

    entry_serialized = r.get(rkey)
    if entry_serialized is not None:
        entry = json.loads(entry_serialized)

        message = '{} 삐빅 중복입니다\nby {} ({})'.format(
                EMOJI_ROBOT, entry['uploader'], entry['time'])
        messages = [TextSendMessage(text=message)]
        line_bot_api.reply_message(event.reply_token, messages)
        return True

    profile = line_bot_api.get_group_member_profile(group_id, user_id)
    uploader = '@' + profile.display_name

    KST = timezone('Asia/Seoul')
    d = datetime.datetime.now(tz=KST)
    entry = {
        'uploader': uploader,
        'time': d.strftime('%m/%d %H:%M'), }

    entry_serialized = json.dumps(entry)
    r.setex(rkey, 86400*3, entry_serialized)
    return False
Exemplo n.º 5
0
def show_today_message(member_info, event):
    filtered = filter(lambda x: 'message_today' in x[1], list(member_info.items()))

    user_id, user_info = random.choice(list(filtered))
    group_id = event.source.group_id
    profile = line_bot_api.get_group_member_profile(group_id, user_id)
    message = '*오늘의 명언*\n\n'
    message += '{}: {}'.format(profile.display_name, user_info['message_today'])
    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message))
Exemplo n.º 6
0
def do_versus(event):
    splitted = event.message.text.split(' vs. ')
    if len(splitted) < 2:
        return

    ranked = ((word, get_score(word.strip())) for word in splitted)
    rank_sorted = sorted(ranked, key=lambda m: m[1], reverse=True)

    message = ''
    for i, (word, score) in enumerate(rank_sorted):
        winner = '' if i > 0 else ' (winner)'
        message += '{}. {} ({}){}\n'.format(i+1, word, score, winner)
    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message))
Exemplo n.º 7
0
def handle(event):

    user_id = event.source.user_id
    profile = line_bot_api.get_profile(user_id)
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(
            text = profile.display_name + ' 您好, 歡迎來到 PTT 股版風向儀,有什麼想知道的事情嗎?',
            quick_reply = quick_reply.quick_reply()
        )
    )

    upsert_user_data( now, profile )
Exemplo n.º 8
0
def delete_entry(ratings, event):
    splitted = event.message.text.split()
    if len(splitted) < 2:
        print('[WARN] too short message to demote')
        return

    to_delete = ' '.join(splitted[1:])
    if to_delete in ratings:
        del ratings[to_delete]
        message = '삭제되었습니다 {}'.format(EMOJI_SMILE)
    else:
        message = '삭제할 수 없습니다 {}'.format(EMOJI_SORRY)

    message = ratings_to_message(ratings) + '\n\n' + message
    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message))
Exemplo n.º 9
0
def predict_verdict(event):
    splitted = event.message.text.split()
    if len(splitted) < 2:
        app.logger.warn('too short message to verdict')
        return

    target = ' '.join(splitted[1:]).replace('@', '')
    verdicts = [
            '무죄', '징역 2년 집행유예 4년', '사형', '국종룸 24시간', '즉결처분',
            '징역 1년 집행유예 2년', '기소유예', '취업제한 5년', '기록 말소형',
            '120시간 사회봉사', '신상공개 10년', '칭호 박탈', '15일 구류',
            '훈방', '징역 30년', '징역 10년', '징벌적 손해배상 1억 5천만원',
            '무기징역', '무죄', '징역 1년', '벌금 300만원', '징역 40년']
    verdict = random.choice(verdicts)
    message = '{0} *AI 형량 예측 결과*\n'.format(EMOJI_BALANCE) + \
        f'{target}: {verdict}'
    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message))
Exemplo n.º 10
0
def roll_dice(event):
    last_word = event.message.text.split()[-1]
    splitted = last_word.split('d')
    if len(splitted) == 1:
        x = 1
        y = splitted[0]
    else:
        x, y = last_word.split('d')

    if y == '%':
        y = 100

    rolls = []
    for i in range(int(x)):
        rolls.append(random.randint(1, int(y)))

    total = sum(rolls)
    total_string = ' '.join((str(r) for r in rolls))
    message = '결과: {} ({})'.format(total, total_string)

    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message))
Exemplo n.º 11
0
def handle(event, rich_menu_id01):
    user_id = event.source.user_id
    profile = line_bot_api.get_profile(user_id)
    try:
        line_bot_api.link_rich_menu_to_user(user_id=event.source.user_id,
                                            rich_menu_id=rich_menu_id01)
        print('Success')
    except Exception as e:
        print(e)

    # 開啟檔案,將用戶個資1.display_name 2.user_id 3.picture_url,存入DB
    # display_name = user_profile['displayName']
    # user_id=user_profile['userId']
    # picture_url = user_profile['pictureUrl']
    # 建立文字消息
    follow_text_send_message = TextSendMessage(
        str(profile.display_name) +
        "你好~我是教練Seal,歡迎歡迎!\n一起來動滋動吧!\n為了幫你量身打造適合的運動,先讓我對你有更多認識吧(❁´◡`❁)")
    # 創造一個QuickReplyButton
    text_quickreply0 = QuickReplyButton(action=PostbackAction(
        label='男', display_text='我是男生~', data='gender=male'))
    text_quickreply1 = QuickReplyButton(action=PostbackAction(
        label='女', display_text='我是女生~', data='gender=female'))
    text_quickreply2 = QuickReplyButton(action=PostbackAction(
        label='其他', display_text='我想選擇其他', data='gender=other'))
    # 創造一個QuickReply,並把剛剛創建的button放進去
    quick_reply_array1 = QuickReply(
        items=[text_quickreply0, text_quickreply1, text_quickreply2])

    # 生成一個文字消息
    reply_text_message1 = TextSendMessage('性別是?',
                                          quick_reply=quick_reply_array1)
    line_bot_api.reply_message(event.reply_token,
                               [follow_text_send_message, reply_text_message1])

    #儲存使用者資料
    print(user_id, profile.display_name, profile.picture_url)
    savebasic01(user_id, profile.display_name, profile.picture_url)
    return "FollowEvent done"
Exemplo n.º 12
0
def handle(event):
    user_id = event.source.user_id
    profile = line_bot_api.get_profile(user_id)
    today = date.today()

    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(
            text='你傳什麼照蛤?我要把他偷偷存起來!',
            quick_reply=QuickReply(items=[
                QuickReplyButton(action=MessageAction(label="好吧", text='好吧'))
            ])))

    image_temp_variable = line_bot_api.get_message_content((event.message.id))

    with open('/tmp/' + event.message.id + '.jpg', 'wb') as f:
        for chunk in image_temp_variable.iter_content():
            f.write(chunk)

    s3_client = boto3.client('s3',
                             aws_access_key_id=s3_access_key_id,
                             aws_secret_access_key=s3_secret_access_key)
    s3_client.upload_file('/tmp/' + event.message.id + '.jpg', s3_bucket,
                          'student08/' + event.message.id + '.jpg')
Exemplo n.º 13
0
def handle(event):
    user_id = event.source.user_id
    profile = line_bot_api.get_profile(user_id)
    today = date.today()

    if event.message.text == '指令':
        return line_bot_api.reply_message(
            event.reply_token,
            FlexSendMessage(alt_text='指令一覽表',
                            contents=flex_message.command_list(today),
                            quick_reply=quick_reply.quick_reply()))
    if event.message.text == '不查了' or event.message.text == '不看了':
        return line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text='好喔', quick_reply=quick_reply.quick_reply()))
    # 如果匹配 ^[自首隨意][:][數字][-][數字][-][數字][:][數字][-][數字][-][數字]$
    # ^:自首必填,$:字尾必為數字
    if re.search(
            "^([\s\S]+)(:+)(\d+)(-+)(\d+)(-+)(\d+)(:+)(\d+)(-+)(\d+)(-+)(\d+)$",
            event.message.text):

        messages = event.message.text.split(':')
        condition = messages[0]
        print(condition)
        start_date = messages[-2]
        end_date = messages[-1]

        if condition == '風向':
            # 先回傳訊息,避免使用者體驗中斷
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='謝謝您的查詢,您查詢的時間區間為\n\n' + start_date +
                                ':' + end_date +
                                '\n\n查詢可能需要耗費幾秒鐘的時間,\n請記得點選 「查看結果」。',
                                quick_reply=quick_reply.get_result(user_id)))
            # 依照時間區間計算股票版公司情緒並除存在 redis 方便用戶查詢
            company = None
            r = redis.from_url(redis_url)
            CalPttSents(r, user_id, start_date, end_date, company)
            return
        elif condition == '留言':
            line_bot_api.reply_message(
                event.reply_token,
                FlexSendMessage(alt_text='前往查看公司評論',
                                contents=flex_message.company_comment(
                                    start_date, end_date),
                                quick_reply=quick_reply.quick_reply()))
            return
        else:
            with open('data/company_dict.json', 'r') as read_file:
                dict_data = json.load(read_file)

            select = condition.split('_')[0]
            company = condition.split('_')[1]
            for company_refers in dict_data.items():
                if company in company_refers[1]:
                    company = company_refers[0]

            if select == '評價':
                # 先回傳訊息,避免使用者體驗中斷
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(
                        text='謝謝您的查詢,您查詢的時間區間為\n\n' + start_date + ':' +
                        end_date + '\n\n查詢可能需要耗費幾秒鐘的時間,\n請記得點選 「查看結果」。',
                        quick_reply=quick_reply.get_result(user_id)))
                r = redis.from_url(redis_url)
                CalPttSents(r, user_id, start_date, end_date, company)
                return
            if select == '留言':
                line_bot_api.reply_message(
                    event.reply_token,
                    FlexSendMessage(alt_text='前往查看公司評論',
                                    contents=flex_message.company_comment(
                                        start_date, end_date, company),
                                    quick_reply=quick_reply.quick_reply()))
                return

    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text='點選快速查詢風向:\n查詢 PTT 股版的留言情緒量化結果\n\n'
                        '點選快速查詢留言:\n查詢 PTT 股版的留言\n\n'
                        '也可以輸入「指令」查詢',
                        quick_reply=quick_reply.quick_reply()))
Exemplo n.º 14
0
def handle(event):

    user_id = event.source.user_id
    profile = line_bot_api.get_profile( user_id )
    r = redis.from_url( redis_url )

    today = date.today ()

    # if re.search( "^action=opinion_leader", event.postback.data ):
    #     post_data = query_string.parse(event.postback.data)
    #     print(post_data)

    # if event.postback.data == 'opinion_leader_list':
    #     line_bot_api.reply_message(
    #         event.reply_token,
    #         TextSendMessage(
    #             text = '請輸入時間',
    #             quick_reply = query_date( [6,12,30,60],user_id )
    #         )
    #     )
        # 若 user 查詢意見領袖投資報酬率時,詢問 user 要依照多久時間為指標各個作者的投資報酬率
        # select (company_name,date) from opinion_leader 會回傳一個 list with company_id and date
        # 用這個 list 去 query 出 company_price => select company_id from company_price where date = (date + user_insert_date)
        # 上面這個 query 會跑 3000 多個,勢必會對使用者體驗造成負擔,所以也要做二段訊息讓資訊緩衝,先把 query 結果存在 redis
        # user 點選查看結果後才會回傳真正的結果
        # 若 user 查詢某特定 id 的

    if event.postback.data == 'company_comment_list':
        r.delete('select')
        r.set('select', 'comment')
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='請輸入時間',
                quick_reply= search_date( today )
            )
        )

    # 查詢自那天起的股市留言歸納出前後三名公司,做成 Flex message 送給用戶
    if event.postback.data == 'company_sentiment_list':
        r.delete( 'select' )
        r.set( 'select', 'sentiment' )
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='請輸入時間',
                quick_reply= search_date( today )
            )
        )

    # 因為 line bot 沒有 cookies & session,所以若要做暫存效果,需要把 start_date & end_date 存入 redis
    # 下面判斷若 redis 裡面有開始與結束時間,則以此時間區間回傳已經儲存在 redis 的公司留言分析結果
    if event.postback.data == 'start_date' or event.postback.data == 'end_date':

        if event.postback.data == 'start_date':
            return r.mset( {'start_date':event.postback.params['date'] } )
        if event.postback.data == 'end_date':
            r.mset( {'end_date':event.postback.params['date']} )

        if r.get( 'start_date' ) and r.get( 'end_date' ):

            if r.get('select').decode() == 'comment':
                line_bot_api.reply_message(
                    event.reply_token,
                    [
                        TextSendMessage(
                            text = "感謝您的查詢,點選以下網址查看留言\n https://ptt-stock-vane.herokuapp.com/comments?start_date="+r.get( 'start_date' ).decode()+"&end_date="+r.get( 'end_date' ).decode()+"&company=",
                            quick_reply = quick_reply.quick_reply()
                        )
                        # FlexSendMessage(
                        #     alt_text = '前往查看公司評論',
                        #     contents = flex_message.company_comment( r.get( 'start_date' ).decode(), r.get( 'end_date' ).decode() ),
                        #     quick_reply = quick_reply.quick_reply()
                        # )
                    ]
                )
            else:
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(
                        text = '謝謝您的查詢,您查詢的時間區間為\n\n' +
                               r.get( 'start_date' ).decode() + ':' + r.get( 'end_date' ).decode() +
                               '\n\n查詢可能需要耗費幾秒鐘的時間,\n請記得點選 「查看結果」。',
                        quick_reply = quick_reply.get_result( user_id )
                    )
                )
                if r.get('select').decode() == 'sentiment':
                    # 依照時間區間計算股票版公司情緒並除存在 redis 方便用戶查詢
                    CalPttSents( r, user_id, r.get( 'start_date' ).decode(), r.get( 'end_date' ).decode() )

            r.delete( 'end_date' )
            r.delete( 'start_date' )

    # 如果 post 過來的是他的 user_id,那就顯示 redis 裡面保存給他的資料
    if event.postback.data == user_id:
        if r.get( user_id ):

            with open( 'data/company_dict.json', 'r' ) as read_file:
                dict_data = json.load( read_file )

            result = json.loads( r.get( user_id ) )

            # 若用戶只查一個公司,就回覆一個公司的情緒分析
            if len(result.keys()) == 1:
                print(result)
                company_id = list(result.keys())[0]
                company_name = dict_data[company_id][1]
                sentiment = '%.2f' % list(result.values())[0][0]
                comment = list(result.values())[0][1]
                return line_bot_api.reply_message(
                    event.reply_token,
                    [
                        # TODO: 用 Flex message 取代
                        TextSendMessage(
                            text = '謝謝您的查詢,以下是您的搜尋結果。\n'+ company_name + ' '+ company_id +
                                   '\n好感度:' + str(sentiment) +
                                   '\n留言數:' + str(comment),
                            quick_reply = quick_reply.quick_reply()
                        )
                    ]
                )

            # 依照 value 來排序字典,篩選掉留言小於 20 的結果
            # 回傳前後三個股版留言好感度統計與留言數,並只擷取小數點後兩位
            neg_data, neg_name, pos_data, pos_name = get_sorted_result( result )

            line_bot_api.reply_message(
                event.reply_token,
                [
                    TextSendMessage(
                        text = '謝謝您的查詢,以下是您的搜尋結果。\n系統會自動替除掉留言少於20的結果\n\n鄉民觀感最好的三間公司:\n' +
                        dict_data[pos_name[2]][1] + '  好感度:' + str(pos_data[2][0]) + '  留言數:' + str(pos_data[2][1]) + '\n' +
                        dict_data[pos_name[1]][1] + '  好感度:' + str(pos_data[1][0]) + '  留言數:' + str(pos_data[1][1]) + '\n' +
                        dict_data[pos_name[0]][1] + '  好感度:' + str(pos_data[0][0]) + '  留言數:' + str(pos_data[0][1]) + '\n\n' +
                        '鄉民觀感最差的公司:\n' +
                        dict_data[neg_name[2]][1] + '  好感度:' + str(neg_data[2][0]) + '  留言數:' + str(neg_data[2][1]) + '\n' +
                        dict_data[neg_name[1]][1] + '  好感度:' + str(neg_data[1][0]) + '  留言數:' + str(neg_data[1][1]) + '\n' +
                        dict_data[neg_name[0]][1] + '  好感度:' + str(neg_data[0][0]) + '  留言數:' + str(neg_data[0][1]) + '\n',
                        quick_reply = quick_reply.quick_reply()
                    ),
                    # TODO: 用小輪播顯示三個綠色好公司,三個紅色壞公司,若要查看公司留言,則導入 flask 網站
                    # 所以要額外做一個用來顯示留言的頁面
                    # FlexSendMessage(
                    #     alt_text = '股市風向圖',
                    #     contents = flex_message.company_list(),
                    #     quick_reply = quick_reply.quick_reply
                    # )
                ]
            )

        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    text = '可能還要再等幾秒鐘,搜尋一天大約1~2秒,如果搜尋30天約等30秒上下',
                    quick_reply = quick_reply.get_result( user_id )
                )
            )
Exemplo n.º 15
0
def show_ranking(ratings, event):
    message = ratings_to_message(ratings)
    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message))
Exemplo n.º 16
0
def handle(event,
           rich_menu_id01=rich_menu_id01,
           rich_menu_id02=rich_menu_id02,
           today=today):
    user_id = event.source.user_id
    profile = line_bot_api.get_profile(user_id)
    msg_content = event.message.text
    check = checkdate(user_id)
    print(check[0])
    #詢問基本資料=================================================================
    if (event.message.text.find('一切都很好,放馬過來吧!ᕦ(ò_óˇ)ᕤ' or '健康') != -1):
        start_textmessage = '瞭解~那麼我們開始今天的練習吧(^_−)−☆ 請點擊下方的圖文選單'
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=start_textmessage))

    elif (event.message.text.find('啊啊⋯有點累' or '不太好') != -1):
        start_textmessage = '瞭解~請不要太勉強自己,適度動一動即可。那麼讓我們開始今天的練習吧(^_−)−☆ 請點擊下方的圖文選單'
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=start_textmessage))

    #健身影片推薦=================================================================
    elif (event.message.text.find('我想練胸肌') != -1):
        with open("./flex/c_push-up.txt", "r", encoding='utf8') as jsonfile:
            json_object = json.load(jsonfile)
        FM = FlexSendMessage.new_from_json_dict(json_object)
        line_bot_api.reply_message(event.reply_token, FM)
    elif (event.message.text.find('我要消除鮪魚肚') != -1):
        with open(os.path.join(os.getcwd(), "flex", "a_10mins_woman.txt"),
                  "r",
                  encoding='utf8') as jsonfile:
            json_object = json.load(jsonfile)
        FM = FlexSendMessage.new_from_json_dict(json_object)
        line_bot_api.reply_message(event.reply_token, FM)

    elif (event.message.text.find('想當背影Killer') != -1):
        '''
        用JSON生成模板消息
            讀取本地的json檔案- json.load 取得json物件
            將json物件放入TemplateSendMessage的new_from_json_dict方法,並存在變數內即可
        '''
        print("有進入elif迴圈")
        with open(os.path.join(os.getcwd(), "flex",
                               "b_all_back_movement.json"),
                  "r",
                  encoding='utf8') as jsonfile:
            json_object = json.load(jsonfile)
        b01 = FlexSendMessage.new_from_json_dict(json_object)
        # with open(os.path.join(os.getcwd(),"flex","b_bird-dog.json"), "r", encoding='utf8') as jsonfile:
        #     json_object = json.load(jsonfile)
        # b02 = FlexSendMessage.new_from_json_dict(json_object)
        # with open(os.path.join(os.getcwd(),"flex","b_10mins_woman.json"), "r", encoding='utf8') as jsonfile:
        #     json_object = json.load(jsonfile)
        # b03 = FlexSendMessage.new_from_json_dict(json_object)
        # line_bot_api.reply_message(event.reply_token,[b01, b02, b03])
        line_bot_api.reply_message(event.reply_token, b01)

    elif (event.message.text.find('我想練臀腿') != -1):
        # elif ('我想練臀腿') in controller.message.text:
        with open(os.path.join(os.getcwd(), "flex", "a_10mins_woman.txt"),
                  "r",
                  encoding='utf8') as jsonfile:
            json_object = json.load(jsonfile)
        FM = FlexSendMessage.new_from_json_dict(json_object)
        line_bot_api.reply_message(event.reply_token, FM)
        with open("flex/h_12mins_woman.json", "r",
                  encoding='utf8') as jsonfile:
            json_object = json.load(jsonfile)
        FM = FlexSendMessage.new_from_json_dict(json_object)
        line_bot_api.reply_message(event.reply_token, FM)
    #切換圖文選單=================================================================
    elif ('編輯紀錄') == (event.message.text):
        line_bot_api.link_rich_menu_to_user(user_id=user_id,
                                            rich_menu_id=rich_menu_id02)
    elif ('回主選單') in (event.message.text):
        line_bot_api.link_rich_menu_to_user(user_id=user_id,
                                            rich_menu_id=rich_menu_id01)

    #運動日誌-新增紀錄=================================================================
## 新增紀錄-1
# elif ('新增紀錄') == (event.message.text):
    elif (event.message.text) == ('新增紀錄'):
        textmessage = '請選擇運動日期~٩(๑❛ᴗ❛๑)۶'
        replydatepicker = buttons_templatenewdate(
            today, initial, max, min)  #\[TextSendMessage(text=textmessage)
        line_bot_api.reply_message(event.reply_token, [replydatepicker])

# 查詢紀錄-1 =>查詢/更新/刪除 =>選擇日期 flex.template_msg.buttons_template=>postback
#     elif ('查詢紀錄') or ('更新紀錄') or(' 刪除紀錄') in (event.message.text):
    elif ('查詢紀錄') == (event.message.text):
        line_bot_api.reply_message(
            event.reply_token,
            buttons_template(today, user_id, initial, max, min))
    elif ('更新紀錄') == (event.message.text):
        line_bot_api.reply_message(
            event.reply_token,
            buttons_template(today, user_id, initial, max, min))
    elif ('刪除紀錄') == (event.message.text):
        line_bot_api.reply_message(
            event.reply_token,
            buttons_template(today, user_id, initial, max, min))

# 目前狀態: (呈現本周運動次數&日誌)
    elif '目前狀態' == event.message.text:
        range = 7
        range, count, table, firstday, today = count_exercise(user_id, range)
        textmessage = f"{table}\n\n建議手機轉橫向查看表格(。・ω・。)"
        textmessage02 = f"{firstday}至\t{today}間\n您本周運動{count}次(*'ω'*)\n以上為本周運動日誌"
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text=textmessage),
            TextSendMessage(text=textmessage02)
        ])

    elif '不用了' == event.message.text:
        pass

### 運動日誌=================================================================
# 查詢紀錄 日期確認: database.usertable.checkdate(user_id)
    elif '對,確認查詢~' == event.message.text:
        startdate = checkdate(user_id)[1]
        enddate = checkdate(user_id)[2]
        table = search_exerciselog(user_id, startdate, enddate)
        textmessage = f" {startdate} 至  {enddate} 運動日誌:\n{table}\n建議手機轉橫向查看表格(。・ω・。)"

        text_quickreply0 = QuickReplyButton(
            action=MessageAction(label="更新紀錄", text="我要更新紀錄~"))
        text_quickreply1 = QuickReplyButton(
            action=MessageAction(label="刪除紀錄", text="我要刪除紀錄~"))
        text_quickreply2 = QuickReplyButton(
            action=MessageAction(label="不用了", text="不用了"))
        quick_reply_array = QuickReply(
            items=[text_quickreply0, text_quickreply1, text_quickreply2])
        reply_text_message = TextSendMessage(text=textmessage,
                                             quick_reply=quick_reply_array)
        line_bot_api.reply_message(event.reply_token, [reply_text_message])
        deletedate(user_id)
    elif '我要更新紀錄~' == event.message.text:
        textmessage = "請複製格式,並輸入該筆紀錄的id & 內容~~"
        textmessage02 = "**範例**\n更新=99(請填入id),內容:今天終於有時間運動惹~開心(*´∀`)♪(請填入日誌內容)"
        textmessage03 = "**格式**\n更新=,內容:"
        text_quickreply0 = QuickReplyButton(
            action=MessageAction(label="重新查詢", text="查詢紀錄"))
        text_quickreply1 = QuickReplyButton(
            action=MessageAction(label="回主選單", text="回主選單"))
        quick_reply_array = QuickReply(
            items=[text_quickreply0, text_quickreply1])
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text=textmessage02),
            TextSendMessage(text=textmessage03),
            TextSendMessage(text=textmessage, quick_reply=quick_reply_array)
        ])

    elif '我要刪除紀錄~' == event.message.text:
        textmessage = "請複製格式,並輸入該筆紀錄的id~~"
        textmessage02 = "**範例**\n刪除=99(請填入id)"
        textmessage03 = "**格式**\n刪除="
        text_quickreply0 = QuickReplyButton(
            action=MessageAction(label="重新查詢", text="查詢紀錄"))
        text_quickreply1 = QuickReplyButton(
            action=MessageAction(label="回主選單", text="回主選單"))
        quick_reply_array = QuickReply(
            items=[text_quickreply0, text_quickreply1])
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text=textmessage02),
            TextSendMessage(text=textmessage03),
            TextSendMessage(text=textmessage, quick_reply=quick_reply_array)
        ])

    elif '錯了,我想重新選擇日期~' == event.message.text:
        deletedate(user_id)
        textmessage = '請選擇運動日期~٩(๑❛ᴗ❛๑)۶'  # \[TextSendMessage(text=textmessage)
        line_bot_api.reply_message(event.reply_token,
                                   buttons_template(today, user_id))

# 查詢紀錄-2 日期確認
## 更新 / 刪除紀錄-2
# 當使用者輸入
    elif "更新=" in msg_content:
        if ",內容:" in msg_content:
            sep = msg_content.split(",內容:")
            id = sep[0].split("=")[1]
            record = sep[1]
            print("將更新的id&record:", id, record)
            textmessage = f"準備更新id={id}\n==新的日誌內容==\n{record}"
            textmessage02 = updatelog(user_id, id, record)
            text_quickreply0 = QuickReplyButton(
                action=MessageAction(label="重新查詢", text="查詢紀錄"))
            text_quickreply1 = QuickReplyButton(
                action=MessageAction(label="回主選單", text="回主選單"))
            quick_reply_array = QuickReply(
                items=[text_quickreply0, text_quickreply1])
            line_bot_api.reply_message(event.reply_token, [
                TextSendMessage(text=textmessage),
                TextSendMessage(text=textmessage02,
                                quick_reply=quick_reply_array)
            ])

        else:
            textmessage = f"格式錯誤Q^Q"
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=textmessage))

    elif "刪除=" in msg_content:
        id = msg_content.split("=")[1]
        print("將刪除的id:", id)
        date, record = search_onelog(user_id, id)
        textmessage = f"準備刪除id={id}\n日期{date}\n=原有日誌內容=\n{record}"
        textmessage02 = deletelog(user_id, id)
        text_quickreply0 = QuickReplyButton(
            action=MessageAction(label="重新查詢", text="查詢紀錄"))
        text_quickreply1 = QuickReplyButton(
            action=MessageAction(label="回主選單", text="回主選單"))
        quick_reply_array = QuickReply(
            items=[text_quickreply0, text_quickreply1])
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text=textmessage),
            TextSendMessage(text=textmessage02, quick_reply=quick_reply_array)
        ])

    ####檢查目前state的日期是什麼,把內容存進相對應的欄位中。
    ## 新增紀錄-2 放最底下不要亂移動XDD
    # 當使用者輸入運動日誌(msg_content)
    # 從usertable-state抓回日期: database.usertable.checkstate
    # 從database.exercise.updatecheck(user_id, date)確認 exercise的record欄位是不是空的,避免重複寫入
    # 詢問使用者是否更新
    # 無日期:結束 / 有日期:確認是否存取(quickreply 是/否) =>Postback
    else:
        state = checkstate(user_id)
        if "checkstate=Y" in state:
            date = state.split(",")[1]
            last_record = updatecheck(user_id, date)
            if str(last_record) == "None":
                print("還未寫入record過,詢問是否新增")
                text_quickreply0 = QuickReplyButton(action=PostbackAction(
                    label='是',
                    display_text='是',
                    data=f"update=Y,date={date},record={msg_content}"))
                text_quickreply1 = QuickReplyButton(action=PostbackAction(
                    label='否', display_text='否', data='update=N'))
                # 有空新增第三個按鈕:重新選擇日期
                quick_reply_array = QuickReply(
                    items=[text_quickreply0, text_quickreply1])
                reply_text_message = TextSendMessage(
                    f"{date}\n--------------------\n{msg_content}\n--------------------\n是否紀錄此筆日誌?",
                    quick_reply=quick_reply_array)
                line_bot_api.reply_message(event.reply_token,
                                           [reply_text_message])
            else:
                print("已經有日誌,詢問是否更新?")
                text_quickreply0 = QuickReplyButton(action=PostbackAction(
                    label='是',
                    display_text='是',
                    data=f"update=Y,date={date},record={msg_content}"))
                text_quickreply1 = QuickReplyButton(action=PostbackAction(
                    label='否', display_text='否', data='update=N'))
                # 有空新增第三個按鈕:重新選擇日期
                quick_reply_array = QuickReply(
                    items=[text_quickreply0, text_quickreply1])
                reply_text_message = TextSendMessage(
                    f"原本已經有紀錄\n{date}\n--------------------\n{last_record}\n--------------------\n是否覆蓋並更新此筆日誌,如下?\n{date}\n--------------------\n{msg_content}\n--------------------\n ",
                    quick_reply=quick_reply_array)
                line_bot_api.reply_message(event.reply_token,
                                           [reply_text_message])

    return "message_event done"
Exemplo n.º 17
0
def adjust_ranking(ratings, member_info, action, event, designated_target=None):
    '''
    ** event example **
    {"message": {"id": "9760259091048", "text": "text text", "type": "text"},
     "replyToken": "4b35e226593e42a7ba0f53fd34b4a71b",
     "source": {"groupId": "C96673d1530d37de2b0a8ffc2e5df5f1f",
                "type": "group",
                "userId": "U13990d12ea3aa82eef9e01fcea9a963f"},
     "timestamp": 1556272465993, "type": "message"}
     '''

    splitted = event.message.text.split()

    if len(splitted) < 2:
        app.logger.warn('too short message to promote/demote')
        return

    if len(splitted) >= 3:
        target = splitted[1:-1]
        target = ' '.join(target)
        ranking_title = splitted[-1]

    if len(splitted) == 2:
        target = random.choice(tuple(ratings.keys()))
        ranking_title = splitted[-1]

    if target == '랜덤':
        target = random.choice(tuple(ratings.keys()))

    group_id, user_id = event.source.group_id, event.source.user_id
    if action == 'special_promote':
        profile = line_bot_api.get_group_member_profile(group_id, user_id)
        self_target = '@' + profile.display_name
        rank = list(ratings.keys()).index(self_target)
        if rank != 0:
            message_text = '랭킹 1위만 사면이 가능합니다'
            text_message = TextSendMessage(text=message_text)
            messages = [text_message]
            line_bot_api.reply_message(event.reply_token, messages)
            return

    if designated_target is not None:
        try:
            target = tuple(ratings.keys())[designated_target]
        except ValueError as e:
            app.logger.error(e)
            target = random.choice(tuple(ratings.keys()))

    try:
        rank = list(ratings.keys()).index(target)
    except ValueError as e:
        app.logger.error(e)
        rank = 10
    mod = calculate_mod(member_info, user_id)

    message = ''
    special = ''
    old_rating = ''
    moved_steps = ''
    if action in ('demote', 'super_demote'):
        if action == 'super_demote':
            success, message, special = roll(mod, max(1, 13-rank+5))
        else:
            success, message, special = roll(mod, max(1, 13-rank))

        if not success:
            profile = line_bot_api.get_group_member_profile(group_id, user_id)
            target = '@' + profile.display_name

        if target in ratings:
            old_rating = ratings[target]
        ratings[target] = ranking_title

        idx = list(ratings.keys()).index(target)
        move_index = min(idx + 1, len(ratings)-1)
        if special in ('critical', 'fumble') or action == 'super_demote':
            move_index = len(ratings)-1

        moved_steps = moved_step_str(idx, move_index)

        rating_list = list(ratings.items())
        target_item = rating_list[idx]
        rating_list = rating_list[:idx] + rating_list[idx+1:]
        rating_list.insert(move_index, target_item)
        ratings.clear()
        for k, v in rating_list:
            ratings[k] = v

    if action in ('promote', 'special_promote'):
        success, message, special = roll(mod, max(1, 13-rank), action == 'special_promote')

        if not success:
            profile = line_bot_api.get_group_member_profile(group_id, user_id)
            target = '@' + profile.display_name

        if target in ratings:
            old_rating = ratings[target]
        ratings[target] = ranking_title

        idx = list(ratings.keys()).index(target)
        move_index = max(idx - 1, 0)
        if special == 'critical':
            move_index = 0
        if not success:
            move_index = min(idx + 1, len(ratings)-1)

        moved_steps = moved_step_str(idx, move_index)

        rating_list = list(ratings.items())
        target_item = rating_list[idx]
        rating_list = rating_list[:idx] + rating_list[idx+1:]
        rating_list.insert(move_index, target_item)
        ratings.clear()
        for k, v in rating_list:
            ratings[k] = v

    message = ratings_to_message(ratings, target, old_rating, moved_steps) + '\n' + message
    text_message = TextSendMessage(text=message)
    messages = [text_message]
    if special in ('critical', 'fumble'):
        special_image = get_special_images(special)
        message = ImageSendMessage(
                original_content_url=special_image, preview_image_url=special_image)
        messages.append(message)

    try:
        line_bot_api.reply_message(event.reply_token, messages)
    except linebot.exceptions.LineBotApiError as e:
        app.logger.error(e)
        app.logger.error(f'image: {special_image}')
Exemplo n.º 18
0
def tell_price(event):
    rand = random.random
    price = int(sum((rand(), rand(), rand(), rand()))/4.0 * 100000) / 100.0
    message = f'{EMOJI_COIN} 싱무연코인(SMC) 현재 가격: {price}'
    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message))