Exemple #1
0
def run(content_config, env, variables):
    news_info = NewsInfo()
    n_items = content_config.get('n_items', DEFAULT_N_ITEMS)
    user_id = GetUserId()

    limit = 200
    if env['platform_type'] == SupportedPlatform.Line:
        limit = 160

    if content_config['mode'] == 'get_content':
        return run_get_content(news_info, variables, limit)

    if content_config['mode'] == 'list_by_source':
        source_name = Resolve(content_config['query_term'], variables)
        return render_cards(
            news_info,
            news_info.trending(user_id, source_name, n_items))

    elif content_config['mode'] == 'prompt':
        m = Message(u'想要知道什麼呢?今天這些字最夯!')
        add_quick_reply_keywords(news_info, m)
        return [m]

    elif content_config['mode'] == 'search':
        query_term = Resolve(content_config['query_term'], variables)
        return render_cards(
            news_info,
            (news_info.search(query_term, n_items)
             if query_term else news_info.trending(user_id)))

    return render_cards(news_info, news_info.trending(user_id))
Exemple #2
0
def run(content_config, unused_env, variables):
    """
    content_config schema:
    {
       "response": "{{variable}",
    }
    """
    m = Message(Resolve(content_config['response'], variables))
    return [m]
Exemple #3
0
def run(content_config, unused_env, variables):
    """
    content_config schema:
    {
       "type": "random or query",
       "term": "query term if type is query",
       "max_count": 5, // max number of images to return
       "auth": {
           "client_id": "imgur client_id",
           "client_secret": "imgur client_secret"
       }
    }
    """
    client = imgurpython.ImgurClient(content_config['auth']['client_id'],
                                     content_config['auth']['client_secret'])

    if content_config['type'] == 'random':
        images = [
            x for x in client.gallery_random() if isinstance(x, GalleryImage)
        ]
    else:
        term = Resolve(content_config['term'], variables)
        images = [
            x for x in client.gallery_search(term)
            if isinstance(x, GalleryImage)
        ]

    images = random.sample(images, int(content_config['max_count']))

    m = Message()
    for i in images:
        c = Message.Bubble(i.title, i.link[:-4], i.link, i.description)
        c.add_button(
            Message.Button(Message.ButtonType.WEB_URL,
                           'Source',
                           url=i.link[:-4]))
        c.add_button(
            Message.Button(Message.ButtonType.POSTBACK,
                           'Like',
                           payload=TextPayload('like %s' % i.link)))
        m.add_bubble(c)

    return [Message('Here are the images you requested'), m]
Exemple #4
0
def run(content_config, unused_env, variables):
    """
    content_config schema:

    Platform dependent message:
    {
        'send_payload_to_current_node': False,
        'api_key': 'google geocoding api key',
        'query_term': 'query term',
        'language': 'zh_TW',
        'region': 'tw',
        'bounds': [
            {'lat': 23.816576, 'long': 119.781068},
            {'lat': 25.314444, 'long': 122.053702}
        ],
        'center': {'lat': 23.816576, 'long': 122.053702}
    }
    """
    query_term = Resolve(content_config['query_term'], variables)

    # Remove stop words
    query_term = re.sub(STOP_WORDS, '', query_term)

    cfg = content_config

    api = GoogleMapsPlaceAPI(content_config['api_key'])

    py_bounds = []
    for b in cfg.get('bounds', []):
        py_bounds.append([(b[0]['lat'], b[0]['long']),
                          (b[1]['lat'], b[1]['long'])])

    results = api.query_top_n(3, query_term, cfg['language'], cfg['region'],
                              py_bounds, cfg.get('center', None))

    in_currrent = content_config['send_payload_to_current_node']

    if not results:
        m = Message(u'對不起,我找不到這個地址, 請重新輸入 >_<')
    elif len(results) == 1:
        m = Message(u'你指的是「%s」嗎?' % results[0]['address'])
        m.add_quick_reply(
            Message.QuickReply(Message.QuickReplyType.TEXT,
                               u'是',
                               payload=LocationPayload(results[0]['location'],
                                                       in_currrent),
                               acceptable_inputs=[u'^對', '(?i)y', '(?i)ok']))
        m.add_quick_reply(
            Message.QuickReply(Message.QuickReplyType.TEXT,
                               u'否',
                               payload=EventPayload('WRONG_ADDRESS', None,
                                                    in_currrent),
                               acceptable_inputs=[u'不', '(?i)n']))
    else:
        m = Message(buttons_text=u'你指的是以下哪一個地址呢?')
        for r in results:
            m.add_button(
                Message.Button(Message.ButtonType.POSTBACK,
                               r['address'],
                               payload=LocationPayload(r['location'],
                                                       in_currrent)))
    return [m]
Exemple #5
0
def run(content_config, unused_env, variables):
    """
    content_config schema:
    {
       "api_key": "api_key",
       "send_payload_to_current_node": true,
       "location": "location variables",
       "max_count": 3
       "distance_threshold": 0.050,
       "display_weather": true
    }
    """

    location = Resolve(content_config['location'], variables)
    if 'coordinates' not in location:
        return [Message('不正確的輸入,請重新輸入')]

    c = (location['coordinates']['lat'], location['coordinates']['long'])
    youbike = YoubikeInfo()

    k = content_config.get('max_count', 5)
    size = (500, 260)

    stations = youbike.find_knn(k, c, content_config['distance_threshold'])
    if not stations:
        return [Message('對不起,這裡附近沒有 Ubike 站喔!')]

    m = GoogleStaticMapAPIRequestBuilder(content_config['api_key'], size)
    m.add_marker(c, 'purple')
    for s in stations:
        m.add_marker((float(s['lat']), float(s['lng'])))

    msgs = []

    # Construct main result cards.
    msg = Message()
    b = Message.Bubble(u'附近的 Ubike 站點',
                       image_url=m.build_url(),
                       subtitle=u'以下是最近的 %d 個站點' % k)

    best = stations[0]
    for s in stations:
        if s['sbi'] > 0:
            best = s
            break

    best_gps_coord = (float(best['lat']), float(best['lng']))
    b.add_button(Message.Button(Message.ButtonType.WEB_URL, u'帶我去',
                                url=m.build_navigation_url(best_gps_coord)))

    to_current = content_config['send_payload_to_current_node']
    b.add_button(Message.Button(Message.ButtonType.POSTBACK, u'再次查詢',
                                payload=LocationPayload(c, to_current)))
    msg.add_bubble(b)

    for s in stations:
        m.clear_markers()
        m.add_marker(c, 'purple')

        gps_coord = (float(s['lat']), float(s['lng']))
        m.add_marker(gps_coord, color='red')

        sbi, bemp = int(s['sbi']), int(s['bemp'])
        subtitle = u'剩餘數量: %d\n空位數量: %d\n' % (sbi, bemp)

        if sbi < 5:
            subtitle += (u'預計進車時間: %d 分鐘\n' %
                         youbike.average_waiting_time(
                             str(s['sno']), youbike.Direction.In))
        if bemp < 5:
            subtitle += (u'預計出位時間:%d 分鐘\n' %
                         youbike.average_waiting_time(
                             str(s['sno']), youbike.Direction.Out))

        b = Message.Bubble(s['ar'], image_url=m.build_url(), subtitle=subtitle)
        b.add_button(Message.Button(Message.ButtonType.WEB_URL,
                                    u'地圖導航',
                                    url=m.build_navigation_url(gps_coord)))
        msg.add_bubble(b)

    msgs.append(msg)

    if content_config['display_weather'] and 'weather' in best:
        # See http://openweathermap.org/weather-conditions
        # for weather codes.
        weather = best['weather']
        code = best['weather']['weather_code']
        temp = weather['temp']
        time = GetUserTime()

        if code / 100 == 3 or code in [500, 501, 520]:
            msgs.append(Message(u'提醒你,現在外面天雨路滑,騎車小心!'
                                u'記得帶傘或穿件雨衣唷'))
        elif (code / 100 == 2 or
              code in [502, 503, 504, 511, 521, 522, 531, 901, 902]):
            msgs.append(Message(u'現在外面大雨滂沱,不如叫個 Uber 吧!'))
        elif temp >= 30 and time.hour >= 10 and time.hour <= 16:
            msgs.append(Message(u'提醒你,現在外面天氣炎熱 (攝氏 %.1f 度) ,'
                                u'記得做好防曬唷' % temp))
    return msgs
Exemple #6
0
def run(content_config, unused_env, variables):
    drama_info = DramaInfo()
    n_items = content_config.get('n_items', DEFAULT_N_ITEMS)
    user_id = GetUserId()

    def append_categories_to_quick_reply(m):
        m.add_quick_reply(
            Message.QuickReply(Message.QuickReplyType.TEXT, u'荼蘼'))
        m.add_quick_reply(
            Message.QuickReply(Message.QuickReplyType.TEXT, u'The K2 第十集'))
        m.add_quick_reply(
            Message.QuickReply(Message.QuickReplyType.TEXT, u'熱門韓劇'))
        m.add_quick_reply(
            Message.QuickReply(Message.QuickReplyType.TEXT, u'熱門日劇'))
        m.add_quick_reply(
            Message.QuickReply(Message.QuickReplyType.TEXT, u'熱門台劇'))
        m.add_quick_reply(
            Message.QuickReply(Message.QuickReplyType.TEXT, u'熱門陸劇'))
        m.add_quick_reply(
            Message.QuickReply(Message.QuickReplyType.TEXT, u'通知設定'))
        return [m]

    if content_config['mode'] == 'subscribe':
        event = variables['event']
        drama_id = event.value['drama_id']
        Memory.Set('last_query_drama_id', drama_id)
        drama_info.subscribe(user_id, drama_id)

        episodes = drama_info.get_history(drama_id=drama_id,
                                          from_episode=0,
                                          backward=True)
        return ([
            Message(u'謝謝您的追蹤,'
                    u'我們會在有更新的時候通知您!'),
            Message(u'在等待的同時,'
                    u'您可以先看看之前的集數喲!')
        ] + render_episodes(episodes, variables))

    if content_config['mode'] == 'unsubscribe':
        event = variables['event']
        drama_id = event.value['drama_id']
        drama_info.unsubscribe(user_id, drama_id)

        return [Message(u'已成功取消訂閱')]

    if content_config['mode'] == 'get_history':
        event = variables['event']
        drama_id = event.value['drama_id']
        Memory.Set('last_query_drama_id', drama_id)
        from_episode = event.value['from_episode']
        backward = event.value['backward']
        episodes = drama_info.get_history(drama_id=drama_id,
                                          from_episode=from_episode,
                                          backward=backward)

        return render_episodes(episodes, variables)

    if content_config['mode'] == 'prompt':
        m = Message(u'你比較喜歡以下的什麼劇呢?')
        append_categories_to_quick_reply(m)
        return [m]

    country = content_config['mode'].replace('trending_', '')
    if content_config['mode'] == 'search':
        query_term = Resolve(content_config['query_term'], variables)
        dramas = drama_info.search(user_id, query_term, n_items)
        if dramas:
            if len(dramas) == 1:
                Memory.Set('last_query_drama_id', dramas[0].id)
            m = render_dramas(dramas)
            append_categories_to_quick_reply(m)
            return [m]
        m = Message(u'找不到耶!你可以換個關鍵字或試試熱門的類別:')
        append_categories_to_quick_reply(m)
        return [m]

    if content_config['mode'] == 'search_episode':
        if len(variables['matches']) == 3:
            dramas = drama_info.search(user_id, variables['matches'][1], 1)
            if dramas:
                Memory.Set('last_query_drama_id', dramas[0].id)

        drama_id = Memory.Get('last_query_drama_id')
        if drama_id:
            try:
                try:
                    serial_number = int(
                        Resolve(content_config['episode'], variables))
                except ValueError:
                    serial_number = convert_to_arabic_numbers(
                        Resolve(content_config['episode'], variables))
                episode = drama_info.get_episode(drama_id, serial_number)
            except Exception:
                return [Message('沒有這一集喔')]
            return render_episodes([episode], variables)
        else:
            return [Message('請先告訴我你要查的劇名')]

    m = render_dramas(drama_info.get_trending(user_id, country=country))
    append_categories_to_quick_reply(m)
    return [m]
Exemple #7
0
def run(content_config, unused_env, variables):
    """
    content_config schema:
    {
        "query_url": "http://ecshweb.pchome.com.tw/search/v3.3/all/results?"
                     "q=%s&page=1&sort=rnk/dc",
        "term": "{{matches#1}}",
        "max_count": 7,
        "list": "prods",
        "attributes": {
              "title": "${{price}}: {{name}}",
              "image": "http://a.ecimg.tw/{{picB}}",
              "item_url": "http://24h.pchome.com.tw/{{Id}}",
              "subtitle": "{{describe}}",
              "buttons": [
                  {
                      "type": "web_url",
                      "title": "商品頁面",
                      "url": "http://24h.pchome.com.tw/{{Id}}"
                  }
              ]
          }
    }
    """
    url = content_config['query_url']
    timeout = content_config.get('timeout_secs', DEFAULT_TIMEOUT_SECS)

    if 'term' in content_config:
        term = Resolve(content_config['term'], variables)
        url = url % urllib.quote(term.encode('utf-8'))

    try:
        content = json.loads(urllib2.urlopen(url, timeout=timeout).read())
    except Exception:
        return []

    max_count = content_config['max_count']
    attributes = content_config['attributes']
    elements = content.get(content_config['list'], [])

    if len(elements) > max_count:
        elements = elements[:max_count]

    m = Message()
    for element in elements:
        var = dict(variables, **element)
        bub = Message.Bubble(title=attributes['title'],
                             item_url=attributes.get('item_url', None),
                             image_url=attributes['image'],
                             subtitle=attributes.get('subtitle', None),
                             variables=var)

        for b in attributes.get('buttons', []):
            payload = b.get('payload', None)
            bub.add_button(
                Message.Button(
                    b_type=Message.ButtonType(b['type']),
                    title=b['title'],
                    url=b.get('url', None),
                    payload=TextPayload(payload) if payload else None,
                    variables=var))

        m.add_bubble(bub)

    return [m]