Example #1
0
# line bot test
# require: pip install line-bot-sdk

import yaml
from linebot import LineBotApi
from linebot.models import TextSendMessage
from linebot.exceptions import LineBotApiError

# config読み込み
with open("./conf/config.yml", mode='r', encoding="utf-8") as f:
    config = yaml.safe_load(f)

# 定数定義
line_access_token = config["default"]["line_access_token"]
line_user_id = config["default"]["line_user_id"]

# インスタンス生成
line_bot_api = LineBotApi(line_access_token)

# 投稿内容
text_message = "test message"

try:
    # ラインユーザIDは配列で指定する。
    line_bot_api.multicast([line_user_id], TextSendMessage(text=text_message))
except LineBotApiError as e:
    # エラーが起こり送信できなかった場合
    print(e)
Example #2
0
def send_text_message(reply_token, text):
    line_bot_api = LineBotApi(channel_access_token)
    line_bot_api.reply_message(reply_token, TextSendMessage(text=text))

    return "OK"
def connect_liveagent(line_id):
    session = get_liveagent_session(line_id)
    profile = get_profile(line_id)
    url = st.LIVEAGENT_HOST + '/chat/rest/Chasitor/ChasitorInit'
    headers = {
        'X-LIVEAGENT-API-VERSION': st.LIVEAGENT_API_VERSION,
        'X-LIVEAGENT-AFFINITY': session.get('affinity_token'),
        'X-LIVEAGENT-SESSION-KEY': session.get('key'),
        'X-LIVEAGENT-SEQUENCE': str(session.get('sequence')),
    }
    post_data = {
        'organizationId':
        st.LIVEAGENT_ORGANIZATION_ID,
        'deploymentId':
        st.LIVEAGENT_DEPLOYMENT_ID,
        'buttonId':
        st.LIVEAGENT_BUTTON_ID,
        'sessionId':
        session.get('liveagent_id'),
        'userAgent':
        st.LIVEAGENT_USER_AGENT,
        'language':
        'ja',
        'trackingId':
        '',
        'screenResolution':
        '',
        'visitorName':
        profile.display_name,
        'isPost':
        True,
        'receiveQueueUpdates':
        True,
        'buttonOverrides': [],
        'prechatDetails': [
            {
                'label': 'ContactLineId',
                'value': session.get('line_id'),
                'entityMaps': [],
                'transcriptFields': [],
                'displayToAgent': True,
                'doKnowledgeSearch': False
            },
        ],
        'prechatEntities': [{
            'entityName':
            'Contact',
            'showOnCreate':
            False,
            'linkToEntityName':
            None,
            'linkToEntityField':
            None,
            'saveToTranscript':
            'ContactId',
            'entityFieldsMaps': [{
                'fieldName': 'LINE_ID__c',
                'label': 'ContactLineId',
                'doFind': True,
                'isExactMatch': True,
                'doCreate': False,
            }]
        }],
    }
    r = requests.post(url, json=post_data, headers=headers)
    if r.status_code == 200:
        LiveagentSession.update_session({
            'line_id':
            line_id,
            'sequence':
            str(session.get('sequence') + 1),
        })
        url = st.LIVEAGENT_HOST + '/chat/rest/System/Messages'
        headers = {
            'X-LIVEAGENT-API-VERSION': st.LIVEAGENT_API_VERSION,
            'X-LIVEAGENT-AFFINITY': session.get('affinity_token'),
            'X-LIVEAGENT-SESSION-KEY': session.get('key'),
        }
        r = requests.get(url,
                         headers=headers,
                         params={'ack': session.get('ack', -1)})
        try:
            result = None
            res_type = None
            if r.status_code == 200:
                body = json.loads(r.text)
                for message in body.get('messages'):
                    res_type, result = process_message(message)

                if res_type == 'end' or res_type == 'fail':
                    LiveagentSession.delete_session(line_id)
                    if result is not None:
                        line_bot_api.push_message(line_id,
                                                  TextSendMessage(text=result))

                else:
                    LiveagentSession.update_session({
                        'line_id': line_id,
                        'ack': body.get('sequence'),
                        'responder': 'LIVEAGENT',
                    })

            elif r.status_code == 204:
                LiveagentSession.delete_session(line_id)

            return True

        except:
            return False

    else:
        LiveagentSession.delete_session(line_id)
        return False
 def publish_by_manual(self, message):
     self.get_user_list()
     for user in self.user_list:
         self.line_bot_api.push_message(user, TextSendMessage(text=message))
def notifyoff(event): #刪除作業
    line_bot_api.reply_message(event.reply_token,TextSendMessage(text="通知功能已關閉"))
Example #6
0
def handle_message(event):
    # 回應使用者輸入的話
    line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Hi'))
Example #7
0
def handle_message(event):
    # DataFrameを定義
    artist_df = pd.DataFrame(columns=[
        'artist_name', 'artist_ID', 'genre', 'popularity',
        'related_artist_names'
    ])
    # 入力されたアーティスト名から情報を取得
    name = event.message.text
    spotapi_out = spotify.search(q='artist:' + name, type='artist')
    try:
        artist_items = spotapi_out['artists']['items'][0]
        artist_id = artist_items['id']
        artid_list = [artist_id]
        artname_related_list = []
        spotapi_out_related = spotify.artist_related_artists(artist_id)
        for artname_related in spotapi_out_related['artists']:
            artname_related_list.append(artname_related['name'])
        s = pd.Series([
            artist_items['name'], artist_items['id'], artist_items['genres'],
            artist_items['popularity'], artname_related_list
        ],
                      index=artist_df.columns)
        artist_df = artist_df.append(s, ignore_index=True)

        # 関連アーティストを探す
        artid_list_tail = 0
        for i in range(1):
            artid_list_head = artid_list_tail
            artid_list_tail = len(artid_list)
            for artid in artid_list[artid_list_head:artid_list_tail]:
                spotapi_out = spotify.artist_related_artists(artid)
                for artid_related in spotapi_out['artists']:
                    artist_df_bool = artist_df['artist_ID'] == artid_related[
                        'id']
                    if artist_df_bool.sum(
                    ) == 0 and artid_related['popularity'] >= 10:
                        # 類似のアーティストリストを作成
                        spotapi_out_related = spotify.artist_related_artists(
                            artid_related['id'])
                        artname_related2_list = []
                        for artname_related2 in spotapi_out_related['artists']:
                            artname_related2_list.append(
                                artname_related2['name'])
                        artid_list.append(artid_related['id'])
                        s = pd.Series([
                            artid_related['name'], artid_related['id'],
                            artid_related['genres'],
                            artid_related['popularity'], artname_related2_list
                        ],
                                      index=artist_df.columns)
                        artist_df = artist_df.append(s, ignore_index=True)

        # アーティストの関係の辞書を作る
        plt.figure(figsize=(16, 16))
        artdic = {}
        for i in range(len(artid_list)):
            artdic[artist_df.iloc[i, 0]] = []
        for i in range(len(artid_list)):
            for artname_related in artist_df.iloc[i, 4]:
                artdic[artist_df.iloc[i, 0]].append(artname_related)

        # 図の書き出し
        G = nx.DiGraph()
        nx.add_path(G, artdic)
        # pos = nx.spring_layout(G, k=0.3)
        pos = nx.circular_layout(G)
        pr = nx.pagerank(G)

        def calc_inverse(n):
            return 1 / n

        nx.draw_networkx_nodes(G,
                               pos,
                               alpha=.6,
                               node_color=list(
                                   map(calc_inverse, list(pr.values()))),
                               cmap=plt.cm.GnBu,
                               node_size=[200 * (1 / v) for v in pr.values()])
        datas = nx.draw_networkx_labels(G,
                                        pos,
                                        font_size=14,
                                        font_weight="bold")
        nx.draw_networkx_edges(G, pos, alpha=1, edge_color="c")
        for t in datas.values():
            t.set_fontproperties(fontprop)

        plt.axis("off")

        image_path = "static/images/image.jpg"
        plt.savefig(image_path)

        image_message = ImageSendMessage(
            original_content_url=
            f"https://fusafmusicbot.herokuapp.com/{image_path}",
            preview_image_url=
            f"https://fusafmusicbot.herokuapp.com/{image_path}")

        genres = ', '.join(artist_items['genres'])

        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text=name + 'が好きなんだ~'),
            TextSendMessage(text='ジャンルは' + genres + 'だね'), image_message,
            TextSendMessage(text='関連性の高いアーティストはこんな感じ!')
        ])
    except IndexError:
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text=name +
                            'ってアーティストは登録されていないみたい\n(英語で登録されている場合もあるよ)'),
            TextSendMessage(text='ほかには何が好き?'),
        ])
Example #8
0
def message2():
    try:
        line_bot_api.push_message(LINE_USER_ID_TO, TextSendMessage(url))
    except LineBotApiError as e:
        print(e)
Example #9
0
def handle_text_message(event):
    question = event.message.text
    answer = request_api(question)
    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=answer))
Example #10
0
def handle_text_message(event):
    text = event.message.text
    userID = event.source.user_id
    profile = line_bot_api.get_profile(event.source.user_id)
    keyword_match_output = []
    for x in rules_db.find():
        if x['keyword'] in text:
            keyword_match_output.append(x)
    try:
        groupID = event.source.group_id
    except:
        groupID = 'No groupID'
    log_info = {
        "userID": userID,
        "messageID": event.message.id,
        "text": text,
        "message_type": event.message.type,
        "source_type": event.source.type,
        "datetime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        "groupID": groupID
    }
    log_db.insert_one(log_info)

    if text == '報到':

        if isinstance(event.source, SourceGroup):
            user_data = users_db.find({}, {"userID": 1, "groupID": 1})
            user_match_output = userID in user_data
            group_match_output = groupID in user_data
            if user_match_output == False and group_match_output == False:
                user_info = {
                    "groupID":
                    groupID,
                    "userID":
                    userID,
                    "display_name":
                    profile.display_name,
                    "picture_url":
                    profile.picture_url,
                    "status_message":
                    profile.status_message,
                    "join_datetime":
                    time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                }
                users_db.insert_one(user_info)
                line_bot_api.reply_message(event.reply_token, [
                    TextSendMessage(text=profile.display_name + '的資料登記完成!'),
                ])
            else:
                line_bot_api.reply_message(event.reply_token, [
                    TextSendMessage(text=profile.display_name + '的資料已經登記過了喔!'),
                ])
        else:
            line_bot_api.reply_message(
                event.reply_token, TextSendMessage(text="資料登記失敗,請聯絡老師或助教!!"))
    elif len(keyword_match_output) != 0:
        # function for exec
        def func():
            exec(rule_string)

        for rule_data in keyword_match_output:
            rule_string = str(rule_data['rule'])
            func()
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text='觸發規則!'))
    elif text == '下載報告':
        download_info = create_zip(tags='report', resource_type='raw')
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=download_info['url']))
    elif re.match(r'([0-9]+)-([^0-9]+)-(點名)', text) != None:
        rollcall_info = {
            "userID": userID,
            "messageID": event.message.id,
            "text": text,
            "message_type": event.message.type,
            "source_type": event.source.type,
            "datetime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            "groupID": groupID
        }
        rollcall_db.insert_one(rollcall_info)
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text=profile.display_name + '點名成功!'))
    elif text == 'help':
        content = '功能說明:\n輸入「報到」進行群組內成員資料登記\n\n點名格式(數字-姓名-點名)\nex:10312345-王小明-點名\n\n上傳檔案網址:\nhttps://ai1082.herokuapp.com'
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=content))
    else:
        pass
    '''
Example #11
0
def push_text_message(text):
    message = TextSendMessage(text=text)
    line_bot_api.push_message(nohara_first_id, message)
Example #12
0
def send_message(token, message):
    line_bot_api.reply_message(
        token,
        TextSendMessage(text=message)
    )
Example #13
0
def sendFlex(event):  #彈性配置
    try:
        bubble = BubbleContainer(
            direction='ltr',  #項目由左向右排列
            header=BoxComponent(  #標題
                layout='vertical',
                contents=[
                    TextComponent(text='冰火飲料', weight='bold', size='xxl'),
                ]),
            hero=ImageComponent(  #主圖片
                url='https://i.imgur.com/3sBRh08.jpg',
                size='full',
                aspect_ratio='792:555',  #長寬比例
                aspect_mode='cover',
            ),
            body=BoxComponent(  #主要內容
                layout='vertical',
                contents=[
                    TextComponent(text='評價', size='md'),
                    BoxComponent(
                        layout='baseline',  #水平排列
                        margin='md',
                        contents=[
                            IconComponent(
                                size='lg',
                                url='https://i.imgur.com/GsWCrIx.png'),
                            TextComponent(text='25   ',
                                          size='sm',
                                          color='#999999',
                                          flex=0),
                            IconComponent(
                                size='lg',
                                url='https://i.imgur.com/sJPhtB3.png'),
                            TextComponent(text='14',
                                          size='sm',
                                          color='#999999',
                                          flex=0),
                        ]),
                    BoxComponent(
                        layout='vertical',
                        margin='lg',
                        contents=[
                            BoxComponent(
                                layout='baseline',
                                contents=[
                                    TextComponent(text='營業地址:',
                                                  color='#aaaaaa',
                                                  size='sm',
                                                  flex=2),
                                    TextComponent(text='台北市信義路14號',
                                                  color='#666666',
                                                  size='sm',
                                                  flex=5)
                                ],
                            ),
                            SeparatorComponent(color='#0000FF'),
                            BoxComponent(
                                layout='baseline',
                                contents=[
                                    TextComponent(text='營業時間:',
                                                  color='#aaaaaa',
                                                  size='sm',
                                                  flex=2),
                                    TextComponent(text="10:00 - 23:00",
                                                  color='#666666',
                                                  size='sm',
                                                  flex=5),
                                ],
                            ),
                        ],
                    ),
                    BoxComponent(layout='horizontal',
                                 margin='xxl',
                                 contents=[
                                     ButtonComponent(
                                         style='primary',
                                         height='sm',
                                         action=URIAction(
                                             label='電話聯絡',
                                             uri='tel:0987654321'),
                                     ),
                                     ButtonComponent(
                                         style='secondary',
                                         height='sm',
                                         action=URIAction(
                                             label='查看網頁',
                                             uri="http://www.e-happy.com.tw"))
                                 ])
                ],
            ),
            footer=BoxComponent(  #底部版權宣告
                layout='vertical',
                contents=[
                    TextComponent(text='Copyright@ehappy studio 2019',
                                  color='#888888',
                                  size='sm',
                                  align='center'),
                ]),
        )
        message = FlexSendMessage(alt_text="彈性配置範例", contents=bubble)
        line_bot_api.reply_message(event.reply_token, message)
    except:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text='發生錯誤!'))
Example #14
0
def handle_message(event):
    event_type = event.source.type
    if event_type == 'user':
        sender_id = event.source.user_id

    elif event_type == 'group':
        sender_id = event.source.group_id

    elif event_type == 'room':
        sender_id = event.source.room_id

    sender = Status.query.filter_by(line_id=sender_id).one()

    print(sender_id)
    if sender.line_status == 0:
        if event.message.text == "登録":
            status = 1
            message = TextSendMessage(
                text="使用者の名前とラズパイIDを「、」区切りで入力してください\n(例)おばあちゃん、12345")

        elif event.message.text == "削除":
            raspis = User.query.filter_by(line_id=sender_id).all()

            if raspis == []:
                text = "登録しているラズパイはありません"
                status = 0
            else:
                text = "削除したいラズパイIDを入力してください\n登録しているラズパイ一覧"
                for raspi in raspis:
                    text += ("\n名前:" + raspi.user_name + " ラズパイID:" +
                             raspi.raspi_id)
                status = 2

            message = TextSendMessage(text=text)

        elif event.message.text == "確認":
            raspis = User.query.filter_by(line_id=sender_id).all()

            if raspis == []:
                text = "登録しているラズパイはありません"
            else:
                text = "登録しているラズパイ一覧"
                for raspi in raspis:
                    text += ("\n名前:" + raspi.user_name + " ラズパイID:" +
                             raspi.raspi_id)

            status = 0
            message = TextSendMessage(text=text)

        elif event.message.text == "バイバイ":
            if event_type == 'group':
                User.query.filter(User.line_id == sender_id).delete()
                db.session.commit()
                line_bot_api.leave_group(sender_id)
                return
            elif event_type == 'room':
                User.query.filter(User.line_id == sender_id).delete()
                db.session.commit()
                line_bot_api.leave_room(sender_id)
                return

        else:
            status = 0
            text = "ラズパイIDを登録したいときは「登録」\n確認したいときは「確認」\n削除したいときは「削除」"
            if event_type == 'group' or event_type == 'room':
                text += "\n退会させたい時は「バイバイ」"
            text += "\nと入力してください"

            message = TextSendMessage(text=text)

    elif sender.line_status == 1:
        raspi = event.message.text.split('、')

        if len(raspi) == 2:
            new_user = User(line_id=sender_id,
                            user_name=raspi[0],
                            raspi_id=raspi[1])
            db.session.add(new_user)
            db.session.commit()

            message = TextSendMessage(text="名前:" + raspi[0] + "\nラズパイID:" +
                                      raspi[1] + "\nで登録されました")
        else:
            message = TextSendMessage(text="指定した形で入力してください")

        status = 0

    elif sender.line_status == 2:
        raspis = User.query.filter_by(line_id=sender_id).all()
        text = event.message.text + "は登録されていません"

        for raspi in raspis:
            if raspi.raspi_id == event.message.text:
                User.query.filter(User.raspi_id == event.message.text).delete()
                db.session.commit()
                text = event.message.text + "を削除しました"

        status = 0
        message = TextSendMessage(text=text)

    else:
        return

    sender.line_status = status
    db.session.commit()

    line_bot_api.reply_message(event.reply_token, message)
Example #15
0
def send_line_msg(msg):
    
    line_bot_api = LineBotApi("your linebot api")
    line_bot_api.broadcast(TextSendMessage(text=msg))
Example #16
0
def handle_follow(event):
	line_bot_api.reply_message(
		event.reply_token, TextSendMessage(text='Got follow event'))
Example #17
0
def process_text_message(event):
    global i_dict
    global app
    global one

    for i in range(4):
        one[i] = int(one[i])

    if event.message.text == '我想要親自玩玩看!':
        i_dict[event.source.user_id] = random.randint(1, 6)
        app = Flask(__name__,
                    static_url_path="/素材" + str(i_dict[event.source.user_id]),
                    static_folder="./素材" + str(i_dict[event.source.user_id]) +
                    "/")

    if event.message.text == '印出i_dict':
        line_bot_api.reply_message(
            event.reply_token,
            [TextSendMessage(text=str(i_dict[event.source.user_id]))])

    if event.message.text == '我想要知道目前的勝率!':
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text="所有玩家目前選了" + str(one[0]) + "次換門,共贏了" +
                            str(one[2]) + "次,勝率是" + '%.0f%%' %
                            (one[2] / one[0] * 100) + "。\n所有玩家目前選了" +
                            str(one[1]) + "次不換門,共贏了" + str(one[3]) + "次,勝率是" +
                            '%.0f%%' % (one[3] / one[1] * 100) + "。")
        ])

    if i_dict[event.source.
              user_id] == 1 and event.message.text == '我不換,堅持選擇左邊的門。':
        one[1] += 1
        one[3] += 1

    if i_dict[event.source.
              user_id] == 1 and event.message.text == '我要換,改成選擇右邊的門。':
        one[0] += 1

    if i_dict[event.source.
              user_id] == 1 and event.message.text == '我要換,改成選擇左邊的門。':
        one[0] += 1
        one[2] += 1

    if i_dict[event.source.
              user_id] == 1 and event.message.text == '我不換,堅持選擇中間的門。':
        one[1] += 1

    if i_dict[event.source.
              user_id] == 1 and event.message.text == '我不換,堅持選擇右邊的門。':
        one[1] += 1

    if i_dict[event.source.
              user_id] == 2 and event.message.text == '我不換,堅持選擇左邊的門。':
        one[1] += 1
        one[3] += 1

    if i_dict[event.source.
              user_id] == 2 and event.message.text == '我要換,改成選擇左邊的門。':
        one[0] += 1
        one[2] += 1

    if i_dict[event.source.
              user_id] == 2 and event.message.text == '我不換,堅持選擇中間的門。':
        one[1] += 1

    if i_dict[event.source.
              user_id] == 2 and event.message.text == '我不換,堅持選擇右邊的門。':
        one[1] += 1

    if i_dict[event.source.
              user_id] == 2 and event.message.text == '我要換,改成選擇中間的門。':
        one[0] += 1

    if i_dict[event.source.
              user_id] == 3 and event.message.text == '我不換,堅持選擇左邊的門。':
        one[1] += 1

    if i_dict[event.source.
              user_id] == 3 and event.message.text == '我不換,堅持選擇中間的門。':
        one[1] += 1
        one[3] += 1

    if i_dict[event.source.
              user_id] == 3 and event.message.text == '我不換,堅持選擇右邊的門。':
        one[1] += 1

    if i_dict[event.source.
              user_id] == 3 and event.message.text == '我要換,改成選擇中間的門。':
        one[0] += 1
        one[2] += 1

    if i_dict[event.source.
              user_id] == 3 and event.message.text == '我要換,改成選擇右邊的門。':
        one[0] += 1

    if i_dict[event.source.
              user_id] == 4 and event.message.text == '我不換,堅持選擇左邊的門。':
        one[1] += 1

    if i_dict[event.source.
              user_id] == 4 and event.message.text == '我不換,堅持選擇中間的門。':
        one[1] += 1
        one[3] += 1

    if i_dict[event.source.
              user_id] == 4 and event.message.text == '我不換,堅持選擇右邊的門。':
        one[1] += 1

    if i_dict[event.source.
              user_id] == 4 and event.message.text == '我要換,改成選擇中間的門。':
        one[0] += 1
        one[2] += 1

    if i_dict[event.source.
              user_id] == 4 and event.message.text == '我要換,改成選擇左邊的門。':
        one[0] += 1

    if i_dict[event.source.
              user_id] == 5 and event.message.text == '我不換,堅持選擇左邊的門。':
        one[1] += 1

    if i_dict[event.source.
              user_id] == 5 and event.message.text == '我不換,堅持選擇中間的門。':
        one[1] += 1

    if i_dict[event.source.
              user_id] == 5 and event.message.text == '我不換,堅持選擇右邊的門。':
        one[1] += 1
        one[3] += 1

    if i_dict[event.source.
              user_id] == 5 and event.message.text == '我要換,改成選擇中間的門。':
        one[0] += 1

    if i_dict[event.source.
              user_id] == 5 and event.message.text == '我要換,改成選擇右邊的門。':
        one[0] += 1
        one[2] += 1

    if i_dict[event.source.
              user_id] == 6 and event.message.text == '我不換,堅持選擇左邊的門。':
        one[1] += 1

    if i_dict[event.source.
              user_id] == 6 and event.message.text == '我不換,堅持選擇中間的門。':
        one[1] += 1

    if i_dict[event.source.
              user_id] == 6 and event.message.text == '我不換,堅持選擇右邊的門。':
        one[1] += 1
        one[3] += 1

    if i_dict[event.source.
              user_id] == 6 and event.message.text == '我要換,改成選擇左邊的門。':
        one[0] += 1

    if i_dict[event.source.
              user_id] == 6 and event.message.text == '我要換,改成選擇右邊的門。':
        one[0] += 1
        one[2] += 1

    # 讀取本地檔案,並轉譯成消息
    result_message_array = []
    replyJsonPath = "素材" + str(i_dict[
        event.source.user_id]) + "/" + event.message.text + "/reply.json"
    result_message_array = detect_json_array_to_new_message_array(
        replyJsonPath)

    # 發送
    line_bot_api.reply_message(event.reply_token, result_message_array)
Example #18
0
def handle_join(event):
	line_bot_api.reply_message(
		event.reply_token,
		TextSendMessage(text='Hi, my name is Reika. Hope we can make some fun in this ' + event.source.type))
Example #19
0
def handle_follow(event):
    line_bot_api.reply_message(event.reply_token,
                               TextSendMessage(text='好きなアーティスト名を教えてくれ'))
Example #20
0
def handle_beacon(event):
	line_bot_api.reply_message(
		event.reply_token,
		TextSendMessage(
			text='Got beacon event. hwid={}, device_message(hex string)={}'.format(
				event.beacon.hwid, event.beacon.dm)))
Example #21
0
def handle_message(event):
    line_bot_api.reply_message(event.reply_token,
                               TextSendMessage(text=event.message.text))
Example #22
0
def handle_text_message(event):

	text=event.message.text
	
	if isinstance(event.source, SourceGroup):
		subject = line_bot_api.get_group_member_profile(event.source.group_id,
														event.source.user_id)
		set_id = event.source.group_id
	elif isinstance(event.source, SourceRoom):
		subject = line_bot_api.get_room_member_profile(event.source.room_id,
                                                   event.source.user_id)
		set_id = event.source.room_id
	else:
		subject = line_bot_api.get_profile(event.source.user_id)
		set_id = event.source.user_id
	
	def split1(text):
		return text.split('/wolfram ', 1)[-1]
		
	def split2(text):
		return text.split('/kbbi ', 1)[-1]
		
	def split3(text):
		return text.split('/echo ', 1)[-1]

	def split4(text):
		return text.split('/wolframs ', 1)[-1]
	
	def split5(text):
		return text.split('/trans ', 1)[-1]
	
	def split6(text):
		return text.split('/wiki ', 1)[-1]
	
	def split7(text):
		return text.split('/wikilang ', 1)[-1]
		
	def split8(text):
		return text.split('/urban ', 1)[-1]

	def split9(text):
		return text.split('/ox ', 1)[-1]
		
	def ox(keyword):
		oxdict_appid = ('7dff6c56')
		oxdict_key = ('41b55bba54078e9fb9f587f1b978121f')
		
		word = quote(keyword)
		url = ('https://od-api.oxforddictionaries.com:443/api/v1/entries/en/{}'.format(word))
		req = requests.get(url, headers={'app_id': oxdict_appid, 'app_key': oxdict_key})
		if "No entry available" in req.text:
			return 'No entry available for "{}".'.format(word)

		req = req.json()
		result = ''
		i = 0
		for each_result in req['results']:
			for each_lexEntry in each_result['lexicalEntries']:
				for each_entry in each_lexEntry['entries']:
					for each_sense in each_entry['senses']:
						if 'crossReferenceMarkers' in each_sense:
							search = 'crossReferenceMarkers'
						else:
							search = 'definitions'
						for each_def in each_sense[search]:
							i += 1
							result += '\n{}. {}'.format(i, each_def)

		if i == 1:
			result = 'Definition of {}:\n'.format(keyword) + result[4:]
		else:
			result = 'Definitions of {}:'.format(keyword) + result
		return result

	
	def wolfram(query):
		wolfram_appid = ('83L4JP-TWUV8VV7J7')

		url = 'https://api.wolframalpha.com/v2/result?i={}&appid={}'
		return requests.get(url.format(quote(query), wolfram_appid)).text
		
	def wolframs(query):
		wolfram_appid = ('83L4JP-TWUV8VV7J7')

		url = 'https://api.wolframalpha.com/v2/simple?i={}&appid={}'
		return url.format(quote(query), wolfram_appid)
	
	def trans(word):
		sc = 'en'
		to = 'id'
		
		if word[0:].lower().strip().startswith('sc='):
			sc = word.split(', ', 1)[0]
			sc = sc.split('sc=', 1)[-1]
			word = word.split(', ', 1)[1]
	
		if word[0:].lower().strip().startswith('to='):
			to = word.split(', ', 1)[0]
			to = to.split('to=', 1)[-1]
			word = word.split(', ', 1)[1]
			
		if word[0:].lower().strip().startswith('sc='):
			sc = word.split(', ', 1)[0]
			sc = sc.split('sc=', 1)[-1]
			word = word.split(', ', 1)[1]
			
		return translator.translate(word, src=sc, dest=to).text
		
	def wiki_get(keyword, set_id, trim=True):
    
		try:
			wikipedia.set_lang(wiki_settings[set_id])
		except KeyError:
			wikipedia.set_lang('en')

		try:
			result = wikipedia.summary(keyword)

		except wikipedia.exceptions.DisambiguationError:
			articles = wikipedia.search(keyword)
			result = "{} disambiguation:".format(keyword)
			for item in articles:
				result += "\n{}".format(item)
		except wikipedia.exceptions.PageError:
			result = "{} not found!".format(keyword)

		else:
			if trim:
				result = result[:2000]
				if not result.endswith('.'):
					result = result[:result.rfind('.')+1]
		return result
		
	def wiki_lang(lang, set_id):
    
		langs_dict = wikipedia.languages()
		if lang in langs_dict.keys():
			wiki_settings[set_id] = lang
			return ("Language has been changed to {} successfully."
					.format(langs_dict[lang]))

		return ("{} not available!\n"
				"See meta.wikimedia.org/wiki/List_of_Wikipedias for "
				"a list of available languages, and use the prefix "
				"in the Wiki column to set the language."
				.format(lang))	
	
	def find_kbbi(keyword, ex=True):

		try:
			entry = KBBI(keyword)
		except KBBI.TidakDitemukan as e:
			result = str(e)
		else:
			result = "Definisi {}:\n".format(keyword)
			if ex:
				result += '\n'.join(entry.arti_contoh)
			else:
				result += str(entry)
		return result
	
	def urban(keyword, ex=True):
		
		try:
			entry = udtop(keyword)
		except (TypeError, AttributeError, udtop.TermNotFound) :
			result = "{} definition not found in urbandictionary.".format(keyword)
		else:
			result = "{} definition:\n".format(keyword)
			if ex:
				result += str(entry)
			else:
				result += entry.definition
		return result
	
	if text == '/help':
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage('I will be here for you'))
	
	elif text == '/leave':
		if isinstance(event.source, SourceGroup):
			line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('I am leaving the group...'))
			line_bot_api.leave_group(event.source.group_id)
		
		elif isinstance(event.source, SourceRoom):
			line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('I am leaving the group...'))
			line_bot_api.leave_room(event.source.room_id)
			
		else:
			line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('>_< cannot do...'))
	
	elif text == '/about':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("Hello, my name is Reika \n"
								"Nice to meet you... \n"
								"source code: https://github.com/Vetrix/ZERO"))
	
	elif text == '/cmd':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("Without parameters: \n"
								"/about, /help, /profile, /leave, /lang \n"
								"/confirm, /buttons, /search image, \n"
								"/manga, /dots, /track, /bet \n"
								"/image_carousel, /imagemap \n"
								"\n"
								"With parameters: \n"
								"/echo, /kbbi, /wolfram, /wolframs, \n"
								"/trans, /wiki, /wikilang, /urban, /ox"))
	
	elif text == '/lang':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("Language for translation see here \n"
								"https://github.com/Vetrix/ZERO/blob/master/Lang.txt"))
	
	elif text == '/manga':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("mangaku.in"))
	
	elif text == '/dots':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("https://www.instagram.com/dotaindonesia2/"))
	
	elif text == '/track':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("http://dota2.prizetrac.kr/international2018"))
	
	elif text == '/bet':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("dota2.com/predictions"))
	
	elif text == '/search image':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("Try this up \n"
								"https://reverse.photos/"))
	
	elif text == '/profile':
		if isinstance(event.source, SourceGroup):
			try:
				profile = line_bot_api.get_group_member_profile(event.source.group_id, event.source.user_id)
				result = ("Display name: " + profile.display_name + "\n" +
						  "Profile picture: " + profile.picture_url + "\n" +
						  "User_ID: " + profile.user_id)
			except LineBotApiError:
				pass	
			line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage(result))
			
		
		elif isinstance(event.source, SourceRoom):
			try:
				profile = line_bot_api.get_room_member_profile(event.source.room_id, event.source.user_id)
				result = ("Display name: " + profile.display_name + "\n" +
						  "Profile picture: " + profile.picture_url + "\n" +
						  "User_ID: " + profile.user_id)
			except LineBotApiError:
				pass	
			line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage(result))
			
				
		else:
			try:
				profile = line_bot_api.get_profile(event.source.user_id)
				result = ("Display name: " + profile.display_name + "\n" +
						  "Profile picture: " + profile.picture_url + "\n" +
						  "User_ID: " + profile.user_id)
				if profile.status_message:
					result += "\n" + "Status message: " + profile.status_message
			except LineBotApiError:
				pass
			line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage(result))
	
	elif text=='/kbbi':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /kbbi {input}'))
	
	elif text=='/urban':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /urban {input}'))
	
	elif text=='/ox':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /ox {input}'))
	
	elif text=='/wolfram':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /wolfram {input}'))
				
	elif text=='/trans':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /trans sc={}, to={}, {text}'))
	
	elif text=='/wiki':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /wiki {text}'))
				
	elif text=='/wikilang':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /wikilang {language_id}'))
	
	elif text == '/confirm':
		confirm_template = ConfirmTemplate(text='Do it?', actions=[
			MessageTemplateAction(label='Yes', text='Yes!'),
			MessageTemplateAction(label='No', text='No!'),
			])
		template_message = TemplateSendMessage(
			alt_text='Confirm alt text', template=confirm_template)
		line_bot_api.reply_message(event.reply_token, template_message)
	
	elif text == '/buttons':
		buttons_template = ButtonsTemplate(
			title='My buttons sample', text='Hello, my buttons', actions=[
				URITemplateAction(
					label='Go to line.me', uri='https://line.me'),
				PostbackTemplateAction(label='ping', data='ping'),
				PostbackTemplateAction(
					label='ping with text', data='ping',
					text='ping'),
				MessageTemplateAction(label='Translate Rice', text='米')
			])
		template_message = TemplateSendMessage(
			alt_text='Buttons alt text', template=buttons_template)
		line_bot_api.reply_message(event.reply_token, template_message)
	
	elif text == '/image_carousel':
		image_carousel_template = ImageCarouselTemplate(columns=[
			ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
								action=DatetimePickerTemplateAction(label='datetime',
																	data='datetime_postback',
																	mode='datetime')),
			ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
								action=DatetimePickerTemplateAction(label='date',
																	data='date_postback',
																	mode='date'))
		])
		template_message = TemplateSendMessage(
			alt_text='ImageCarousel alt text', template=image_carousel_template)
		line_bot_api.reply_message(event.reply_token, template_message)
		
	elif text == '/imagemap':
		pass
	
	elif text[0:].lower().strip().startswith('/wolfram '):
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(wolfram(split1(text))))
			
	elif text[0:].lower().strip().startswith('/wolframs '):
		line_bot_api.reply_message(
			event.reply_token,
			ImageSendMessage(original_content_url= wolframs(split4(text)),
								preview_image_url= wolframs(split4(text))))

	elif text[0:].lower().strip().startswith('/kbbi '):
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(find_kbbi(split2(text))))
			
	elif text[0:].lower().strip().startswith('/urban '):
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(urban(split8(text))))
			
	elif text[0:].lower().strip().startswith('/ox '):
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(ox(split9(text))))
			
	elif text[0:].lower().strip().startswith('/echo ') :
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(split3(text)))
			
	elif text[0:].lower().strip().startswith('/trans ') :
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(trans(split5(text))))
	
	elif text[0:].lower().strip().startswith('/wiki ') :
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(wiki_get(split6(text), set_id=set_id)))
			
	elif text[0:].lower().strip().startswith('/wikilang ') :
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(wiki_lang(split7(text), set_id=set_id)))
Example #23
0
def notifyon(event): #顯示作業
    line_bot_api.reply_message(event.reply_token,TextSendMessage(text="通知功能已開啟"))
Example #24
0
    def Manager_Cancel_Message(SelectTime):
        firebase_rec = []
        r = []
        doc_ref = firedb.collection_group('訂位紀錄')
        docs = doc_ref.stream()  # generator
        # 1個ID(collection)算一次迴圈
        for doc in docs:
            for d in doc.to_dict():  # for each in dict
                try:
                    print(doc.to_dict()[d][1][:-6])
                    if datetime.strptime(doc.to_dict()[d][1][:-6],
                                         '%Y-%m-%d') == datetime.strptime(
                                             SelectTime,
                                             '%Y-%m-%d'):  # 跟選取的為同一天
                        r = doc.to_dict()[d]
                        r.append(doc.id)
                        firebase_rec.append(r)
                except:
                    pass
        Contents = []
        if len(firebase_rec) != 0:
            for t in range(len(firebase_rec)):
                Contents.append({
                    "type": "bubble",
                    "body": {
                        "type":
                        "box",
                        "layout":
                        "vertical",
                        "contents": [
                            {
                                "type":
                                "text",
                                # [['黃先生', '2020-02-08T11:30', '4', 'C桌(4人)', '1', 'Ue7d3f74f2e5108ceadf2faca070a3f50']]
                                "text":
                                "姓名: " + firebase_rec[t][0] + "\n訂位時間: " +
                                firebase_rec[t][1][-5:] + "\n人數: " +
                                firebase_rec[t][2] + "\n桌號: " +
                                firebase_rec[t][3],
                                "margin":
                                "md",
                                "wrap":
                                True
                            },
                            {
                                "type": "button",
                                "action": {
                                    "type":
                                    "postback",
                                    "label":
                                    "取消這位客人",
                                    "data":
                                    "cancel " + firebase_rec[t][0] + " " +
                                    firebase_rec[t][1] + " " +
                                    firebase_rec[t][2] + " " +
                                    firebase_rec[t][3] + " " +
                                    firebase_rec[t][5]
                                },
                                "margin": "md",
                                "weight": "bold",
                                "align": "center"
                            }
                        ]
                    },
                    "styles": {
                        "footer": {
                            "separator": True
                        }
                    }
                })
            ManagerCancelMessage = FlexSendMessage(alt_text='選取欲取消訂位的客人',
                                                   position='absolute',
                                                   contents={
                                                       "type": "carousel",
                                                       "contents": Contents
                                                   })
        else:
            ManagerCancelMessage = TextSendMessage(text="選取日期內沒有客人訂位")

        return ManagerCancelMessage
Example #25
0
def rmhw(event): #刪除作業
    line_bot_api.reply_message(event.reply_token,TextSendMessage(text="作業刪除成功"))
Example #26
0
def process_text_message(event):
    global producer  #
    global consumer  #
    global server  #
    global r  #

    nowtime = str(
        time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    msg = str(event.message.text).upper().strip()
    # 取出消息內User的資料
    profile = line_bot_api.get_profile(event.source.user_id)
    #     print(profile)

    #取出userid, displayname 丟回全域變數
    profile_dict = vars(profile)
    print("使用者輸入內容 =", msg, " ,LINE名字 =", profile_dict.get("display_name"),
          " ,使用者 =", profile_dict.get("user_id"), " ,輸入內容時間 =", nowtime)

    ID = profile_dict.get("user_id")  #
    text = event.message.text  #
    query = str(text)  #
    groupid = str(ID)  #

    #使用者及使用者輸入內容匯入kafka(2020070041700先註解kafka有問題)
    kafkaproducer(server=server, topic='2_resquest', ID=ID, query=query)  #

    if msg == '股票推薦':
        line_bot_api.push_message(ID, TextSendMessage(text='請稍等,\n資料產生中!!'))

        user_type = str(r.get(ID))
        user_type += '_'
        user_type += str(datetime.datetime.now().strftime('%Y%m%d'))
        res = pro_kafkaconsumer(server=server,
                                groupid='groupid',
                                topic='promote_stock',
                                ID=user_type)  #此ID為type1(kafka內的)
        Stock_list = [i for i in eval(res[user_type]).keys()]
        Str = "股票推薦清單" + emoji_upinfo
        Str += '\n'
        Str += "======================="
        Str += '\n'
        for stl in Stock_list:
            Str += stl
            Str += '\n'

        Str += '======================'
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=Str))

    elif msg == '.2-1_10%內可接受範圍':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    elif msg == '.2-3_50%內可接受範圍':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    elif msg == '.2-4_100%以上':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    elif msg == '.3-1_1個月內':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    elif msg == '.3-4_1年以上':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    elif msg == '.4-1_每天花費1~2小時':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    elif msg == '.4-3_每月花費1~2小時':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    elif msg == '.5-1_高風險高報酬':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    elif msg == '.6-1_投資一定有風險':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    elif msg == '.7-1_我很積極布局':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    elif msg == '.7-2_我要觀察一陣子':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    elif msg == '.7-4_認賠殺出':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    elif msg == '.8-1_我喜愛賺價差':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    elif msg == '.8-2_我喜愛超高報酬':
        res = kafkaconsumer(server=server,
                            groupid=groupid,
                            topic='1_resquest',
                            ID=ID)  #
        res = res[ID]  #
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(res)))

    # 個股新聞
    elif re.match('N[0-9]{4}', msg):
        stockNumber = msg[1:5]
        content = app_1_news.single_stock(stockNumber)
        line_bot_api.push_message(
            ID, TextSendMessage('即將給您編號' + stockNumber + '\n個股新聞!'))
        line_bot_api.push_message(ID, content)
        btn_msg = Msg_Template.stock_reply_other(stockNumber)
        line_bot_api.push_message(ID, btn_msg)

    # 每週新聞回顧
    elif re.match("每週新聞回顧", msg):
        line_bot_api.push_message(ID,
                                  TextSendMessage("我們將給您最新的周回顧,\n請點選圖片連結!!"))
        line_bot_api.push_message(ID, app_1_news.weekly_finance_news())

    # 查詢某檔股票股價
    elif re.match('S[0-9]', msg):
        stockNumber = msg[1:]
        stockName = stockprice.get_stock_name(stockNumber)
        if stockName == "no":
            line_bot_api.push_message(ID, TextSendMessage("股票編號錯誤"))
        else:
            line_bot_api.push_message(
                ID, TextSendMessage('稍等一下,\n查詢編號' + stockNumber + '\n的股價中...'))
            content_text = stockprice.getprice(stockNumber, msg)
            content = Msg_Template.stock_reply(stockNumber, content_text)
            line_bot_api.push_message(ID, content)

    #K線圖     #OK
    elif re.match("K[0-9]{4}", msg):
        stockNumber = msg[1:]
        content = Msg_Template.kchart_msg + "\n" + Msg_Template.kd_msg
        line_bot_api.push_message(ID, TextSendMessage(content))
        line_bot_api.push_message(ID, TextSendMessage('稍等一下,\nK線圖繪製中...'))
        k_imgurl = kchart.draw_kchart(stockNumber)
        line_bot_api.push_message(
            ID,
            ImageSendMessage(original_content_url=k_imgurl,
                             preview_image_url=k_imgurl))
        btn_msg = Msg_Template.stock_reply_other(stockNumber)
        line_bot_api.push_message(ID, btn_msg)

    #MACD指標     #OK
    elif re.match("MACD[0-9]", msg):
        stockNumber = msg[4:]
        content = Msg_Template.macd_msg
        line_bot_api.push_message(
            ID, TextSendMessage('稍等一下,\n將給您編號' + stockNumber + '\nMACD指標...'))
        line_bot_api.push_message(ID, TextSendMessage(content))
        MACD_imgurl = Technical_Analysis.MACD_pic(stockNumber, msg)
        line_bot_api.push_message(
            ID,
            ImageSendMessage(original_content_url=MACD_imgurl,
                             preview_image_url=MACD_imgurl))
        btn_msg = Msg_Template.stock_reply_other(stockNumber)
        line_bot_api.push_message(ID, btn_msg)

    #RSI指標  #OK
    elif re.match('RSI[0-9]', msg):
        stockNumber = msg[3:]
        line_bot_api.push_message(
            ID, TextSendMessage('稍等一下,\n將給您編號' + stockNumber + '\nRSI指標...'))
        RSI_imgurl = Technical_Analysis.stock_RSI(stockNumber)
        line_bot_api.push_message(
            ID,
            ImageSendMessage(original_content_url=RSI_imgurl,
                             preview_image_url=RSI_imgurl))
        btn_msg = Msg_Template.stock_reply_other(stockNumber)
        line_bot_api.push_message(ID, btn_msg)

    #BBAND指標      #OK
    elif re.match("BBAND[0-9]", msg):
        stockNumber = msg[5:]
        content = Msg_Template.bband_msg
        line_bot_api.push_message(ID, TextSendMessage(content))
        line_bot_api.push_message(
            ID, TextSendMessage('稍等一下,\n將給您編號' + stockNumber + '\nBBand指標...'))
        BBANDS_imgurl = Technical_Analysis.BBANDS_pic(stockNumber, msg)
        line_bot_api.push_message(
            ID,
            ImageSendMessage(original_content_url=BBANDS_imgurl,
                             preview_image_url=BBANDS_imgurl))
        btn_msg = Msg_Template.stock_reply_other(stockNumber)
        line_bot_api.push_message(ID, btn_msg)

    #畫近一年股價走勢圖      #OK
    elif re.match("P[0-9]{4}", msg):
        stockNumber = msg[1:]
        line_bot_api.push_message(
            ID, TextSendMessage('稍等一下,\n將給您編號' + stockNumber + '\n股價走勢圖!'))
        trend_imgurl = stockprice.stock_trend(stockNumber, msg)
        line_bot_api.push_message(
            ID,
            ImageSendMessage(original_content_url=trend_imgurl,
                             preview_image_url=trend_imgurl))
        btn_msg = Msg_Template.stock_reply_other(stockNumber)
        line_bot_api.push_message(ID, btn_msg)

    # 個股年收益率分析圖 #OK
    elif re.match('E[0-9]{4}', msg):
        targetStock = msg[1:]
        line_bot_api.push_message(
            ID, TextSendMessage('分析' + targetStock + '中,\n年收益率圖產生中,\n稍等一下。'))
        imgurl2 = stockprice.show_return(targetStock, msg)
        line_bot_api.push_message(
            ID,
            ImageSendMessage(original_content_url=imgurl2,
                             preview_image_url=imgurl2))
        btn_msg = Msg_Template.stock_reply_other(targetStock)
        line_bot_api.push_message(ID, btn_msg)

    #三大法人買賣資訊  #OK
    elif re.match('F[0-9]', msg):
        stockNumber = msg[1:]
        line_bot_api.push_message(
            ID,
            TextSendMessage('稍等一下,\n將給您編號' + stockNumber + '\n三大法人買賣資訊...'))
        content = Institutional_Investors.institutional_investors(stockNumber)
        line_bot_api.push_message(ID, TextSendMessage(content))
        btn_msg = Msg_Template.stock_reply_other(stockNumber)
        line_bot_api.push_message(ID, btn_msg)

    # 籌碼面分析圖    #失敗_有空從做此步
#     elif re.match('C[0-9]', msg):
#         targetStock = msg[1:]
#         line_bot_api.push_message(ID, TextSendMessage('分析' + targetStock + '中,\n籌碼面分析圖產生中,\n稍等一下。'))
#         imgurl2 = Institutional_Investors.institutional_investors_pic(targetStock)
#         if imgurl2 == "股票代碼錯誤!":
#             line_bot_api.push_message(ID, TextSendMessage("股票代碼錯誤!"))

#         line_bot_api.push_message(ID, ImageSendMessage(original_content_url=imgurl2, preview_image_url=imgurl2))
#         btn_msg = Msg_Template.stock_reply_other(targetStock)
#         line_bot_api.push_message(ID, btn_msg)

#功能說明
    elif msg == '功能說明':
        line_bot_api.reply_message(event.reply_token, \
            TextSendMessage(text='您好~\n在此說明我的功能!\n\nK+個股代號(舉例:K2330),\n=>會產生出2330的K線圖。\n\nN+個股代號(舉例:N2330),\n=>會顯示近期2330的新聞連結。\n\nS+個股代號(舉例:S2330),\n=>會顯示最近2330的\n開、高、收、低價格。\n\nMACD+個股代號(舉例:MACD2330),\n=>會產生出2330的MACD指標圖。\n\nRSI+個股代號(舉例:RSI2330),\n=>會產生出2330的RSI指標圖。\n\nBBAND+個股代號(舉例:BBAND2330),\n=>會產生出2330的BBAND指標圖。\n\nP+個股代號(舉例:P2330),\n=>會產生出2330的一年股價走勢圖。\n\nE+個股代號(舉例:E2330),\n=>會產生出2330的年收益率分析圖。\n\nF+個股代號(舉例:F2330),\n=>會產生出2330三大法人買賣資訊。\n\n或者點選"股票推薦",\n推薦適合您的股票名單。\n\n功能說明完畢,\n謝謝觀看!!'))

    #問候語回應
    elif msg in ("你好", "哈嘍", 'HI', 'hi', '嗨', "妳好", "您好", "Hi", "hI"):
        line_bot_api.reply_message(event.reply_token, \
            TextSendMessage(text='您好~歡迎加入股市小子!\n下方圖文選單可以點選!\n或請點選下方"功能說明",\n會詳列出我的功能說明!'))

    else:
        pass

    # 讀取本地檔案,並轉譯成消息
    result_message_array = []
    replyJsonPath = "素材/" + event.message.text + "/reply.json"
    result_message_array = detect_json_array_to_new_message_array(
        replyJsonPath)

    # 發送
    line_bot_api.reply_message(event.reply_token, result_message_array)
Example #27
0
def handle_message(event):
    input_text = event.message.text
    history_list = get_history_list()
    if history_list[0]['type'] == 'user':  #個人部分
        selfId = history_list[0]['user_id']
        if (history_list[0]['Status'] == 'save') and ('記帳' in input_text):
            output_text = '記帳成功'
        elif input_text == '@官網':
            output_text = 'https://reurl.cc/4yjNyY'
        elif input_text == '@help':
            output_text = '請直接把多多分帳邀請至群組以解鎖分帳功能唷~'

        elif '多多公布欄' in input_text:
            output_text = '多多感謝您的體諒!我會在群組中繼續為大家服務。'
        elif input_text == '理財':
            line_bot_api.reply_message(
                event.reply_token,
                TemplateSendMessage(
                    alt_text='Buttons template',
                    template=ButtonsTemplate(
                        title='理財小幫手',
                        text='請選擇功能',
                        actions=[
                            URITemplateAction(
                                label='股市', uri='https://tw.stock.yahoo.com/'),
                            URITemplateAction(
                                label='匯率',
                                uri='https://rate.bot.com.tw/xrt?Lang=zh-TW'),
                            URITemplateAction(
                                label='財經新聞',
                                uri='https://www.msn.com/zh-tw/money')
                        ])))

    elif history_list[0]['type'] == 'room':  #聊天室部分
        Carousel_template = TemplateSendMessage(
            alt_text='請把我加入群組',
            template=ImageCarouselTemplate(columns=[
                ImageCarouselColumn(
                    image_url="https://i.imgur.com/wUob12p.jpg",
                    action=URITemplateAction(
                        uri="https://i.imgur.com/wUob12p.jpg")),
                ImageCarouselColumn(
                    image_url="https://i.imgur.com/MRMWivy.jpg",
                    action=URITemplateAction(
                        uri="https://i.imgur.com/MRMWivy.jpg"))
            ]))
        line_bot_api.reply_message(event.reply_token, Carousel_template)

    else:  #群組部分
        selfGroupId = history_list[0]['group_id']
        if (history_list[0]['Status'] == 'set') and ('@分帳設定' in input_text):
            groupNumber = get_groupPeople(history_list, 1)
            output_text = '分帳設定成功:共有' + str(groupNumber) + '人分帳'

        elif (history_list[0]['Status'] == 'save') and ('@分帳' in input_text):
            output_text = '分帳記錄成功'

        elif (history_list[0]['Status'] == 'None') and ('@分帳' in input_text):
            output_text = '分帳記錄失敗'

        elif input_text == '@設定查詢':
            groupMember = get_groupPeople(history_list, 2)
            output_text = "分帳名單:"
            for i in range(get_groupPeople(history_list, 1)):
                output_text += '\n' + groupMember[i]

        elif '@美金設定' in input_text:
            NowRate = get_TodayRate(1)
            output_text = "今日匯率:" + str(NowRate)

        elif '@日圓設定' in input_text:
            NowRate = get_TodayRate(2)
            output_text = "今日匯率:" + str(NowRate)

        elif '@歐元設定' in input_text:
            NowRate = get_TodayRate(3)
            output_text = "今日匯率:" + str(NowRate)

        elif input_text == '@刪除':
            for i in range(3):
                data_UserData = usermessage.query.filter(
                    usermessage.group_id == selfGroupId).filter(
                        usermessage.status == 'save').delete(
                            synchronize_session='fetch')
            output_text = '刪除成功'
            db.session.commit()

        elif input_text == '@設定刪除':
            data_UserData = usermessage.query.filter(
                usermessage.group_id == selfGroupId).filter(
                    usermessage.status == 'set').delete(
                        synchronize_session='fetch')
            db.session.commit()
            output_text = '刪除成功'

        elif '@clear' in input_text:  #刪除單個分帳者
            data_UserData = usermessage.query.filter(
                usermessage.status == 'set').filter(
                    usermessage.group_id == selfGroupId)
            del_spiltperson = ' ' + input_text.replace('@clear',
                                                       '').strip(' ') + ' '
            for _data in data_UserData:
                old_nickname = ' ' + _data.nickname + ' '
                old_nickname = old_nickname
                if old_nickname.count(del_spiltperson):
                    new_nickname = old_nickname.replace(
                        del_spiltperson, ' ').replace('  ', ' ').strip(' ')
                    add_data = usermessage(id=_data.id,
                                           group_num='0',
                                           nickname=new_nickname,
                                           group_id=_data.group_id,
                                           type=_data.type,
                                           status='set',
                                           account='0',
                                           user_id=_data.user_id,
                                           message=_data.message,
                                           birth_date=_data.birth_date)
                    personID = _data.id
                    data_UserData = usermessage.query.filter(
                        usermessage.id == personID).delete(
                            synchronize_session='fetch')
                    db.session.add(add_data)
                    db.session.commit()
                    output_text = "刪除成功,若被刪除的人在帳目中,請記得把帳目也修改掉!\n\n分帳名單:"
            try:
                if output_text == '刪除成功,若被刪除的人在帳目中,請記得把帳目也修改掉!\n\n分帳名單:':
                    groupMember = get_groupPeople(history_list, 2)
                    for i in range(get_groupPeople(history_list, 1)):
                        output_text += '\n' + groupMember[i]
            except:
                output_text = '刪除失敗'

        elif '@delete' in input_text:  #刪除單筆分帳
            count = usermessage.query.filter(
                usermessage.status == 'save').filter(
                    usermessage.group_id == selfGroupId).count()
            try:
                del_number = int(input_text.strip('@delete '))
                if del_number <= count:
                    data_UserData = usermessage.query.order_by(
                        usermessage.birth_date).filter(
                            usermessage.status == 'save').filter(
                                usermessage.group_id ==
                                selfGroupId)[del_number - 1:del_number]
                    for _data in data_UserData:
                        personID = _data.id
                    data_UserData = usermessage.query.filter(
                        usermessage.id == personID).delete(
                            synchronize_session='fetch')
                    output_text = '刪除成功' + '\n\n' + '記帳清單:' + '\n' + get_settleList(
                        selfGroupId)
                    db.session.commit()
                else:
                    output_text = '刪除失敗'
            except:
                output_text = '刪除失敗'

        elif input_text == '@查帳':
            output_text = get_settleList(selfGroupId)
            flexmsg = {
                "type": "flex",
                "altText": "Flex Message",
                "contents": {
                    "type": "bubble",
                    "hero": {
                        "type": "image",
                        "url": "https://imgur.com/KahFQi9.jpg",
                        "size": "full",
                        "aspectRatio": "20:13",
                        "aspectMode": "cover",
                        "action": {
                            "type": "text",
                            "text": "查查"
                        }
                    },
                    "body": {
                        "type":
                        "box",
                        "layout":
                        "vertical",
                        "contents": [{
                            "type": "text",
                            "text": "查帳",
                            "size": "xl",
                            "weight": "bold"
                        }, {
                            "type":
                            "box",
                            "layout":
                            "vertical",
                            "spacing":
                            "sm",
                            "margin":
                            "lg",
                            "contents": [
                                {
                                    "type":
                                    "box",
                                    "layout":
                                    "baseline",
                                    "spacing":
                                    "sm",
                                    "contents": [{
                                        "type": "text",
                                        "text": output_text + ". . .",
                                        "flex": 5,
                                        "size": "sm",
                                        "color": "#666666",
                                        "wrap": True
                                    }]
                                },
                            ]
                        }]
                    },
                    "footer": {
                        "type":
                        "box",
                        "layout":
                        "vertical",
                        "flex":
                        0,
                        "spacing":
                        "sm",
                        "contents": [{
                            "type": "button",
                            "action": {
                                "type": "uri",
                                "label": "查看更多",
                                "uri":
                                "https://liff.line.me/1654876504-rK3v07Pk"
                            },
                            "height": "sm",
                            "style": "link"
                        }, {
                            "type": "button",
                            "action": {
                                "type": "uri",
                                "label": "記錄分帳",
                                "uri":
                                "https://liff.line.me/1654876504-9wWzOva7"
                            },
                            "height": "sm",
                            "style": "link"
                        }, {
                            "type": "button",
                            "action": {
                                "type": "uri",
                                "label": "編輯分帳者",
                                "uri":
                                "https://liff.line.me/1654876504-QNXjnrl2"
                            },
                            "height": "sm",
                            "style": "link"
                        }, {
                            "type": "spacer",
                            "size": "sm"
                        }]
                    }
                }
            }
            line_bot_api.reply_message(
                event.reply_token,
                messages=FlexSendMessage.new_from_json_dict(flexmsg))

        elif input_text == '@結算':
            selfGroupId = history_list[0]['group_id']
            dataSettle_UserData = usermessage.query.filter(
                usermessage.group_id == selfGroupId).filter(
                    usermessage.status == 'save').filter(
                        usermessage.type == 'group')
            historySettle_list = []
            person_list = get_groupPeople(history_list, 2)
            person_num = get_groupPeople(history_list, 1)
            for _data in dataSettle_UserData:
                historySettle_dic = {}
                historySettle_dic['Account'] = _data.account
                historySettle_dic['GroupPeople'] = _data.group_num
                historySettle_dic['message'] = _data.message
                historySettle_list.append(historySettle_dic)

            dataNumber = len(historySettle_list)
            account = np.zeros(person_num)
            exchange_rate_USD = 0
            exchange_rate_JPY = 0
            exchange_rate_EUR = 0
            for i in range(dataNumber):  #分帳金額
                b = dict(historySettle_list[i])
                GroupPeopleString = b['GroupPeople'].strip(' ').split(
                    ' ')  #刪除代墊者
                del GroupPeopleString[0]

                if 'USD' in b['message']:  #匯率轉換
                    if exchange_rate_USD:
                        exchange_rate = exchange_rate_USD
                    else:
                        exchange_rate_USD = get_exchangeRate(1)
                        exchange_rate = exchange_rate_USD
                elif 'JPY' in b['message']:
                    if exchange_rate_JPY:
                        exchange_rate = exchange_rate_JPY
                    else:
                        exchange_rate_JPY = get_exchangeRate(2)
                        exchange_rate = exchange_rate_JPY
                elif 'EUR' in b['message']:
                    if exchange_rate_EUR:
                        exchange_rate = exchange_rate_EUR
                    else:
                        exchange_rate_EUR = get_exchangeRate(3)
                        exchange_rate = exchange_rate_EUR
                else:
                    exchange_rate = 1

                payAmount = exchange_rate * int(
                    b['Account']) / len(GroupPeopleString)
                a1 = set(person_list)  #分帳設定有的人
                a2 = set(GroupPeopleString)
                duplicate = list(a1.intersection(a2))  #a1和a2重複的人名
                for j in range(len(duplicate)):  #分帳金額
                    place = person_list.index(duplicate[j])
                    payAmount_place = GroupPeopleString.index(
                        duplicate[j]) + 1  #多種分帳金額 - 金額位置
                    if (payAmount_place < len(GroupPeopleString)
                            and GroupPeopleString[payAmount_place].isdigit()):
                        payAmount = exchange_rate * int(
                            GroupPeopleString[payAmount_place])
                    account[place] -= payAmount

            for j in range(dataNumber):  #代墊金額
                b = dict(historySettle_list[j])
                GroupPeopleString = b['GroupPeople'].strip(' ').split(' ')
                if 'USD' in b['message']:  #匯率轉換
                    if exchange_rate_USD:
                        exchange_rate = exchange_rate_USD
                    else:
                        exchange_rate_USD = get_exchangeRate(1)
                        exchange_rate = exchange_rate_USD
                elif 'JPY' in b['message']:
                    if exchange_rate_JPY:
                        exchange_rate = exchange_rate_JPY
                    else:
                        exchange_rate_JPY = get_exchangeRate(2)
                        exchange_rate = exchange_rate_JPY
                elif 'EUR' in b['message']:
                    if exchange_rate_EUR:
                        exchange_rate = exchange_rate_EUR
                    else:
                        exchange_rate_EUR = get_exchangeRate(3)
                        exchange_rate = exchange_rate_EUR
                else:
                    exchange_rate = 1

                for i in range(person_num):
                    if GroupPeopleString[0] == person_list[i]:
                        account[i] += exchange_rate * int(b['Account'])

            #將人和錢結合成tuple,存到一個空串列
            person_account = []
            for i in range(person_num):
                zip_tuple = (person_list[i], account[i])
                person_account.append(zip_tuple)

            #重複執行交換動作
            result = ""
            for i in range(person_num - 1):  #排序
                person_account = sorted(person_account, key=lambda s: s[1])

                #找到最大、最小值
                min_tuple = person_account[0]
                max_tuple = person_account[-1]

                #找到目前代墊最多的人
                if i == 0:
                    maxPerson = max_tuple[0]
                    minPerson = min_tuple[0]

                min = float(min_tuple[1])
                max = float(max_tuple[1])

                #交換,印出該付的錢
                if min == 0 or max == 0:
                    pass
                elif (min + max) > 0:
                    result = result + str(
                        min_tuple[0]) + '付給' + str(max_tuple[0]) + " " + str(
                            abs(round(min, 2))) + '元' + '\n'
                    max_tuple = (max_tuple[0], min + max)
                    min_tuple = (min_tuple[0], 0)
                elif (min + max) < 0:
                    result = result + str(
                        min_tuple[0]) + '付給' + str(max_tuple[0]) + " " + str(
                            abs(round(max, 2))) + '元' + '\n'
                    min_tuple = (min_tuple[0], min + max)
                    max_tuple = (max_tuple[0], 0)
                else:
                    result = result + str(
                        min_tuple[0]) + '付給' + str(max_tuple[0]) + " " + str(
                            abs(round(max, 2))) + '元' + '\n'
                    min_tuple = (min_tuple[0], 0)
                    max_tuple = (max_tuple[0], 0)

                person_account[0] = min_tuple
                person_account[-1] = max_tuple
            # result=result+'\n'+'下次不要再讓'+str(max_tuple[0])+'付錢啦! TA幫你們付很多了!'

            output_text = result.strip('\n')

            flexmsg = {
                "type": "flex",
                "altText": "Flex Message",
                "contents": {
                    "type": "bubble",
                    "hero": {
                        "type": "image",
                        "url": "https://imgur.com/GteXIvk.jpg",
                        "size": "full",
                        "aspectRatio": "20:13",
                        "aspectMode": "cover",
                        "action": {
                            "type": "text",
                            "text": "借錢要還,誰還要借?"
                        }
                    },
                    "body": {
                        "type":
                        "box",
                        "layout":
                        "vertical",
                        "contents": [{
                            "type": "text",
                            "text": "簡化版本",
                            "size": "xl",
                            "weight": "bold"
                        }, {
                            "type":
                            "box",
                            "layout":
                            "vertical",
                            "spacing":
                            "sm",
                            "margin":
                            "lg",
                            "contents": [
                                {
                                    "type":
                                    "box",
                                    "layout":
                                    "baseline",
                                    "spacing":
                                    "sm",
                                    "contents": [{
                                        "type": "text",
                                        "text": result + ". . .",
                                        "flex": 5,
                                        "size": "sm",
                                        "color": "#666666",
                                        "wrap": True
                                    }]
                                },
                            ]
                        }]
                    },
                    "footer": {
                        "type":
                        "box",
                        "layout":
                        "vertical",
                        "flex":
                        0,
                        "spacing":
                        "sm",
                        "contents": [{
                            "type": "button",
                            "action": {
                                "type": "uri",
                                "label": "查看更多",
                                "uri":
                                "https://liff.line.me/1654876504-rK3v07Pk"
                            },
                            "height": "sm",
                            "style": "link"
                        }, {
                            "type": "button",
                            "action": {
                                "type": "uri",
                                "label": "記錄分帳",
                                "uri":
                                "https://liff.line.me/1654876504-9wWzOva7"
                            },
                            "height": "sm",
                            "style": "link"
                        }, {
                            "type": "button",
                            "action": {
                                "type": "uri",
                                "label": "編輯分帳者",
                                "uri":
                                "https://liff.line.me/1654876504-QNXjnrl2"
                            },
                            "height": "sm",
                            "style": "link"
                        }, {
                            "type": "spacer",
                            "size": "sm"
                        }]
                    }
                }
            }
            line_bot_api.reply_message(
                event.reply_token,
                messages=FlexSendMessage.new_from_json_dict(flexmsg))

        elif input_text == '@稍微':
            selfGroupId = history_list[0]['group_id']
            dataSettle_UserData = usermessage.query.filter(
                usermessage.group_id == selfGroupId).filter(
                    usermessage.status == 'save').filter(
                        usermessage.type == 'group')
            historySettle_list = []
            person_list = get_groupPeople(history_list, 2)  #分帳設定人名
            person_num = get_groupPeople(history_list, 1)  #分帳設定人數
            for _data in dataSettle_UserData:
                historySettle_dic = {}
                historySettle_dic['Account'] = _data.account
                historySettle_dic['GroupPeople'] = _data.group_num
                historySettle_dic['message'] = _data.message
                historySettle_list.append(historySettle_dic)

            dataNumber = len(historySettle_list)
            account = np.zeros((person_num, person_num))
            exchange_rate_USD = 0
            exchange_rate_JPY = 0
            exchange_rate_EUR = 0
            for i in range(dataNumber):
                b = dict(historySettle_list[i])
                GroupPeopleString = b['GroupPeople'].split(' ')

                if 'USD' in b['message']:  #匯率轉換
                    if exchange_rate_USD:
                        exchange_rate = exchange_rate_USD
                    else:
                        exchange_rate_USD = get_exchangeRate(1)
                        exchange_rate = exchange_rate_USD
                elif 'JPY' in b['message']:
                    if exchange_rate_JPY:
                        exchange_rate = exchange_rate_JPY
                    else:
                        exchange_rate_JPY = get_exchangeRate(2)
                        exchange_rate = exchange_rate_JPY
                elif 'EUR' in b['message']:
                    if exchange_rate_EUR:
                        exchange_rate = exchange_rate_EUR
                    else:
                        exchange_rate_EUR = get_exchangeRate(3)
                        exchange_rate = exchange_rate_EUR
                else:
                    exchange_rate = 1
                payAmount = exchange_rate * int(b['Account']) / (
                    len(GroupPeopleString) - 1)  #不包含代墊者
                a1 = set(person_list)  #分帳設定有的人
                a2 = set(GroupPeopleString)
                duplicate = list(a1.intersection(a2))  #a1和a2重複的人名

                for j in range(len(duplicate)):  #誰付誰錢矩陣 2給1
                    place1 = person_list.index(GroupPeopleString[0])
                    place2 = person_list.index(duplicate[j])
                    account[place1][place2] += payAmount
            result = ""
            for j in range(person_num):  #誰付誰錢輸出
                for i in range(person_num):
                    payAmount = account[i][j] - account[j][i]
                    if (payAmount > 0):
                        result += person_list[j] + '付給' + person_list[
                            i] + " " + str(round(payAmount, 2)) + '元' + '\n'
            output_text = result.strip('\n')

        elif input_text == '@清空資料庫':
            data_UserData = usermessage.query.filter(
                usermessage.status == 'None').delete(
                    synchronize_session='fetch')
            db.session.commit()
            output_text = '爽啦沒資料囉\n快給我重新設定匯率'

        elif '@查查' in input_text:
            output_text = "欠錢不還啦 幹你娘"

        elif input_text == '@多多':
            try:
                message = TextSendMessage(
                    text="快速選擇下列功能:",
                    quick_reply=QuickReply(items=[
                        QuickReplyButton(
                            action=MessageAction(label="主選單", text="@選單")),
                        QuickReplyButton(
                            action=MessageAction(label="查帳", text="@查帳")),
                        QuickReplyButton(
                            action=MessageAction(label="簡化結算", text="@結算")),
                        QuickReplyButton(
                            action=MessageAction(label="不簡化結算", text="@稍微")),
                        QuickReplyButton(
                            action=MessageAction(label="使用說明", text="@help")),
                    ]))
                line_bot_api.reply_message(event.reply_token, message)
            except:
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage('發生錯誤!'))

        elif input_text == '@help':
            Carousel_template = TemplateSendMessage(
                alt_text='使用說明',
                template=ImageCarouselTemplate(columns=[
                    ImageCarouselColumn(
                        image_url="https://imgur.com/xvZq2mD.png",
                        action=URITemplateAction(
                            uri="https://imgur.com/xvZq2mD.png")),
                    ImageCarouselColumn(
                        image_url="https://imgur.com/oER72MY.png",
                        action=URITemplateAction(
                            uri="https://imgur.com/oER72MY.png"))
                ]))
            line_bot_api.reply_message(event.reply_token, Carousel_template)

            line_bot_api.reply_message(event.reply_token, flexmsg)
        elif input_text == '@選單':
            message = ImagemapSendMessage(
                base_url="https://imgur.com/cODeL32.jpg",
                alt_text='功能總覽',
                base_size=BaseSize(height=927, width=1040),
                actions=[
                    URIImagemapAction(
                        #分帳者設定
                        link_uri="https://liff.line.me/1654876504-QNXjnrl2",
                        area=ImagemapArea(x=0, y=464, width=522, height=459)),
                    URIImagemapAction(
                        #記錄分帳
                        link_uri="https://liff.line.me/1654876504-9wWzOva7",
                        area=ImagemapArea(x=0, y=0, width=521, height=463)),
                    MessageImagemapAction(
                        #使用說明
                        text="@help",
                        area=ImagemapArea(x=525, y=464, width=515,
                                          height=459)),
                    URIImagemapAction(
                        #查帳結算
                        link_uri="https://liff.line.me/1654876504-rK3v07Pk",
                        area=ImagemapArea(x=522, y=0, width=518, height=463))
                ])
            line_bot_api.reply_message(event.reply_token, message)

        elif input_text == '@官網':
            output_text = 'https://reurl.cc/4yjNyY'

        elif input_text == '電影':
            output_text = str(get_movie())

        elif input_text == '啾啾啾':
            output_text = '啾啾啾'

        elif input_text == '逛夜市' or input_text == '烤小鳥' or input_text == '屏東':
            output_text = '不要吃焦阿巴'

        elif input_text == '廖擊敗':
            output_text = '廖奕翔還錢 操!'

        elif input_text == 'debug好累':
            output_text = '關我屁事,我已經好幾天沒睡了=='

        elif input_text == '乖狗狗':
            line_bot_api.reply_message(
                event.reply_token,
                StickerSendMessage(package_id=1, sticker_id=2))

        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(output_text))
Example #28
0
app = Flask(__name__, static_url_path="/images", static_folder="./images/")

# 生成實體物件
line_bot_api = LineBotApi(
    secretFileContentJson.get("LINE_CHANNEL_ACCESS_TOKEN"))
handler = WebhookHandler(secretFileContentJson.get("LINE_CHANNEL_SECRET"))

# 創建 QuickReplyButton
## 點擊後,開啟相機
cameraQuickReplyButton = QuickReplyButton(action=CameraAction(label="拍照"))
## 點擊後,切換至照片相簿選擇
cameraRollQRB = QuickReplyButton(action=CameraRollAction(label="相簿"))
## 設計 QuickReplyButton 的 List
quickReplyList = QuickReply(items=[cameraQuickReplyButton, cameraRollQRB])
## 將 quickReplyList 塞入 TextSendMessage 中
quickReplyTextSendMessage = TextSendMessage(text='請選擇功能',
                                            quick_reply=quickReplyList)

# 建立 quickReply 關鍵字字典
template_message_dict = {"@功能": quickReplyTextSendMessage}


# 取得現在時間
def get_time():
    pacific = pytz.timezone('Asia/Taipei')
    d = datetime.datetime.now(pacific)

    return d.strftime('%Y-%m-%d %H:%M:%S')


# 傳送資料到資料庫
def sendtodatabase(params_tuple):
def handle_text_message(event):
    text = event.message.text  #message from user

    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=text))  #reply the same message from user
Example #30
0
def handle_message(event):
    text = event.message.text
    translated = translate_text(text)
    line_bot_api.reply_message(event.reply_token,
                               TextSendMessage(text=translated))