def test_carousel_container(self): arg = { 'contents': [ BubbleContainer(body=BoxComponent( layout='vertical', contents=[TextComponent(text='Hey')])), BubbleContainer(body=BoxComponent( layout='vertical', contents=[TextComponent(text='Foo')])), ] } self.assertEqual(self.serialize_as_dict(arg, type=self.CAROUSEL), CarouselContainer(**arg).as_json_dict())
def intro(self, name): bubble = BubbleContainer( # body body=BoxComponent( layout='vertical', spacing='md', contents=[ TextComponent(text='Hello {0},\n\n'.format(name), weight='bold', size='lg'), # main info TextComponent(text='我是呂明聲,現在就讀中央資管所碩一,熱愛開發、嘗試新技術,喜歡透過資訊科技解決問題 !\n\n如履歷所述,我曾擔任過資源教室助教及銀行資訊部實習生,喜歡協助同學也喜歡團隊合作解決問題,相信是TechFRESH不可或缺的Hack, everything 精神 !\n\n很高興能在這相遇,期望這是我們認識的開始!\n\nRegards,\nMing-Sheng,Lyu', size='md', wrap=True, color='#272727'), SeparatorComponent(margin='xl'), BoxComponent( layout = 'vertical', contents = [ SpacerComponent(size='md'), ButtonComponent( style='primary', height='sm', action=MessageAction(label="SAM's Skill", text='你會什麼?'), ) ] ) ] ) ) message = FlexSendMessage(alt_text="SAM's Intro", contents=bubble) return message
def handle_follow(event): print(event.source.user_id) template = template_env.get_template('welcome_message.json') data = template.render() data = eval(data) flex_message = FlexSendMessage(alt_text='下次產檢注意事項',contents=BubbleContainer.new_from_json_dict(data)) line_bot_api.reply_message(event.reply_token, flex_message)
def test_bubble_container(self): arg = { 'header': BoxComponent(layout='vertical', contents=[TextComponent(text='Header text')]), 'body': BoxComponent(layout='vertical', contents=[TextComponent(text='Body text')]), 'footer': BoxComponent(layout='vertical', contents=[TextComponent(text='Footer text')]), 'styles': BubbleStyle(header=BlockStyle(background_color='#00ffff'), hero=BlockStyle(background_color='#00ffff', separator=True), footer=BlockStyle(background_color='#00ffff', separator=True, separator_color='#00ffff')) } heros = [ ImageComponent(uri='https://example.com/flex/images/image.jpg'), BoxComponent(layout='vertical', contents=[TextComponent(text='Body text')]), ] for hero in heros: arg['hero'] = hero self.assertEqual(self.serialize_as_dict(arg, type=self.BUBBLE), BubbleContainer(**arg).as_json_dict())
def construct_multiple_choice(data): actions = [] for button in data.get("buttons"): actions.append( ButtonComponent( style="primary", height="sm", margin="md", action=MessageAction(label=button.get("title"), text=button.get("title")), )) bubble = BubbleContainer( direction="ltr", body=BoxComponent( layout="vertical", contents=construct_mc_header(data) + [ TextComponent( text=data.get("text"), size="md", margin="lg", wrap=True, ) ], ), footer=BoxComponent(layout="vertical", contents=actions), ) return bubble
def get_greeting_carousel(parts: list): buttons = [] elements = [] for i, part in enumerate(parts): elements.append( ButtonComponent(color='#097AC5', action=MessageAction(label=part, text=part))) if i % 2 == 1: buttons.append( BoxComponent(layout="horizontal", color='#097AC5', contents=list(elements))) elements = [] return CarouselContainer(contents=[ BubbleContainer( size='mega', body=BoxComponent( layout="vertical", background_color='#f8f8f8', contents=[ TextComponent( align='start', color='#222E38', text= '😇If wanna know me more, please click your interested section below!', size='md', weight='regular', wrap=True) ]), footer=BoxComponent(layout="vertical", padding_all='none', background_color='#F8F8F8', contents=list(buttons))) ])
def single(set1): for x in set1: mes = BubbleContainer( hero=ImageComponent(url=set1[x], size='full', align='center', aspect_ratio='13:13', aspect_mode='cover'), body=BoxComponent(layout='vertical', contents=[ TextComponent(margin='md', text=x, weight='bold', size='md', align='center'), SeparatorComponent(margin='xl', color='#0000FF'), BoxComponent(margin='md', layout='horizontal', spacing='xs', contents=[ ButtonComponent( style='link', color='#84C1FF', flex=1, height='sm', action=MessageAction( label="我的最愛", text='SeeMyLove')) ]) ])) return FlexSendMessage(alt_text="hello", contents=mes) else: return TextSendMessage(text="None img")
def createBubbleContainer(station_name, what_day, time1, time2, time3): bubble = BubbleContainer( direction="ltr", header=BoxComponent(layout="vertical", contents=[ BoxComponent(layout="horizontal", contents=[ TextComponent( text=station_name, weight="bold"), TextComponent(text=what_day) ]) ]), body=BoxComponent(layout="vertical", contents=[ BoxComponent(layout="horizontal", contents=[ TextComponent(text="↓Campus"), TextComponent(text=time1) ]), BoxComponent(layout="horizontal", contents=[ TextComponent(text="↓" + station_name), TextComponent(text=time2) ]), BoxComponent(layout="horizontal", contents=[ TextComponent(text="↓Campus"), TextComponent(text=time3) ]) ]), styles=BubbleStyle(body=BlockStyle(separator=True))) return bubble
def price(): mes = BubbleContainer( header=BoxComponent(layout='baseline', contents=[ TextComponent(text='Q5:價格預算', weight='bold', size='xxl', flex=2, align='center') ]), body=BoxComponent( layout='vertical', spacing='xs', contents=[ ButtonComponent(style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='100~350元', text='100~350元')), ButtonComponent(margin='xl', style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='351~600元', text='351~600元')), ButtonComponent(margin='xl', style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='600元以上', text='600元以上')) ])) message = FlexSendMessage(alt_text="hello", contents=mes) return message
def add_video(template, title, url, thumbnails): bubble = BubbleContainer( direction='ltr', hero=ImageComponent(url=thumbnails, size='full', aspect_ratio='20:13', aspect_mode='cover', gravity='center'), body=BoxComponent( layout='vertical', contents=[ # title TextComponent(text=title, wrap=True, weight='bold', size='xxl', align='center') ]), footer=BoxComponent(layout='vertical', spacing='sm', contents=[ SpacerComponent(size='sm'), ButtonComponent( style='link', height='sm', action=URIAction(label='點擊查看', uri=url), ) ]), ) template.contents.append(bubble) return template
def create_response(self): trashinfo = self._context['trash_info'][0] contents = [ TextComponent(text=self._context['text'], wrap=True, size='sm'), SeparatorComponent(), ] if trashinfo['name'] != '': contents.append( TextComponent(text='名前', color='#a0a0a0', size='sm')) contents.append( TextComponent(text=trashinfo['name'], wrap=True, size='sm')) if trashinfo['category'] != '': contents.append( TextComponent(text='種類', color='#a0a0a0', size='sm')) contents.append( TextComponent(text=trashinfo['category'], wrap=True, size='sm')) if trashinfo['note'] != '': contents.append( TextComponent(text='メモ', color='#a0a0a0', size='sm')) contents.append( TextComponent(text=trashinfo['note'], wrap=True, size='sm')) return FlexSendMessage( alt_text=self._context['text'], contents=BubbleContainer(body=BoxComponent( layout='vertical', contents=contents, spacing='md')))
def chain(): mes = BubbleContainer( header=BoxComponent(layout='baseline', contents=[ TextComponent(text='Q4:想購買的通路', weight='bold', size='xxl', flex=2, align='center') ]), body=BoxComponent( layout='vertical', spacing='xs', contents=[ ButtonComponent(style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='家樂福', text='家樂福')), ButtonComponent(margin='xl', style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='全聯', text='全聯')), ButtonComponent(margin='xl', style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='Costco', text='Costco')) ])) message = FlexSendMessage(alt_text="hello", contents=mes) return message
def res_user_status(event): profile = line_bot_api.get_profile(event.source.user_id) status_msg = profile.status_message if status_msg != "None": # LINEに登録されているstatus_messageが空の場合は、"なし"という文字列を代わりの値とする status_msg = "なし" message=FlexSendMessage( alt_text='ユーザー情報', contents=BubbleContainer( header=BoxComponent( layout="vertical", contents=[ TextComponent( text='text', align='center', gravity='center', contents=[ SpanComponent(text='ユーザー情報') ] ) ] ),#Header hero=ImageComponent( url=profile.picture_url, size="full", aspect_mode="fit", action=None ), body=BoxComponent( layout="vertical", contents=[ TextComponent( text='text', align='center', gravity='center', contents=[ SpanComponent(text=f'User Id: {profile.user_id}') ] ), TextComponent( text='text', align='center', gravity='center', contents=[ SpanComponent(text=f'Status Message: {status_msg}') ] ) ] ),#Body footer=BoxComponent( layout="vertical", contents=[ ButtonComponent( action=MessageAction(label="成功", text="?") ) ] )#Footer ) ) line_bot_api.reply_message(event.reply_token, messages=message)
def build_rabbit_adopt_content(): container = BubbleContainer( direction='ltr', body=BoxComponent( layout='vertical', contents=[ TextComponent(text='你還沒有兔子', weight='bold', size='xl'), SeparatorComponent(), BoxComponent(layout='horizontal', spacing='sm', contents=[ ButtonComponent( style='primary', height='sm', color='#95B9B4', action=MessageAction(label='領養兔子', text='領養兔子'), ), ButtonComponent(style='primary', height='sm', color='#95B9B4', action=MessageAction( label='沒事了', text='沒事了')) ]) ], ), ) return container
def test_template(): conn = model.Conn() # get all subject by class_id query_select_subject = 'SELECT * FROM subject WHERE id = %s' conn.query(query_select_subject, '2') row_subject = conn.cursor.fetchone() # get all topic by subject_id query_select_topic = 'SELECT * FROM topic WHERE subject_id = %s' conn.query(query_select_topic, '1') rows_topic = conn.cursor.fetchall() if len(rows_topic) == 0: # topic is empty line_bot_api.reply_message(event.reply_token, [TextMessage(text=constant.TOPIC_EMPTY)]) else: # topic exist contents = [] for row in rows_topic: contents.append( BubbleContainer( direction='ltr', body=BoxComponent( layout='vertical', contents=[ TextComponent(text=str(row['name']), margin='md', size='xl', align='center', gravity='center', weight='bold'), ButtonComponent(action=PostbackAction( label='Belajar', text='Belajar', data='action=material_learn&subject_id=' + str(row_subject['id']) + '&topic_id=' + str(row['id']))), ButtonComponent(action=PostbackAction( label='Diskusi', text='Diskusi', data='action=material_discussion&subject_id=' + str(row_subject['id']) + '&topic_id=' + str(row['id']))), ButtonComponent(action=PostbackAction( label='Latihan Soal', text='Latihan Soal', data='action=material_quiz&subject_id=' + str(row_subject['id']) + '&topic_id=' + str(row['id']))) ]))) flex_message = FlexSendMessage( alt_text='Carousel Topik', contents=CarouselContainer(contents=contents)) print('HERE, contents:', contents) print('HERE, flex_message:', flex_message) return 'OK'
def aroma(): mes = BubbleContainer( header=BoxComponent(layout='baseline', contents=[ TextComponent(text='Q2:喜歡的香氣', weight='bold', size='xxl', flex=2, align='center') ]), body=BoxComponent( layout='vertical', spacing='xs', contents=[ ButtonComponent(style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='花香 (ex:玫瑰花...)', text='花香')), ButtonComponent(margin='xl', style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='漿果 (ex:櫻桃...)', text='漿果')), ButtonComponent(margin='xl', style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='柑橘 (ex:檸檬...)', text='柑橘')), ButtonComponent(margin='xl', style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='熱帶水果 (ex:鳳梨...)', text='熱帶水果')), ButtonComponent(margin='xl', style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='淺色水果 (ex:杏桃...)', text='淺色水果')), ButtonComponent(margin='xl', style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='香料 (ex:胡椒...)', text='香料')), ButtonComponent(margin='xl', style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='土木 (ex:橡木桶...)', text='土木')) ])) message = FlexSendMessage(alt_text="hello", contents=mes) return message
def ci_post(): data = request.json drone_repo_name = data[ "drone_repo_name"] if "drone_repo_name" in data else "-" drone_commit_branch = data[ "drone_commit_branch"] if "drone_commit_branch" in data else "-" drone_commit_author = data[ "drone_commit_author"] if "drone_commit_author" in data else "-" drone_commit_message = data[ "drone_commit_message"] if "drone_commit_message" in data else "-" drone_build_event = data[ "drone_build_event"] if "drone_build_event" in data else "-" drone_build_status = data[ "drone_commit_status"] if "drone_commit_status" in data else "-" drone_commit_link = data[ "drone_commit_link"] if "drone_commit_link" in data else "-" build_status_color = "#33aa55" if drone_build_status.lower( ) == "success" else "#cc3d33" ci_build_number = data[ "ci_build_number"] if "ci_build_number" in data else "-" template = template_env.get_template(FLEX_JSON_FP) rendered_template = template.render( build_status_color=build_status_color, drone_repo_name=drone_repo_name, drone_commit_branch=drone_commit_branch, drone_commit_author=drone_commit_author, drone_commit_message=drone_commit_message, drone_build_event=drone_build_event, drone_build_status=drone_build_status, drone_commit_link=drone_commit_link, ci_build_number=ci_build_number, ) dict_template = eval(rendered_template) print("[DEBUG][dict_template]", dict_template) ### Random Pick PR Reviewer if pr and build success collection = MongoClient( env["mongo"]["url"])[env["mongo"]["db"]][env["mongo"]["collection"]] repo = collection.find_one({"repo_name": drone_repo_name}) users = list(repo["users"]) group_id = [(item["name"], item["group_id"]) for item in env["projects"] if item["name"] == drone_repo_name][0][1] flex_message = FlexSendMessage( alt_text="{} repo 有最新更動!".format(drone_repo_name), contents=BubbleContainer.new_from_json_dict(dict_template)) messages = list() if drone_build_event == "pull_request" and drone_build_status == "success": try: text_message = TextMessage(text="請 *{}* 負責審 PR !".format( random.choice(users)["user_name"])) except: text_message = TextMessage(text="孤單寂寞,沒有人關心我,嗚...") messages.append(text_message) messages.append(flex_message) line_bot_api.push_message(group_id, messages) return 'OK'
def handle_follow(event): r.set(event.source.user_id, "01") line_bot_api.link_rich_menu_to_user( event.source.user_id, "richmenu-4318d8c8dba62fc14de3fced2943e413") json = { "type": "bubble", "hero": { "type": "image", "url": request.url_root.replace("http://", "https://") + "/imgs/mercari_info.png", "size": "full", "aspectRatio": "8:4", "aspectMode": "cover", }, "body": { "type": "box", "layout": "vertical", "contents": [{ "type": "text", "text": "友達追加ありがとう!画像を送るとメルカリの出品用に「専用」「送料込み」等のテキストを追加するBotだよ。\n\n気に入ったら友達にもオススメしてね!", "weight": "bold", "size": "md", "wrap": True, }], }, "footer": { "type": "box", "layout": "vertical", "spacing": "sm", "contents": [{ "type": "button", "style": "primary", "height": "sm", "action": { "type": "uri", "label": "画像を選択", "uri": "line://nv/cameraRoll/multi", }, }], "flex": 0, }, } line_bot_api.reply_message( event.reply_token, [ FlexSendMessage(alt_text="代替テキスト", contents=BubbleContainer.new_from_json_dict(json)) ], )
def generate_search_bubble_from_key(key): search_bubble = BubbleContainer(body=BoxComponent( layout='vertical', contents=[ TextComponent( text='更多 {} 的搜尋結果'.format(key), action=URIAction( uri='https://search.books.com.tw/search/query/key/{}/cat/BKA' .format(key))) ])) return search_bubble
def show_menu_handler(group_id): print("[DEBUG] use show_menu_handler") template = template_env.get_template(PROJECTS_FLEX_JSON_FP) carousel_list = [] for proj in env["projects"]: if proj["group_id"] == group_id: rendered_template = template.render(project_name=proj["name"]) dict_template = eval(rendered_template) carousel_list.append( BubbleContainer.new_from_json_dict(dict_template)) template_opera = template_env.get_template(PROJECT_OPERA_FLEX_JSON_FP) dict_template_opera = eval(template_opera.render()) carousel_list.append( BubbleContainer.new_from_json_dict(dict_template_opera)) flex_message = FlexSendMessage(alt_text="請選擇專案加入", contents=CarouselContainer(carousel_list)) line_bot_api.push_message(group_id, flex_message)
def FlexWeatherTemplate(city, url, w, aqiindex, uvi): return (FlexSendMessage( alt_text=city + "-天氣及空氣品質 Flex", contents=BubbleContainer(body=BoxComponent( layout="vertical", padding_all="0px", contents=[ ImageComponent(url=url, gravity="center", margin="none", size="full", aspectRatio="1:1", aspectMode="cover"), BoxComponent( layout="vertical", padding_all="20px", position="absolute", contents=[ TextComponent(text=city, size="xl"), TextComponent(text=str( datetime.datetime.now(pytz.timezone( 'Asia/Taipei')).strftime("%Y/%m/%d %H:%M")), size="xs"), ImageComponent(url="https" + w.get_weather_icon_url()[4:], size="xxs", align="start"), TextComponent(text=status2ct(w.get_status()), size="xxl", weight="bold"), TextComponent(text=w.get_detailed_status(), size="xs"), TextComponent(text="溫度: " + str( round( w.get_temperature( unit='celsius')['temp'], 1)) + "°C" + " 濕度: " + str(w.get_humidity()) + "%", size="xl"), TextComponent(text="空氣品質: " + requests.get( 'https://data.epa.gov.tw/api/v1/aqx_p_432?api_key=9be7b239-557b-4c10-9775-78cadfc555e9&format=json&limit=1234' ).json()['records'][aqiindex]['AQI'] + "(" + aqi2rate( requests.get( 'https://data.epa.gov.tw/api/v1/aqx_p_432?api_key=9be7b239-557b-4c10-9775-78cadfc555e9&format=json&limit=100' ).json()['records'][aqiindex]['AQI']) + ")"), TextComponent( text="紫外線: " + str(round(float(uvi.json()['records'][0] ['UVI']))) + "(" + uvi2rate(uvi.json()['records'][0]['UVI']) + ")"), TextComponent( text="風速: " + str(round(w.get_wind()['speed'] * 18 / 5, 1)) + "km/h") ]) ]))))
def showimg(): mes = BubbleContainer(body=BoxComponent( layout='vertical', spacing='xs', contents=[ ButtonComponent(style='secondary', color='#FFEE99', height='sm', action=MessageAction(label='ShowImg', text='showImg')) ])) message = FlexSendMessage(alt_text="hello", contents=mes) return message
def get_total_flex(body_content,footer_content=[ButtonComponent(style='link',action=URIAction(label='My github', uri='https://github.com/kevin1061517?tab=repositories'))]): bubble = BubbleContainer( body=BoxComponent( layout='vertical', contents=body_content ), footer=BoxComponent( layout='vertical', spacing='sm', contents= footer_content ) ) return bubble
def test_flex_message(self): arg = { 'alt_text': 'this is a flex message', 'contents': BubbleContainer(body=BoxComponent(layout='vertical', contents=[ TextComponent(text='hello'), TextComponent(text='world') ])) } self.assertEqual(self.serialize_as_dict(arg, type=self.FLEX), FlexSendMessage(**arg).as_json_dict())
def getYoutubeBubble(url): bubble = BubbleContainer( direction='ltr', spacing='none', hero=ImageComponent( url=url, size='md', aspect_ratio="1:1", aspect_mode='cover', action=URIAction(label='RateBeer', uri=url), ), ) return bubble
def article_fetching(tag): files = [filename for filename in os.listdir('./article/') if filename.startswith(tag)] col = [] template = template_env.get_template('article.json') for file_name in files: print(file_name) with open('article/%s'%(file_name)) as f: article = json.load(f) pprint(article) data = template.render(article) data = eval(data) col.append(BubbleContainer.new_from_json_dict(data)) message = FlexSendMessage(alt_text='推薦文章', contents=CarouselContainer(contents=col)) return message
def get_line_group(dir_name): files = sorted([filename for filename in os.listdir(dir_name)]) col = [] template = template_env.get_template('line_group.json') for file_name in files: print(file_name) with open('%s%s'%(dir_name,file_name)) as f: group = json.load(f) pprint(group) data = template.render(group) data = eval(data) col.append(BubbleContainer.new_from_json_dict(data)) message = FlexSendMessage(alt_text='加入群組', contents=CarouselContainer(contents=col)) return message
def create_response(self): contents = [ TextComponent(text=self._context['text'], wrap=True, size='sm'), ] contents.append( ButtonComponent(style='primary', color=Colors['primary'], action=URIAction( label=self._context['button']['text'], uri=self._context['button']['uri']))) return FlexSendMessage( alt_text=self._context['text'], contents=BubbleContainer(body=BoxComponent( layout='vertical', contents=contents, spacing='md')))
def create_response(self): contents = [ TextComponent(text=self._context['text'], wrap=True, size='sm'), SeparatorComponent() ] for index, name in enumerate(self._context['trash_list']): contents.append( TextComponent(text=name, color='#0000ff', wrap=True, action=MessageAction(text=name))) return FlexSendMessage( alt_text=self._context['text'], contents=BubbleContainer(body=BoxComponent( layout='vertical', contents=contents, spacing='md')))
def arrival_timer_breaked(): return FlexSendMessage("集合時間になりました", BubbleContainer( size="mega", body=BoxComponent( layout="vertical", separator="true", contents=[ TextComponent( text="集合時間になりました", align="center", size="lg" ), ]), styles=BubbleStyle(body=BlockStyle(background_color="#ffffff")) ))