Exemplo n.º 1
0
def handle_message(event):

    # ユーザからの検索ワードを取得
    word = event.message.text

    # 記事取得関数を呼び出し
    result = sc.getNews(word)

    #この後おすすめでpv数から記事取得
    # 応答メッセージ(記事検索結果)を送信
    if word == "hello":
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=str(categ)))
    elif word == "items":
        les = "les"
        template = template_env.get_template('test2.json')
        data = template.render(dict(items=les))

        line_bot_api.reply_message(
            event.reply_token,
            # ===================================================
            FlexSendMessage(
                alt_text="items",
                # dataを入力してカルーセルで応答
                contents=CarouselContainer.new_from_json_dict(
                    json.loads(data)))
            # ----------------------------------------------------------------
        )

    else:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=result))
def auto_message():
    # 打开数据库连接
    conn = pymysql.connect(host='35.222.24.169',
                           port=3306,
                           user='******',
                           password='******',
                           db='news',
                           charset='utf8')

    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = conn.cursor()

    # 使用 execute()  方法执行 SQL 查询
    cursor.execute("SELECT userid \
                   FROM user ")
    data = cursor.fetchall()
    #  取出userid包成list
    conn.close()
    userid = []
    for user in data:
        for i in user:
            userid.append(i)


#        print(userid)
    carouselContent = CarouselContainer.new_from_json_dict(
        json.loads(foreign_recommend()))
    flexCarouselSendMeesage = FlexSendMessage(alt_text="foreign",
                                              contents=carouselContent)
    line_bot_api = linebot.LineBotApi(
        'mvdB7r737zcCXyzycwFOd6VZN8e1sbcQWkh8v6ue7nUfyU4/O/b2+ROhYazZ21pYoUSBtsnlE4L5Dfwpkdrk2lPJPxEzkdTgzkT5ycPeLZWpAtypNc8ogBLL0LdsRiM4ezuh0uqsssGkLL2aCb4IQwdB04t89/1O/w1cDnyilFU='
    )
    line_bot_api.multicast(userid, flexCarouselSendMeesage)
Exemplo n.º 3
0
def handle_message(event):
    if event.message.text == 'test-for-concurrency':
        with open('./test.json', 'r', encoding='utf-8') as f:
            json_dict = json.load(f)
            flex_message = FlexSendMessage(
                alt_text='hello',
                contents=CarouselContainer.new_from_json_dict(json_dict))
            line_bot_api.reply_message(event.reply_token, flex_message)
Exemplo n.º 4
0
def handle_follow(event):
    print(event)
    with open('./test.json', 'r', encoding='utf-8') as f:
        json_dict = json.load(f)
        flex_message = FlexSendMessage(
            alt_text='hello',
            contents=CarouselContainer.new_from_json_dict(json_dict))
        line_bot_api.reply_message(event.reply_token, flex_message)
Exemplo n.º 5
0
def push_carousel_message(user_id, data):
    """外のモジュールからlineのbotにFlexメッセージを返させるメソッド"""
    print('user_id: {}'.format(user_id))
    print('data: {}'.format(json.loads(data)))
    line_bot_api.push_message(
        user_id,
        FlexSendMessage(alt_text="items",
                        contents=CarouselContainer.new_from_json_dict(
                            json.loads(data))))
Exemplo n.º 6
0
def handle_live():
    to = request.args.get('id')
    data = rss_feed.get_live_feed()
    if len(data) > 0:
        carousel_data = rss_feed.create_live_flxed(data['data'])
        if carousel_data is not None:
            carousel_message = CarouselContainer.new_from_json_dict(carousel_data)
            line_bot_api.push_message(to=to, messages=FlexSendMessage(alt_text="โปรแกรมถ่ายทอดสดฟุตบอล", contents=carousel_message))
    return jsonify({'status': 'ok'})
 def menu_reply_message(cls, recipe):
     '''
     :param carousel:
     :param recipe: list contains dictionaries of recipe
     :return: FlexSendMessage
     '''
     reply_template = cls.customize_recipe(recipe)
     return FlexSendMessage(
         alt_text="hello",
         contents=CarouselContainer.new_from_json_dict(reply_template))
Exemplo n.º 8
0
def reply_items(event: MessageEvent, match: Match):

    items = qiita.get_items(10)

    template = template_env.get_template('items.json')
    data = template.render(dict(items=items))

    print(data)

    line_bot_api.reply_message(
        event.reply_token,
        FlexSendMessage(alt_text="items",
                        contents=CarouselContainer.new_from_json_dict(
                            json.loads(data))))
Exemplo n.º 9
0
def reply_tag(event: MessageEvent, match: Match):

    tag_name = match.group(1)

    tag = qiita.get_tag(tag_name)
    items = qiita.get_tag_items(tag_name, 5)

    template = template_env.get_template('tag.json')
    data = template.render(dict(tag=tag, items=items))

    print(data)

    line_bot_api.reply_message(
        event.reply_token,
        FlexSendMessage(alt_text='tag',
                        contents=CarouselContainer.new_from_json_dict(
                            json.loads(data))))
Exemplo n.º 10
0
def send_msg(user_id, reply_token, msg):
    try:
        line_bot_api.reply_message(
            reply_token,
            FlexSendMessage(alt_text="trainings",
                            contents=CarouselContainer.new_from_json_dict(
                                json.loads(msg))))
        return
    except json.decoder.JSONDecodeError:
        pass
    except Exception as e:
        app.logger.error(e)
        return
    try:
        line_bot_api.reply_message(reply_token, TextSendMessage(text=msg))
    except Exception as e:
        app.logger.error(e)
        return
Exemplo n.º 11
0
def flex_oil():
    oil_obj = crawler.oil()
    oil_data = oil_obj.getData()

    oil_flex_container_json = json.load(open("container/oil.json", 'r', encoding="utf-8"))
    for i in range(2):
        oil_flex_container_json["contents"][i]["header"]["contents"][0]["text"] = oil_data[i][0]
        oil_flex_container_json["contents"][i]["body"]["contents"][0]["contents"][1]["text"] = str(oil_data[i][1])
        oil_flex_container_json["contents"][i]["body"]["contents"][2]["contents"][1]["text"] = str(oil_data[i][2])
        oil_flex_container_json["contents"][i]["body"]["contents"][4]["contents"][1]["text"] = str(oil_data[i][3])
        oil_flex_container_json["contents"][i]["body"]["contents"][6]["contents"][1]["text"] = str(oil_data[i][4])
        oil_flex_container_json["contents"][i]["footer"]["contents"][0]["text"] = oil_data[i][6] + '    ' + oil_data[i][
            5]

    oil_carousel_content = CarouselContainer.new_from_json_dict(oil_flex_container_json)
    flex_bubble_send_message = FlexSendMessage(alt_text="oil", contents=oil_carousel_content)

    return flex_bubble_send_message
Exemplo n.º 12
0
def flex_invoice():
    inv = crawler.invoice()
    old = inv.show(3)

    invoice_flex_container_json = json.load(open("container/invoice.json", 'r', encoding="utf-8"))

    for i in range(3):
        invoice_flex_container_json["contents"][i]["header"]["contents"][0]["text"] = old[i][0]
        invoice_flex_container_json["contents"][i]["body"]["contents"][0]["contents"][1]["text"] = old[i][1][0]
        invoice_flex_container_json["contents"][i]["body"]["contents"][2]["contents"][1]["text"] = old[i][1][1]
        invoice_flex_container_json["contents"][i]["body"]["contents"][4]["contents"][1]["text"] = old[i][1][2]
        invoice_flex_container_json["contents"][i]["body"]["contents"][5]["contents"][1]["text"] = old[i][1][3]
        invoice_flex_container_json["contents"][i]["body"]["contents"][6]["contents"][1]["text"] = old[i][1][4]
        invoice_flex_container_json["contents"][i]["body"]["contents"][8]["contents"][1]["text"] = ' '.join(
            old[i][1][5:])

    invoice_carousel_content = CarouselContainer.new_from_json_dict(invoice_flex_container_json)
    flex_bubble_send_message = FlexSendMessage(alt_text="invoice", contents=invoice_carousel_content)

    return flex_bubble_send_message
Exemplo n.º 13
0
def process_postback_event(event):
    query_string_dict = parse_qs(event.postback.data)
    user_profile = vars(line_bot_api.get_profile(event.source.user_id))
    user_id = user_profile["user_id"]
    if "menu" in query_string_dict.keys():
        pg.update_data(user_id, query_string_dict["menu"][0])
        linkRichMenuId = open(
            "data/" + query_string_dict.get('menu')[0] + '/rich_menu_id',
            'r').read()
        # link_rich_menu_to_user : 更換選單指令
        line_bot_api.link_rich_menu_to_user(event.source.user_id,
                                            linkRichMenuId)

        # 新聞頭條
        flexCarouselContainerJsonDict = create_news_message(
            query_string_dict.get('menu')[0], "首頁")
        if flexCarouselContainerJsonDict != "":
            carouselContent = CarouselContainer.new_from_json_dict(
                json.loads(flexCarouselContainerJsonDict))
            flexCarouselSendMeesage = FlexSendMessage(alt_text="新聞頭條",
                                                      contents=carouselContent)
            # 發送
            line_bot_api.reply_message(event.reply_token,
                                       flexCarouselSendMeesage)
Exemplo n.º 14
0
def handle_message(event):
    hands = ["グー", "チョキ", "パー"]
    battle_flg = False
    commands = {
        "bye": "グループを退会します。",
        "dir": "ディレクトリの表示をします。",
        "Test": "FlexMessageのテストを表示します。",
        "UserId": "UserIdを表示します。"
    }

    if event.message.text == 'じゃんけん':
        hands_img = {
            "グー":
            "https://image.middle-edge.jp/medium/d334db3f-010d-45f0-8999-d57c84e76677.jpg?1485589415",
            "チョキ":
            "https://www.sozai-library.com/wp-content/uploads/2015/07/5092-300x225.jpg",
            "パー":
            "https://image.jimcdn.com/app/cms/image/transf/none/path/se516d3bb2a89d52e/image"
            "/i65b87465dfb3a4ab/version/1551120498/image.jpg"
        }
        items = [
            QuickReplyButton(image_url=hands_img[hand],
                             action=MessageAction(label=f"{hand}",
                                                  text=f"{hand}"))
            for hand in hands
        ]
        messages = TextSendMessage(text="じゃーんけーん",
                                   quick_reply=QuickReply(items=items))
        client.reply_message(event.reply_token, messages=messages)
        battle_flg = True

    if event.message.text in hands and battle_flg:
        res_text = Janken.Rock_Paper_Scissors(event.message.text)
        client.reply_message(event.reply_token, TextSendMessage(res_text))
        battle_flg = False
        print(battle_flg)

    if event.message.text == 'help':
        cmd_mes = ''
        for cmd in commands:
            cmd_mes += cmd + ":"
            cmd_mes += commands[cmd] + "\n"
        client.reply_message(event.reply_token, TextSendMessage(cmd_mes))

    if event.message.text == "bye":
        client.reply_message(event.reply_token, TextSendMessage("See you!"))

        # グループトークからの退出処理
        if hasattr(event.source, "group_id"):
            client.leave_group(event.source.group_id)

        # ルームからの退出処理
        if hasattr(event.source, "room_id"):
            client.leave_room(event.source.room_id)

        return

    if event.message.text == 'UserId':
        client.reply_message(event.reply_token,
                             TextSendMessage(event.source.user_id))

    if event.message.text == 'Profile':
        profile = client.get_profile(event.source.user_id)
        name = profile.display_name  # -> 表示名
        userid = profile.user_id  # -> ユーザーID
        image = profile.picture_url  # -> 画像のURL
        client.reply_message(event.reply_token,
                             TextSendMessage(f"Name:{name}\nUserId:{userid}"))
        client.reply_message(
            event.reply_token,
            ImageSendMessage(original_content_url=image,
                             preview_image_url=image))

    if event.message.text == "dir":
        current_dir = os.getcwd()
        ls = os.listdir(current_dir)
        full_path = os.path.realpath(__file__)
        client.reply_message(
            event.reply_token,
            TextSendMessage(str(f"{current_dir}\n{str(ls)}\n{full_path}")))

    if event.message.text == "Test":
        try:
            item = "ぶりぶり"
            template = template_env.get_template('Test.json')
            data = template.render(dict(items=item))
            client.reply_message(
                event.reply_token,
                messages=FlexSendMessage(
                    alt_text='hello',
                    contents=CarouselContainer.new_from_json_dict(
                        json.loads(data))))
        except Exception as e:
            tb = sys.exc_info()[2]
            client.reply_message(
                event.reply_token,
                TextSendMessage(f"[Error]\nType:{str(type(e))}\n"
                                f"Args:{str(e.args)}\n"
                                f"Except:{str(e)}\n"
                                f"Mes:\n{e.with_traceback(tb)}"))
    '''client.reply_message(
Exemplo n.º 15
0
              "height": "md",
              "style": "primary",
              "gravity": "center"
            }
          ]
        }
      }
    ]
  }
"""

from linebot.models import (FlexSendMessage, CarouselContainer)

import json

carouselContent = CarouselContainer.new_from_json_dict(
    json.loads(flexCarouselContainerJsonDict))
flexCarouselSendMeesage = FlexSendMessage(alt_text="壓力",
                                          contents=carouselContent)

template_message_dict = {"Book": flexCarouselSendMeesage}

from collections import OrderedDict

x = OrderedDict()


# 每個人的狀態記下來用{ID:Q(n)}
# 不管輸入什麼都回應text的內容
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    user_profile = line_bot_api.get_profile(event.source.user_id)
Exemplo n.º 16
0
def omikuji(event):
    '''
    
    from jinja2 import Environment, FileSystemLoader, select_autoescape
    template_env = Environment(
        loader=FileSystemLoader('py-linebot/templates'),
        autoescape=select_autoescape(['html', 'xml', 'json'])
    )
    les = "les"
    template = template_env.get_template('test.json')
    data = template.render(dict(items=les))

    line_bot_api.reply_message(
        event.reply_token,
        FlexSendMessage(
            alt_text="items",
            contents=CarouselContainer.new_from_json_dict(json.loads(data))
        )
    )
    


 

    
    text=dic()
    #path="https://hackathon-engineer-omikuji.herokuapp.com/static/mikuji/base.jpg"
    #image = Image.open('py-linebot/static/mikuji/base.jpg')

    image_path,comment=make_mikuji(text)
    import os
    path = os.getcwd()
    files = os.listdir(path)
    print(type(files))  # <class 'list'>
    print(files) 

    url = f"https://winter-hackathon2020.herokuapp.com/static/mikuji/{image_path}"

    #image_path = "base.jpg"
    #comment='test'
    
    line_bot_api.reply_message(
        event.reply_token,
        TemplateSendMessage(
            alt_text="占い結果",
            template=ButtonsTemplate(
                text=comment + "だよ~",
                title="占い結果",
                image_size="cover",
                thumbnail_image_url=url,
                actions=[
                    URIAction(
                        uri="https://twitter.com/intent/tweet?" + 
                            urllib.parse.urlencode(
                            {
                                "img": url,
                                "hashtags": "えんじにあうらない",
                                "text": comment + "だよ~"
                            }
                        ),
                        label="Twitterで共有"
                    )
                ]
            )
        )
    )
Exemplo n.º 17
0
def handle_text_message(event):
    text = event.message.text
    print_source(event)
    result = ''

    if text.lower() == 'liff':
        line_bot_api.reply_message(event.reply_token, messages=TextSendMessage(text=get_liff_app('/liff')))
        return
    if 'live' in text.lower():
        data = rss_feed.get_live_feed()
        if len(data) > 0:
            carousel_data = rss_feed.create_live_flxed(data['data'])
            if carousel_data is not None:
                carousel_message = CarouselContainer.new_from_json_dict(carousel_data)
                line_bot_api.reply_message(event.reply_token, messages=FlexSendMessage(alt_text="โปรแกรมถ่ายทอดสดฟุตบอล", contents=carousel_message))

    if text.lower() == '@bot help':
        print_help(event)
        return
    if '@bot results=' in text.lower():
        league_name = text.lower().split('=')[1]
        if league_name in fixtures_header_color:
            results_pb = PostbackEvent(timestamp=time(), source=event.source, reply_token=event.reply_token,
            postback={
                'data': 'results={0}'.format(league_name)
            })
            handle_results(results_pb)
        else:
            print_help(event)
    if '@bot fixtures=' in text.lower():
        league_name = text.lower().split('=')[1]
        if league_name in fixtures_header_color:
            fixtures_pb = PostbackEvent(timestamp=time(), source=event.source, reply_token=event.reply_token,
            postback={
                'data': 'fixtures={0}'.format(league_name)
            })
            handle_fixtures(fixtures_pb)
        else:
            print_help(event)
    if '@bot teamnews=' in text.lower():
        team_name = text.lower().split('=')[1]
        if team_name in team_name_dict:
            teamnews_pb = PostbackEvent(timestamp=time(), source=event.source, reply_token=event.reply_token,
            postback={
                'data': 'team_news={0}'.format(team_name)
            })
            handle_team_news(teamnews_pb)
        else:
            print_help(event)
    if '@bot team=' in text.lower():
        team_name = text.lower().split('=')[1]
        if team_name in team_name_dict:
            team_pb = PostbackEvent(timestamp=time(), source=event.source, reply_token=event.reply_token,
            postback={
                'data': 'team={0}'.format(team_name_dict[team_name])
            })
            handle_teams(team_pb)
        else:
            print_help(event)
    if '@bot standings=' in text.lower():
        league_name = text.lower().split('=')[1]
        if league_name in fixtures_header_color:
            standings_pb = PostbackEvent(timestamp=time(), source=event.source, reply_token=event.reply_token,
            postback={
                'data': 'standings={0}'.format(league_name)
            })
            handle_standings(standings_pb)
        else:
            print_help(event)

    if text.lower() == 'news=bbc-sport':
        data = rss_feed.get_bbc_feed(5)
        result = football_news.get_news_bubble("#FEE63E", data)
    if text.lower() == 'news=sky-sport':
        data = rss_feed.get_skysports_feed(5)
        result = football_news.get_news_bubble("#BB0211", data, header_text_color="#ffffff")
    if text.lower() == 'news=goal.com':
        data = rss_feed.get_goal_feed(5)
        result = football_news.get_news_bubble("#091F2C", data, header_text_color="#ffffff")
    if text.lower() == 'news=guardian':
        data = rss_feed.get_guardian_feed(5)
        result = football_news.get_news_bubble("#09508D", data, header_text_color="#ffffff")
    if text.lower() == 'news=mirror':
        data = rss_feed.get_mirror_feed(5)
        result = football_news.get_news_bubble("#E80E0D", data, header_text_color="#ffffff")
    if text.lower() == 'news=shotongoal':
        data = rss_feed.get_shot_on_goal_feed(5)
        result = football_news.get_news_bubble("#1A1A1A", data, header_text_color="#ffffff")
    if text.lower() == 'news=soccersuck':
        data = rss_feed.get_soccersuck_feed(5)
        result = football_news.get_news_bubble("#197F4D", data)
    if text.lower() == 'news=dailymail':
        data = rss_feed.get_daily_mail_feed(5)
        result = football_news.get_news_bubble("#ffffff", data)
    if text.lower() == '@bot allnews':
        get_all_news(event.reply_token)

    if isinstance(result, BubbleContainer):
        line_bot_api.reply_message(event.reply_token, FlexSendMessage(alt_text='news', contents=result))
Exemplo n.º 18
0
def make_carousel_flex():
    message_template = FlexSendMessage(
        alt_text="ポートフォリオ",
        contents=CarouselContainer.new_from_json_dict(portfolio_data))
    return message_template
Exemplo n.º 19
0
def process_text_message(event):
    user_id = event.source.user_id
    # 讀取本地檔案,並轉譯成消息
    result_message_array = []
    if event.message.text == "#切換新聞台":
        # 切換新聞台
        quickReplyList = QuickReply(
            items=create_QuickReplyButton(['TVBS新聞', 'Yahoo新聞', '蘋果日報']))
        quickReplyTextSendMessage = TextSendMessage(text='請選擇新聞台',
                                                    quick_reply=quickReplyList)
        # 發送
        line_bot_api.reply_message(event.reply_token,
                                   quickReplyTextSendMessage)

    elif event.message.text == "#新聞頭條":
        user_profile = vars(line_bot_api.get_profile(user_id))
        select_news = pg.select_table(
            "select select_news from user_info where user_id='" + user_id +
            "';")[0][0]
        flexCarouselContainerJsonDict = create_news_message(select_news, "首頁")
        if flexCarouselContainerJsonDict != "":
            carouselContent = CarouselContainer.new_from_json_dict(
                json.loads(flexCarouselContainerJsonDict))
            flexCarouselSendMeesage = FlexSendMessage(alt_text="新聞頭條",
                                                      contents=carouselContent)
            # 發送
            line_bot_api.reply_message(event.reply_token,
                                       flexCarouselSendMeesage)
    elif event.message.text == "#新聞類別":
        user_profile = vars(line_bot_api.get_profile(user_id))
        select_news = pg.select_table(
            "select select_news from user_info where user_id='" + user_id +
            "';")[0][0]
        if select_news == "TVBS新聞":
            # 切換類別
            quickReplyList = QuickReply(
                items=create_QuickReplyButton(['焦點', '地方社會', '娛樂']))
            quickReplyTextSendMessage = TextSendMessage(
                text='請選擇類別', quick_reply=quickReplyList)
            # 發送
            line_bot_api.reply_message(event.reply_token,
                                       quickReplyTextSendMessage)
        elif select_news == "Yahoo新聞":
            # 切換類別
            quickReplyList = QuickReply(
                items=create_QuickReplyButton(['選舉', '財金', '娛樂', '運動']))
            quickReplyTextSendMessage = TextSendMessage(
                text='請選擇類別', quick_reply=quickReplyList)
            # 發送
            line_bot_api.reply_message(event.reply_token,
                                       quickReplyTextSendMessage)
        elif select_news == "蘋果日報":
            # 切換類別
            quickReplyList = QuickReply(
                items=create_QuickReplyButton(['焦點', '政治', '娛樂', '生活']))
            quickReplyTextSendMessage = TextSendMessage(
                text='請選擇類別', quick_reply=quickReplyList)
            # 發送
            line_bot_api.reply_message(event.reply_token,
                                       quickReplyTextSendMessage)
    elif event.message.text == "#隨機新聞":
        user_profile = vars(line_bot_api.get_profile(user_id))
        select_news = pg.select_table(
            "select select_news from user_info where user_id='" + user_id +
            "';")[0][0]
        if select_news == "TVBS新聞":
            class_array = ['首頁', '焦點', '地方社會', '娛樂']
            select_class = class_array[random.randint(0, len(class_array) - 1)]
            flexCarouselContainerJsonDict = create_news_message(
                select_news, select_class)
            if flexCarouselContainerJsonDict != "":
                carouselContent = CarouselContainer.new_from_json_dict(
                    json.loads(flexCarouselContainerJsonDict))
                flexCarouselSendMeesage = FlexSendMessage(
                    alt_text="隨機新聞", contents=carouselContent)
                # 發送
                line_bot_api.reply_message(event.reply_token,
                                           flexCarouselSendMeesage)
        elif select_news == "Yahoo新聞":
            class_array = ['首頁', '選舉', '財金', '娛樂', '運動']
            select_class = class_array[random.randint(0, len(class_array) - 1)]
            flexCarouselContainerJsonDict = create_news_message(
                select_news, select_class)
            if flexCarouselContainerJsonDict != "":
                carouselContent = CarouselContainer.new_from_json_dict(
                    json.loads(flexCarouselContainerJsonDict))
                flexCarouselSendMeesage = FlexSendMessage(
                    alt_text="Yahoo新聞", contents=carouselContent)
                # 發送
                line_bot_api.reply_message(event.reply_token,
                                           flexCarouselSendMeesage)
        elif select_news == "蘋果日報":
            class_array = ['首頁', '焦點', '政治', '娛樂', '生活']
            select_class = class_array[random.randint(0, len(class_array) - 1)]
            flexCarouselContainerJsonDict = create_news_message(
                select_news, select_class)
            if flexCarouselContainerJsonDict != "":
                carouselContent = CarouselContainer.new_from_json_dict(
                    json.loads(flexCarouselContainerJsonDict))
                flexCarouselSendMeesage = FlexSendMessage(
                    alt_text="蘋果日報", contents=carouselContent)
                # 發送
                line_bot_api.reply_message(event.reply_token,
                                           flexCarouselSendMeesage)

    elif "#" in event.message.text:
        user_profile = vars(line_bot_api.get_profile(user_id))
        select_news = pg.select_table(
            "select select_news from user_info where user_id='" + user_id +
            "';")[0][0]
        select_class = event.message.text.replace("#", "")
        flexCarouselContainerJsonDict = create_news_message(
            select_news, select_class)
        if flexCarouselContainerJsonDict != "":
            carouselContent = CarouselContainer.new_from_json_dict(
                json.loads(flexCarouselContainerJsonDict))
            flexCarouselSendMeesage = FlexSendMessage(alt_text="#",
                                                      contents=carouselContent)
            # 發送
            line_bot_api.reply_message(event.reply_token,
                                       flexCarouselSendMeesage)
Exemplo n.º 20
0
 def get_weather_aqi_daily_message(self, daily_data):
     flex_carousel = {"type": "carousel", "contents": []}
     for af in daily_data['aqi_forecast']:
         af['av'] = (af['max'] + af['min']) / 2
         current_date = datetime.now().date().strftime('%Y-%m-%d')
         if af['date'] < current_date:
             continue
         if af['av'] > 0 and af['av'] <= 50:
             bg_color = '#009966'
             aqi_level_text = 'Good'
             text_color = '#ffffff'
         elif af['av'] > 50 and af['av'] <= 100:
             bg_color = '#ffde33'
             aqi_level_text = 'Moderate'
             text_color = '#000000'
         elif af['av'] > 100 and af['av'] <= 150:
             bg_color = '#ff9933'
             aqi_level_text = 'Unhealthy for Sensitive Groups'
             text_color = '#000000'
         elif af['av'] > 150 and af['av'] <= 200:
             bg_color = '#cc0033'
             aqi_level_text = 'Unhealthy'
             text_color = '#ffffff'
         elif af['av'] > 200 and af['av'] <= 300:
             bg_color = '#660099'
             aqi_level_text = 'Very Unhealthy'
             text_color = '#ffffff'
         elif af['av'] > 300:
             bg_color = '#7e0023'
             aqi_level_text = 'Hazardous'
             text_color = '#ffffff'
         bubble = {
             "type": "bubble",
             "body": {
                 "type":
                 "box",
                 "layout":
                 "vertical",
                 "spacing":
                 "md",
                 "contents": [{
                     "type":
                     "text",
                     "text":
                     self._format_date(af['date'],
                                       to_format='%a, %-d %b %Y'),
                     "size":
                     "md",
                     "color":
                     text_color,
                     "weight":
                     "bold"
                 }, {
                     "type": "text",
                     "text": daily_data['station_name'],
                     "size": "xs",
                     "color": text_color,
                     "wrap": True
                 }, {
                     "type":
                     "text",
                     "text":
                     "{0} ~ {1}".format(af['min'], af['max']),
                     "size":
                     "3xl",
                     "wrap":
                     True,
                     "color":
                     text_color,
                     "weight":
                     "bold"
                 }, {
                     "type": "text",
                     "text": aqi_level_text,
                     "wrap": True,
                     "color": text_color,
                     "size": "sm"
                 }]
             },
             "styles": {
                 "body": {
                     "backgroundColor": bg_color
                 }
             }
         }
         flex_carousel['contents'].append(bubble)
     carousel_msg = CarouselContainer.new_from_json_dict(flex_carousel)
     return FlexSendMessage(alt_text='AQI Daily Forecast',
                            contents=carousel_msg)
Exemplo n.º 21
0
def handle_fixtures():
    response = getFixtures()
    if response.status_code == 200:
        matches = response.json()
        carousel_dict = {'type': 'carousel', 'contents': []}
        data_bubble_dict = {}
        for match in matches:
            dt = datetime.strptime(match['match_start_date'],
                                   '%Y-%m-%d %H:%M:%S')
            dt_local = dt - timedelta(hours=7)
            bubble_dict = {
                'type': 'bubble',
                'direction': 'ltr',
                'body': {
                    'type':
                    'box',
                    'layout':
                    'vertical',
                    'contents': [{
                        'type':
                        'box',
                        'layout':
                        'baseline',
                        'contents': [{
                            'type': 'icon',
                            'url': wc_logo_url,
                            'size': '3xl'
                        }, {
                            'type':
                            'text',
                            'weight':
                            'bold',
                            'color':
                            '#1DB446',
                            'size':
                            'md',
                            "text":
                            dt_local.date().strftime('%A %d %B %Y')
                        }]
                    }, {
                        'type': 'separator',
                        'margin': 'sm'
                    }, {
                        'type': 'box',
                        'layout': 'vertical',
                        'margin': 'sm',
                        'spacing': 'sm',
                        'contents': []
                    }]
                }
            }
            home_team_name = match['team_home_en']
            home_team_emoji = get_country_emoji(home_team_name)
            away_team_name = match['team_away_en']
            away_team_emoji = get_country_emoji(away_team_name)
            team_match_text = home_team_emoji + match[
                'team_home_th'] + ' vs ' + match[
                    'team_away_th'] + away_team_emoji
            if dt_local.date() not in data_bubble_dict:
                data_bubble_dict[dt_local.date()] = bubble_dict
                bubble = bubble_dict
            else:
                bubble = data_bubble_dict[dt_local.date()]
            bubble['body']['contents'][2]['contents'].append({
                'type':
                'box',
                'layout':
                'horizontal',
                'contents': [{
                    'type': 'text',
                    'text': team_match_text,
                    'size': 'sm',
                    'color': '#555555',
                    'wrap': True,
                    'flex': 9
                }, {
                    'type': 'text',
                    'text': dt.strftime('%H:%M'),
                    'size': 'sm',
                    'color': '#555555',
                    'flex': 0
                }, {
                    'type': 'image',
                    'url': ch[match['channel_code']],
                    'size': 'md',
                    "margin": 'sm'
                }]
            })

        for key, value in data_bubble_dict.items():
            if len(carousel_dict['contents']) > 10:
                break
            carousel_dict['contents'].append(value)
        return CarouselContainer.new_from_json_dict(carousel_dict)

    return None
 def menu_test(cls):
     return FlexSendMessage(alt_text="hello",
                            contents=CarouselContainer.new_from_json_dict(
                                cls.recipe_menu_tmp))
Exemplo n.º 23
0
 def get_aqi_daily_message(self, aqi_raw_data, limit=7):
     local_timezone = aqi_raw_data['timezone']
     daily_forecasts = aqi_raw_data['forecasts_daily']
     added_item = 0
     flex_carousel = {"type": "carousel", "contents": []}
     for index in range(0, len(daily_forecasts)):
         if added_item > limit:
             break
         bubble = {
             "type": "bubble",
             "direction": "ltr",
             "body": {
                 "type": "box",
                 "layout": "vertical",
                 "spacing": "sm",
                 "contents": []
             }
         }
         aqi = daily_forecasts[index]['aqius']
         styles = self._get_aqi_message_style(aqi)
         date_str = self._convert_str_to_date(
             daily_forecasts[index]['ts'],
             tz_str=local_timezone,
             output_date_format='%A %-d %B %Y')
         if date_str is not None:
             bubble['body']['contents'].extend([{
                 "type":
                 "text",
                 "text":
                 date_str,
                 "size":
                 "sm",
                 "align":
                 "center",
                 "color":
                 styles['text_color']
             }, {
                 "type":
                 "separator",
                 "color":
                 styles['text_color']
             }, {
                 "type":
                 "box",
                 "layout":
                 "horizontal",
                 "contents": [{
                     "type": "image",
                     "url": styles['icon_url'],
                     "aspectRatio": "1:1",
                     "flex": 0
                 }, {
                     "type":
                     "box",
                     "layout":
                     "vertical",
                     "contents": [{
                         "type": "text",
                         "text": "{0}".format(aqi),
                         "size": 'xxl',
                         "align": "center",
                         "weight": "bold",
                         "color": styles['text_color']
                     }, {
                         "type": "text",
                         "text": "US AQI",
                         "size": "xs",
                         "align": "center",
                         "color": styles['text_color']
                     }, {
                         "type": "text",
                         "text": styles['text'],
                         "size": styles['text_size'],
                         "align": "center",
                         "gravity": "center",
                         "weight": "bold",
                         "color": styles['text_color'],
                         "wrap": True
                     }]
                 }]
             }])
             bubble['styles'] = {
                 "body": {
                     "backgroundColor": styles['background_color']
                 }
             }
             added_item += 1
             bubble_container = BubbleContainer.new_from_json_dict(bubble)
             flex_carousel['contents'].append(bubble_container)
     carousel_container = CarouselContainer.new_from_json_dict(
         flex_carousel)
     return carousel_container