def sendButton(event): #按鈕樣版 try: message = TemplateSendMessage( alt_text='按鈕樣板', template=ButtonsTemplate( thumbnail_image_url= 'https://media-cdn.tripadvisor.com/media/photo-s/12/56/61/11/img-20180315-192402-01.jpg', #顯示的圖片 title='好吃的比薩', #主標題 text='請選擇:', #副標題 actions=[ MessageTemplateAction( #顯示文字計息 label='文字訊息', text='@購買披薩'), URITemplateAction( #開啟網頁 label='連結網頁', uri='http://www.e-happy.com.tw'), PostbackTemplateAction( #執行Postback功能,觸發Postback事件 label='回傳訊息', #按鈕文字 #text='@購買披薩', #顯示文字計息 data='action=buy' #Postback資料 ), ])) line_bot_api.reply_message(event.reply_token, message) except: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='發生錯誤!'))
def sendButton4(event): #按鈕樣版 try: message = TemplateSendMessage( alt_text='按鈕樣板', template=ButtonsTemplate( thumbnail_image_url='https://i.imgur.com/ZGaXkKd.jpg', title='demo', text='pizza demo', actions=[ MessageTemplateAction( #顯示文字計息 label='文字訊息', text='@購買披薩'), URITemplateAction( #開啟網頁 label='website mcu', uri='https://web.mcu.edu.tw/'), PostbackTemplateAction( #執行Postback功能,觸發Postback事件 label='回傳訊息', #按鈕文字 #text='@購買披薩', #顯示文字計息 data='action=buy' #Postback資料 ), ])) line_bot_api.reply_message(event.reply_token, message) except: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='發生錯誤!'))
def sendDatetime(event): #日期時間 try: message = TemplateSendMessage( alt_text='日期時間範例', template=ButtonsTemplate( thumbnail_image_url='https://i.imgur.com/VxVB46z.jpg', title='日期時間示範', text='請選擇:', actions=[ DatetimePickerTemplateAction( label="選取日期", data="action=sell&mode=date", #觸發postback事件 mode="date", #選取日期 initial="2019-06-01", #顯示初始日期 min="2019-01-01", #最小日期 max="2020-12-31" #最大日期 ), DatetimePickerTemplateAction( label="選取時間", data="action=sell&mode=time", mode="time", #選取時間 initial="10:00", min="00:00", max="23:59"), DatetimePickerTemplateAction( label="選取日期時間", data="action=sell&mode=datetime", mode="datetime", #選取日期時間 initial="2019-06-01T10:00", min="2019-01-01T00:00", max="2020-12-31T23:59") ])) line_bot_api.reply_message(event.reply_token, message) except: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='發生錯誤!'))
def foo(self, event): reply_token = event.reply_token button_message = TemplateSendMessage( alt_text='Button', template=ButtonsTemplate( thumbnail_image_url='https://i.imgur.com/eU7uJAJ.jpg', image_aspect_ratio="rectangle", image_size="contain", title='再來一次?', text='Please select', actions=[ MessageAction( label='Yes', text='Yes' ), MessageAction( label='No', text='No' ), ] ) ) send_text_message(reply_token, button_message) self.go_to_winning(event)
def sendButton(event): #按鈕樣版 try: message = TemplateSendMessage( alt_text='按鈕樣板', template=ButtonsTemplate( thumbnail_image_url="https://i.imgur.com/4QfKuz1.png", #顯示的圖片 title='按鈕樣版示範', #主標題 text='請選擇:', #副標題 actions=[ MessageTemplateAction( #顯示文字計息 label='文字訊息', text='@購買披薩'), URITemplateAction( #開啟網頁 label='連結網頁', uri="http://*****:*****@購買披薩', #顯示文字計息 data='action=buy' #Postback資料 ), ])) line_bot_api.reply_message(event.reply_token, message) except: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='發生錯誤!'))
def on_enter_rand_oniD(self, event): print("I'm entering oniD") reply_token = event.reply_token global sheetURL chosenMInfo = random.choice(os16List) if len(chosenMInfo) > 3: MusicTitle = "★" + chosenMInfo[1] + " " + chosenMInfo[0] + "[裏]" sheetURL = wrapImage(chosenMInfo[2], True) else: MusicTitle = "★" + chosenMInfo[1] + " " + chosenMInfo[0] sheetURL = wrapImage(chosenMInfo[2], False) bMsg = TMsg(alt_text='Button', template=ButtonsTemplate( thumbnail_image_url="https://i.imgur.com/vWbUSUf.png", title=MusicTitle, text="Please Select level to choose from.", actions=[ MsgAction(label="リセット", text="reset"), MsgAction(label="譜面を見るドン!♪", text="see_sheet"), MsgAction(label="同じ難しさで選ぶドン!♪", text="s16") ])) send_button_message(reply_token, bMsg)
def handle_text_message(event): if event.reply_token in ('00000000000000000000000000000000', 'ffffffffffffffffffffffffffffffff'): # Ignore a request for verification (when pressing 'VERIFY' button in developers console) return if event.message.text == 'a': reply_event = TemplateSendMessage( alt_text='Buttons template', template=ButtonsTemplate( thumbnail_image_url= 'https://upload.wikimedia.org/wikipedia/commons/thumb/5/54/Tel_aviv_long_exposure_public_domain_3.jpg/1024px-Tel_aviv_long_exposure_public_domain_3.jpg', title='Menu', text='Please select', actions=[ PostbackTemplateAction(label='postback', data='action=buy&itemid=1'), MessageTemplateAction(label='message', text='message text'), URITemplateAction(label='uri', uri='http://okdtsk.info') ])) else: reply_event = TextSendMessage( text='Reply to {}'.format(event.message.text)) line_bot_api.reply_message(event.reply_token, reply_event)
def openCameraRoll(event): #按鈕樣版 try: message = TemplateSendMessage( alt_text='按鈕樣板', template=ButtonsTemplate( thumbnail_image_url='https://i.imgur.com/4QfKuz1.png', #顯示的圖片 title='按鈕樣版示範', #主標題 text='請選擇:', #副標題 actions=[ URITemplateAction( #開啟相機 label='開啟相機', uri='line://nv/camera/'), URITemplateAction( #開啟相簿 label='開啟相簿', uri='line://nv/cameraRoll/single'), PostbackTemplateAction( #執行Postback功能,觸發Postback事件 label='回傳訊息', #按鈕文字 #text='@購買披薩', #顯示文字計息 data='action=buy' #Postback資料 ), ])) line_bot_api.reply_message(event.reply_token, message) except: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='發生錯誤!'))
def buttletemplate_weather_east(id): message = TemplateSendMessage( alt_text='Buttons template', template=ButtonsTemplate( # thumbnail_image_url='https://example.com/image.jpg', title='東部縣市', text='Please select', actions=[ MessageAction( label='宜蘭縣', text='宜蘭縣' ), MessageAction( label='花蓮縣', text='花蓮縣' ), MessageAction( label='臺東縣', text='臺東縣' ) ] ) ) line_bot_api.push_message(id,message)
def send(event): #按鈕樣版 try: message = TemplateSendMessage( alt_text='24HBOT', template=ButtonsTemplate( thumbnail_image_url='https://i.imgur.com/ts7gkps.png', #顯示的圖片 title='LINE對話機器人將會是下一個世代的App', #主標題 text= 'LINE在台灣擁有2100萬用戶,對台灣的公司商家而言,有90%的使用者不需要額外下載新的App,就可以溝通互動。', #副標題 actions=[ URITemplateAction( #開啟網頁 label='更多各行各業對話機器人', uri='https://www.chatbizz.biz'), URITemplateAction( #開啟網頁 label='更多免費LINE APP', uri='https://lin.ee/2EcRPEUs9'), URITemplateAction( label='訂閱或訂購', uri='https://unitbesto.wixsite.com/mysite') ])) line_bot_api.reply_message(event.reply_token, message) except: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='發生錯誤!'))
def registerMessage(registedstep=0): if registedstep == 1: message = TextSendMessage(text="請告知我您的身份證字號") elif registedstep == 2: message = TextSendMessage(text='請輸入使用者名稱') elif registedstep == 3: message = TemplateSendMessage( alt_text="工作選項", template=ButtonsTemplate(text="註冊成功,請選擇工作項目", actions=[ MessageTemplateAction( label='訂票去', text='訂票去', ), MessageTemplateAction(label='未註冊', text='未註冊'), MessageTemplateAction(label='查詢訂票', text='查詢訂票') ])) elif registedstep == 4: message = TextSendMessage(text="身份證字號已存在,請重新輸入身份證字號") elif registedstep == 5: message = TextSendMessage(text="使用者名稱已存在,請重新輸入使用者名稱") return message
def sendButton(event): #按鈕樣版 try: message = TemplateSendMessage( alt_text='洗錢小知識', template=ButtonsTemplate( thumbnail_image_url='https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTAbBLFzkUIGJndS970UI6i0B2jfTDs6Uy1AtyVMtMDuHwPWlWV&usqp=CAU', #顯示的圖片 title=' ', #主標題 text='查詢特定人士:', #副標題 actions=[ URITemplateAction( label='查詢公司名', uri='https://reurl.cc/AqXVEe' ), URITemplateAction( label='查詢董監事', uri='https://reurl.cc/AqXVEe' ), ] ) ) line_bot_api.reply_message(event.reply_token, message) except: line_bot_api.reply_message(event.reply_token,TextSendMessage(text='發生錯誤!'))
def display_failed_test_menu(self): """ Display Failed Tests Jobs """ button_template = ButtonsTemplate() job_list = jenkins.list_failed_job() if len(job_list) > 0: button_template.text = 'Please Select The Failed Test Jobs' button_template.thumbnail_image_url = '{0}/confirm_rerun_failed_test.jpg'.format( bucket_prefix) for job in job_list: job_name = job['name'] button_template.actions.append( PostbackAction(label=job_name, data='rerun_test={}'.format(job_name))) else: button_template.text = 'Congratulations! All Tests are Passed' button_template.thumbnail_image_url = 'https://images.pexels.com/photos/941693/pexels-photo-941693.jpeg' button_template.actions.append( PostbackAction(label='OK', data='OK')) return button_template
def handle_message(event): global countt Listentext = event.message.text Listentext = Listentext.lower() helptable="請輸入關鍵字來獲得更多訊息:\n-> 觀看自介影片:video\n-> 查看我的個人網頁:myweb\n-> 查看我的Github:github\n\n更詳盡的自我介紹請輸入:aboutme" if countt == 0: message = TextSendMessage(text=("Hello, 大家好~~\n我是廖莉祺(Claire Liao)\n"+helptable)) line_bot_api.reply_message(event.reply_token, message) countt = 1 elif countt==1: if Listentext=="video": message = VideoSendMessage( type="video", original_content_url='https://www.csie.ntu.edu.tw/~b04902046/profile_web_1.mp4', preview_image_url='https://www.csie.ntu.edu.tw/~b04902046/cx617.jpg' ) line_bot_api.reply_message(event.reply_token, message) elif "myweb" == Listentext: message = TemplateSendMessage( alt_text='Buttons template', template=ButtonsTemplate( thumbnail_image_url='https://xiao617.github.io/csx_linker/cx617.jpg', title='Myweb', text='View my web!', actions=[ URITemplateAction( label='view my web', uri='https://www.csie.ntu.edu.tw/~b04902046/' ) ] ) ) line_bot_api.reply_message(event.reply_token, message) elif "github" == Listentext: message = TemplateSendMessage( alt_text='Buttons template', template=ButtonsTemplate( thumbnail_image_url='https://avatars0.githubusercontent.com/u/9919?s=280&v=4', title='My Github', text='All my work is on github!', actions=[ URITemplateAction( label='view my github', uri='https://github.com/xiao617' ) ] ) ) line_bot_api.reply_message(event.reply_token, message) elif "aboutme" == Listentext: message = TextSendMessage(text="hello,我是廖莉祺\n目前就讀台大資工\n(你可以問我研究相關的問題\n或是輸入:返回)") line_bot_api.reply_message(event.reply_token, message) countt = 2 elif "123" == Listentext: hint = "我會唸詩還會說笑話啊" message = TextSendMessage(text=hint) stickerr = StickerSendMessage( package_id='1', sticker_id='2' ) line_bot_api.reply_message(event.reply_token, (message,stickerr)) countt = 3 else: message = TextSendMessage(text=helptable) line_bot_api.reply_message(event.reply_token, message) elif countt==2: if "返回" in Listentext: message = TextSendMessage(text=helptable) line_bot_api.reply_message(event.reply_token, message) countt = 1 elif "研究細節" in Listentext: myresearch = "computer vision:\n我主要是做Motion recognition\n以及360 image detection\nrobotics:\n是做機器人的控制\n特別是使用pepper\n\n如果你想知道我的研究經歷\n歡迎跟我聊,\n或是輸入:返回" message = TextSendMessage(text=myresearch) line_bot_api.reply_message(event.reply_token, message) elif "研究經歷" in Listentext: myresearch = "我目前是在台大傅立成教授的智慧機器人實驗室以及中研院劉庭祿教授的電腦視覺實驗室\n\n2017/2~now:智慧機器人實驗室\n2018/1~now:電腦視覺實驗室\n\n輸入:返回\n或是使用help" message = TextSendMessage(text=myresearch) line_bot_api.reply_message(event.reply_token, message) elif ("research" in Listentext) or ("Research" in Listentext) or ("研究" in Listentext) or ("專題" in Listentext): myresearch = "我的專題領域是:\n-> computer vision &\n-> robotics\n如果你想進一步了解\n可以跟我聊聊研究細節\n(如果你不知道該說什麼\n也可以使用help)" message = TextSendMessage(text=myresearch) line_bot_api.reply_message(event.reply_token, message) else: researchtable = "這部分你可以跟我聊聊:\n\t1.研究\n\t2.研究細節\n\t3.研究經歷\n\n或是輸入:返回" message = TextSendMessage(text=researchtable) line_bot_api.reply_message(event.reply_token, message)
def setUp(self): self.tested = LineBotApi('channel_secret') self.button_template_message = TemplateSendMessage( alt_text='Buttons template', template=ButtonsTemplate( thumbnail_image_url='https://example.com/image.jpg', title='Menu', text='Please select', actions=[ PostbackTemplateAction( label='postback', text='postback text', data='action=buy&itemid=1' ), MessageTemplateAction( label='message', text='message text' ), URITemplateAction( label='uri', uri='http://example.com/' ) ] ) ) self.button_message = [{ "type": "template", "altText": "Buttons template", "template": { "type": "buttons", "thumbnailImageUrl": "https://example.com/image.jpg", "title": "Menu", "text": "Please select", "actions": [ { "type": "postback", "label": "postback", "text": "postback text", "data": "action=buy&itemid=1" }, { "type": "message", "label": "message", "text": "message text" }, { "type": "uri", "label": "uri", "uri": "http://example.com/" } ] } }] self.confirm_template_message = TemplateSendMessage( alt_text='Confirm template', template=ConfirmTemplate( text='Are you sure?', actions=[ PostbackTemplateAction( label='postback', text='postback text', data='action=buy&itemid=1' ), MessageTemplateAction( label='message', text='message text' ) ] ) ) self.confirm_message = [{ "type": "template", "altText": "Confirm template", "template": { "type": "confirm", "text": "Are you sure?", "actions": [ { "type": "postback", "label": "postback", "text": "postback text", "data": "action=buy&itemid=1" }, { "type": "message", "label": "message", "text": "message text" } ] } }] self.carousel_template_message = TemplateSendMessage( alt_text='Carousel template', template=CarouselTemplate( columns=[ CarouselColumn( thumbnail_image_url='https://example.com' '/item1.jpg', title='this is menu1', text='description1', actions=[ PostbackTemplateAction( label='postback1', text='postback text1', data='action=buy&itemid=1' ), MessageTemplateAction( label='message1', text='message text1' ), URITemplateAction( label='uri1', uri='http://example.com/1' ) ] ), CarouselColumn( thumbnail_image_url='https://example.com' '/item2.jpg', title='this is menu2', text='description2', actions=[ PostbackTemplateAction( label='postback2', text='postback text2', data='action=buy&itemid=2' ), MessageTemplateAction( label='message2', text='message text2' ), URITemplateAction( label='uri2', uri='http://example.com/2' ) ] ) ] ) ) self.carousel_message = [{ "type": "template", "altText": "Carousel template", "template": { "type": "carousel", "columns": [ { "thumbnailImageUrl": "https://example.com/item1.jpg", "title": "this is menu1", "text": "description1", "actions": [ { "type": "postback", "label": "postback1", "text": "postback text1", "data": "action=buy&itemid=1" }, { "type": "message", "label": "message1", "text": "message text1" }, { "type": "uri", "label": "uri1", "uri": "http://example.com/1" } ] }, { "thumbnailImageUrl": "https://example.com/item2.jpg", "title": "this is menu2", "text": "description2", "actions": [ { "type": "postback", "label": "postback2", "text": "postback text2", "data": "action=buy&itemid=2" }, { "type": "message", "label": "message2", "text": "message text2" }, { "type": "uri", "label": "uri2", "uri": "http://example.com/2" } ] } ] } }]
def on_postback(event): user_id = event.source.user_id reply_token = event.reply_token post_data = event.postback.data if post_data == "工学部": line_bot_api.reply_message(event.reply_token, [ TextSendMessage( text="下のボタンから学科を選択してください。", quick_reply=QuickReply(items=[ QuickReplyButton( action=PostbackAction(label=major, data=major)) for major in major_list["工学部"] ])) ]) elif post_data == "ヘルプ": line_bot_api.reply_message(event.reply_token, [ TextSendMessage(text="""再登録をしたいとき・・・ 下の「学部再登録」のボタンを押してください。もう一度下にボタンが出現します。\n ご感想、エラー報告・・・ 「送信フォーム」のボタンを押してください。Googleフォームが現れ、匿名で送信できます。\n 鬼仏情報の投稿・・・ 「トンペー鬼仏表」のボタンを押してください。サイトに移動します。\n 経済学部の方・・・ 「ゼミ協」とテキストを送信してください。ゼミ協(東北大学経済学部)が運営するLINEbotの紹介リンクを送信します。"""), TemplateSendMessage( alt_text="選択ボタン", template=ButtonsTemplate( text="以下から選択してください", image_size="cover", actions=[ MessageAction(text="学部再登録", label="学部再登録"), URIAction(uri="https://forms.gle/XmjrKMPacj9H7nDH9", label="送信フォーム"), URIAction(uri="https://www.tonpe.site/toppages/index", label="トンペー鬼仏表") ])) ]) # 絞り込み検索 elif post_data[-1] == "論" or post_data[-1] == "学" or post_data[-1] == "語": lecture_group = post_data user_major = get_usermajor(user_id) if user_major: lecture_info = syllabus_db.search_lecture_info( lecture_group, user_major) # 講義情報の辞書のリストが返ってくる if (user_major == "機知" or user_major == "情物" or user_major == "化バイ" or user_major == "材料" or user_major == "建築" or user_major == "理") and post_data == "自然科学": line_bot_api.reply_message( event.reply_token, TextSendMessage(text="工,理は件数が多いため表示できません")) if len(lecture_info) < 10: line_bot_api.reply_message(event.reply_token, [ FlexSendMessage(alt_text='シラバス情報', contents=CarouselContainer([ gen_card_syllabus(dic, post_data) for dic in lecture_info[:10] ])), TextSendMessage(text=f"上記{len(lecture_info)}件の講義が見つかりました") ]) elif 10 < len(lecture_info) and len(lecture_info) <= 20: line_bot_api.reply_message(event.reply_token, [ FlexSendMessage(alt_text='シラバス情報', contents=CarouselContainer([ gen_card_syllabus(dic, post_data) for dic in lecture_info[:10] ])), FlexSendMessage(alt_text='シラバス情報', contents=CarouselContainer([ gen_card_syllabus(dic, post_data) for dic in lecture_info[10:20] ])), TextSendMessage(text=f"上記{len(lecture_info)}件の講義が見つかりました") ]) elif 20 < len(lecture_info) and len(lecture_info) <= 30: line_bot_api.reply_message(event.reply_token, [ FlexSendMessage(alt_text='シラバス情報', contents=CarouselContainer([ gen_card_syllabus(dic, post_data) for dic in lecture_info[:10] ])), FlexSendMessage(alt_text='シラバス情報', contents=CarouselContainer([ gen_card_syllabus(dic, post_data) for dic in lecture_info[10:20] ])), FlexSendMessage(alt_text='シラバス情報', contents=CarouselContainer([ gen_card_syllabus(dic, post_data) for dic in lecture_info[20:30] ])), TextSendMessage(text=f"上記{len(lecture_info)}件の講義が見つかりました") ]) # 所属登録が済んでいない場合 else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text="所属を登録してください")) else: # ユーザ情報をDBに格納 if post_data[-1] == "部": user_major = post_data[0] else: user_major = post_data user_db.add_userinfo(user_major, user_id) line_bot_api.reply_message( event.reply_token, TextSendMessage(text=post_data + "で登録しました!"))
def handle_message(event): text = event.message.text if text == "学部再登録": userid = event.source.user_id user_db.del_userinfo(userid) # user情報を削除 line_bot_api.reply_message(event.reply_token, [ TextSendMessage(text="現在登録されていた学部は削除されました。"), TextSendMessage( text="もう一度下のボタンから学部を選択してください。", quick_reply=QuickReply(items=[ QuickReplyButton( action=PostbackAction(label=major, data=major)) for major in major_list ])) ]) elif text == "送信フォーム": line_bot_api.reply_message( event.reply_token, TemplateSendMessage( alt_text="送信フォーム", template=ButtonsTemplate( text="送信フォーム", image_size="cover", actions=[ URIAction(uri="https://forms.gle/cAMusm8ZN8i4SmbL8", label="ご感想、ご要望はこちら") ]))) elif text == "ゼミ協": line_bot_api.reply_message( event.reply_token, TextSendMessage(text="https://lin.ee/bOegrZ3\n上記のリンクより友だち追加できます!")) #教官または講義名いずれかが送信されたとき.もしくはもう一度探すとき elif "_" not in text or "でもう一度探す" in text: if "でもう一度探す" in text: text = text.split("_")[0] teacherList = onihotoke_db.searchTeacher(text, False) #教員列からワードを検索 lectureList = onihotoke_db.searchLecture(text, False) #講義列からワードを検索 kibutsuList = [] #2つのリストを結合 1つは空であるはず. kibutsuList.extend(teacherList) kibutsuList.extend(lectureList) #検索結果が空でないとき,その検索結果をlabelにもつボタンを送信. if kibutsuList: #kibutsuListの要素数が20を超えないようにする. if len(kibutsuList) > 19: kibutsuList = random.sample( kibutsuList, 19) #一応シャッフルする.何回か表示すればすべての講義を見れるように. kibutsuList.extend(["でもう一度探す"]) #20個目 buttons_templates = [] roop = (len(kibutsuList) + 3) // 4 #最大4つまで表示できるテンプレートを何回表示すればいいか. for i in range(roop): #その回数だけ回す. if i == roop - 1: #最後は4つ以下になるからスライス部分を変える必要あり. buttons_templates.append( ButtonsTemplate(title='講義名を選択してください', text='choose the lecture name', actions=[ MessageAction( label=text + " " + name[:10], text=text + "_" + name) for name in kibutsuList[4 * i:] ])) break buttons_templates.append( ButtonsTemplate( title='講義名を選択してください', text='choose the lecture name', actions=[ MessageAction(label=text + " " + name[:10], text=text + "_" + name) for name in kibutsuList[4 * i:4 * (i + 1)] ])) try: line_bot_api.reply_message(event.reply_token, [ TemplateSendMessage(alt_text='講義を選択してください', template=buttons_template) for buttons_template in buttons_templates ]) # slackに報告 requests.post(SLACKBOT_SEARCH_KEYWORD, data=json.dumps({'text': "検索ワード : " + text})) except: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="エラーのため講義情報を表示できません。エラーは報告済みです。")) # slackに報告 requests.post(SLACKBOT_ERROR_KEYWORD, data=json.dumps({'text': "エラー検索ワード : " + text})) # 該当する講義がなかったとき else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text='該当する講義情報が見つかりませんでした。')) # slackに報告 requests.post(SLACKBOT_ERROR_KEYWORD, data=json.dumps({'text': "見つからなかった検索ワード : " + text})) #教官名と講義名のどちらも送信されたとき、その講義の鬼仏情報をユーザーに送信 elif "_" in text: texts = text.split("_") #『教官名_講義名』 という入力を期待している kibutsuList = onihotoke_db.searchAll(texts[0], texts[1].split(",")[0]) print(texts[1].split(",")[0]) #講義情報の辞書のリスト # print(kibutsuList) if kibutsuList: if len(kibutsuList) > 10: kibutsuList = random.sample( kibutsuList, 10) #一応シャッフルする.何回か表示すればすべての講義を見れるように. try: line_bot_api.reply_message( event.reply_token, FlexSendMessage(alt_text='鬼仏情報', contents=CarouselContainer([ gen_card_onihotoke(dic) for dic in kibutsuList ]))) # slackに報告 requests.post(SLACKBOT_SEARCH_KEYWORD, data=json.dumps({'text': "検索ワード : " + text})) except: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="エラーのため講義情報を表示できません。エラーは報告済みです。")) # slackに報告 SLACKBOT_WEBHOOK_URL = os.environ["SLACKBOT_ERROR_KEYWORD"] requests.post(SLACKBOT_ERROR_KEYWORD, data=json.dumps({'text': "エラー検索ワード : " + text})) # 該当する講義がなかったとき else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text='該当する講義情報が見つかりませんでした。')) # slackに報告 SLACKBOT_WEBHOOK_URL = os.environ["SLACKBOT_ERROR_KEYWORD"] requests.post(SLACKBOT_ERROR_KEYWORD, data=json.dumps({'text': "見つからなかった検索ワード : " + text})) #検索結果が空だったとき、その旨をユーザーに送信 else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='教官名または講義名を入力してください.')) # slackに報告 SLACKBOT_WEBHOOK_URL = os.environ["SLACKBOT_ERROR_KEYWORD"] requests.post(SLACKBOT_ERROR_KEYWORD, data=json.dumps({'text': "たぶん適当な検索ワード : " + text}))
def handle_text_message(event): text = event.message.text # 送られてきた言葉が植物の名前だった場合は、それをキャッシュし「なに?」と返す if user_data.plant_exists(text): current_plant = text line_bot_api.reply_message(event.reply_token, TextSendMessage(text='なに?')) if text == 'profile': if isinstance(event.source, SourceUser): profile = line_bot_api.get_profile(event.source.user_id) line_bot_api.reply_message(event.reply_token, [ TextSendMessage(text='なまえ: ' + profile.display_name), TextSendMessage(text='一言: ' + profile.status_message) ]) else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="「ユーザIDがないとこのコマンドは使えません」")) elif text == 'bye': if isinstance(event.source, SourceGroup): line_bot_api.reply_message(event.reply_token, TextSendMessage(text='またね、今までありがとう')) line_bot_api.leave_group(event.source.group_id) elif isinstance(event.source, SourceRoom): line_bot_api.reply_message(event.reply_token, TextSendMessage(text='またね、今までありがとう')) line_bot_api.leave_room(event.source.room_id) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text="ぼくはここから動けないよ...")) elif text == 'confirm': confirm_template = ConfirmTemplate(text='これでいい?', actions=[ MessageAction(label='Yes', text='はい!'), MessageAction(label='No', text='いいえ'), ]) 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=[ URIAction(label='Go to line.me', uri='https://line.me'), PostbackAction(label='ping', data='ping'), PostbackAction(label='ping with text', data='ping', text='ping'), MessageAction(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 == 'carousel': carousel_template = CarouselTemplate(columns=[ CarouselColumn(text='hoge1', title='fuga1', actions=[ URIAction(label='Go to line.me', uri='https://line.me'), PostbackAction(label='ping', data='ping') ]), CarouselColumn(text='hoge2', title='fuga2', actions=[ PostbackAction(label='ping with text', data='ping', text='ping'), MessageAction(label='Translate Rice', text='米') ]), ]) template_message = TemplateSendMessage(alt_text='Carousel alt text', template=carousel_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=DatetimePickerAction(label='datetime', data='datetime_postback', mode='datetime')), ImageCarouselColumn( image_url='https://via.placeholder.com/1024x1024', action=DatetimePickerAction( 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 == 'flex': bubble = BubbleContainer( direction='ltr', hero=ImageComponent(url='https://example.com/cafe.jpg', size='full', aspect_ratio='20:13', aspect_mode='cover', action=URIAction(uri='http://example.com', label='label')), body=BoxComponent( layout='vertical', contents=[ # title TextComponent(text='Brown Cafe', weight='bold', size='xl'), # review BoxComponent( layout='baseline', margin='md', contents=[ IconComponent( size='sm', url='https://example.com/gold_star.png'), IconComponent( size='sm', url='https://example.com/grey_star.png'), IconComponent( size='sm', url='https://example.com/gold_star.png'), IconComponent( size='sm', url='https://example.com/gold_star.png'), IconComponent( size='sm', url='https://example.com/grey_star.png'), TextComponent(text='4.0', size='sm', color='#999999', margin='md', flex=0) ]), # info BoxComponent( layout='vertical', margin='lg', spacing='sm', contents=[ BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent(text='Place', color='#aaaaaa', size='sm', flex=1), TextComponent(text='Shinjuku, Tokyo', wrap=True, color='#666666', size='sm', flex=5) ], ), BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent(text='Time', color='#aaaaaa', size='sm', flex=1), TextComponent( text="10:00 - 23:00", wrap=True, color='#666666', size='sm', flex=5, ), ], ), ], ) ], ), footer=BoxComponent( layout='vertical', spacing='sm', contents=[ # callAction, separator, websiteAction SpacerComponent(size='sm'), # callAction ButtonComponent( style='link', height='sm', action=URIAction(label='CALL', uri='tel:000000'), ), # separator SeparatorComponent(), # websiteAction ButtonComponent(style='link', height='sm', action=URIAction( label='WEBSITE', uri="https://example.com")) ]), ) message = FlexSendMessage(alt_text="hello", contents=bubble) line_bot_api.reply_message(event.reply_token, message) elif text == 'quick_reply': line_bot_api.reply_message( event.reply_token, TextSendMessage( text='Quick reply', quick_reply=QuickReply(items=[ QuickReplyButton( action=PostbackAction(label="label1", data="data1")), QuickReplyButton( action=MessageAction(label="label2", text="text2")), QuickReplyButton(action=DatetimePickerAction( label="label3", data="data3", mode="date")), QuickReplyButton(action=CameraAction(label="label4")), QuickReplyButton(action=CameraRollAction(label="label5")), QuickReplyButton(action=LocationAction(label="label6")), ]))) # ユーザからビーコンの設定を行う elif text == 'beacon': BeaconWhisperEvent(event.reply_token, line_bot_api, user_data).configBeaconMsg() # 植物を削除するときの命令 elif text == 'remove' or text == 'delete': if current_plant is not None: confirm_template = ConfirmTemplate( text=current_plant + "の情報を削除します\n本当によろしいですか?\n", actions=[ PostbackAction(label='Yes', data='delete_plant ' + current_plant, displayText='はい'), PostbackAction(label='No', data='delete_plant_cancel ' + current_plant, displayText='いいえ'), ]) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='植物が選択されていません')) elif text == 'disconnect' and current_plant is not None: plant_animator.disconnect() line_bot_api.reply_message(event.reply_token, TextMessage(text=current_plant + ":またね")) # 植物情報(plant)のアプデをかける elif text == 'update': plant_animator.update() if current_plant is None: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='どの植物に呼びかけますか?')) # text.split()[0] in (create, register) elif text.split()[0] in ('create', 'register'): plant_animator.register_plant(text.split[1]) line_bot_api.reply_message(event.reply_token, TextSendMessage(text='植物の名前を決めてあげてください!')) # この処理は工事中↑ # 方針としては一番最後にelse: で入れて、textを"create hoge"みたいに入れてもらってsplitして入れればい何とかなる(きもいけど) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.message.text))
def Build(self): bLen = len(self.buttons) if bLen == 0: return ([], None) carousels = [] while bLen > 15: carousels.append( TemplateSendMessage(alt_text=self.altTextHeader, template=CarouselTemplate(columns=[]))) car = carousels[-1] for k in range(1, 16): button = self.buttons.pop(0) colLen = len(car.template.columns) if colLen == 0: car.template.columns.append( CarouselColumn(text=self.columnText, actions=[])) elif len(car.template.columns[-1].actions) == 3: car.template.columns.append( CarouselColumn(text=self.columnText, actions=[])) car.template.columns[-1].actions.append( MessageTemplateAction(label=button.label, text=button.text)) car.alt_text = (car.alt_text + button.altTextEntry)[:400] bLen = bLen - 15 cbLen = 0 cols = 0 rows = 0 if bLen > 4: for i in range(1, 5): div = bLen // i if div > 3: continue if cbLen < div * i: cbLen = div * i cols = i rows = div elif cbLen == div * i and div > rows: cbLen = div * i cols = i rows = div bbLen = bLen - cbLen if cbLen > 0: carousels.append( TemplateSendMessage(alt_text=self.altTextHeader, template=CarouselTemplate(columns=[]))) count = 0 for button in self.buttons: count = count + 1 if count > cbLen: break car = carousels[-1] colLen = len(car.template.columns) if colLen == 0: car.template.columns.append( CarouselColumn(text=self.columnText, actions=[])) elif len(car.template.columns[-1].actions) == rows: if colLen == cols: carousels.append( TemplateSendMessage( alt_text=self.altTextHeader, template=CarouselTemplate(columns=[]))) car = carousels[-1] car.template.columns.append( CarouselColumn(text=self.columnText, actions=[])) car.template.columns[-1].actions.append( MessageTemplateAction(label=button.label, text=button.text)) car.alt_text = (car.alt_text + button.altTextEntry)[:400] car = carousels[-1] colLen = len(car.template.columns) if colLen == 0 or (colLen == 1 and len(car.template.columns[-1].actions) == 0): carousels.remove(car) elif len(car.template.columns[-1].actions) == 0: car.template.columns.remove(car.template.columns[-1]) but = None if bbLen > 0: but = TemplateSendMessage(alt_text=self.altTextHeader, template=ButtonsTemplate( text=self.columnText, actions=[])) for val in self.buttons[cbLen:]: but.template.actions.append( MessageTemplateAction(label=val.label, text=val.text)) but.alt_text = (but.alt_text + val.altTextEntry)[:400] return [carousels, but]
def handle_text_message(event): text = event.message.text if text == 'profile': if isinstance(event.source, SourceUser): profile = line_bot_api.get_profile(event.source.user_id) line_bot_api.reply_message(event.reply_token, [ TextSendMessage(text='Display name: ' + profile.display_name), TextSendMessage(text='Status message: ' + str(profile.status_message)) ]) else: line_bot_api.reply_message( event.reply_token, TextSendMessage( text="Bot can't use profile API without user ID")) elif text == 'quota': quota = line_bot_api.get_message_quota() line_bot_api.reply_message(event.reply_token, [ TextSendMessage(text='type: ' + quota.type), TextSendMessage(text='value: ' + str(quota.value)) ]) elif text == 'quota_consumption': quota_consumption = line_bot_api.get_message_quota_consumption() line_bot_api.reply_message(event.reply_token, [ TextSendMessage(text='total usage: ' + str(quota_consumption.total_usage)), ]) elif text == 'push': line_bot_api.push_message(event.source.user_id, [ TextSendMessage(text='PUSH!'), ]) elif text == 'multicast': line_bot_api.multicast([event.source.user_id], [ TextSendMessage(text='THIS IS A MULTICAST MESSAGE'), ]) elif text == 'broadcast': line_bot_api.broadcast([ TextSendMessage(text='THIS IS A BROADCAST MESSAGE'), ]) elif text.startswith('broadcast '): # broadcast 20190505 date = text.split(' ')[1] print("Getting broadcast result: " + date) result = line_bot_api.get_message_delivery_broadcast(date) line_bot_api.reply_message(event.reply_token, [ TextSendMessage(text='Number of sent broadcast messages: ' + date), TextSendMessage(text='status: ' + str(result.status)), TextSendMessage(text='success: ' + str(result.success)), ]) elif text == 'bye': if isinstance(event.source, SourceGroup): line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Leaving group')) line_bot_api.leave_group(event.source.group_id) elif isinstance(event.source, SourceRoom): line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Leaving group')) line_bot_api.leave_room(event.source.room_id) else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="Bot can't leave from 1:1 chat")) elif text == 'image': url = request.url_root + '/static/logo.png' app.logger.info("url=" + url) line_bot_api.reply_message(event.reply_token, ImageSendMessage(url, url)) elif text == 'confirm': confirm_template = ConfirmTemplate(text='Do it?', actions=[ MessageAction(label='Yes', text='Yes!'), MessageAction(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=[ URIAction(label='Go to line.me', uri='https://line.me'), PostbackAction(label='ping', data='ping'), PostbackAction(label='ping with text', data='ping', text='ping'), MessageAction(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 == 'carousel': carousel_template = CarouselTemplate(columns=[ CarouselColumn(text='hoge1', title='fuga1', actions=[ URIAction(label='Go to line.me', uri='https://line.me'), PostbackAction(label='ping', data='ping') ]), CarouselColumn(text='hoge2', title='fuga2', actions=[ PostbackAction(label='ping with text', data='ping', text='ping'), MessageAction(label='Translate Rice', text='米') ]), ]) template_message = TemplateSendMessage(alt_text='Carousel alt text', template=carousel_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=DatetimePickerAction(label='datetime', data='datetime_postback', mode='datetime')), ImageCarouselColumn( image_url='https://via.placeholder.com/1024x1024', action=DatetimePickerAction( 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 == 'flex': bubble = BubbleContainer( direction='ltr', hero=ImageComponent(url='https://example.com/cafe.jpg', size='full', aspect_ratio='20:13', aspect_mode='cover', action=URIAction(uri='http://example.com', label='label')), body=BoxComponent( layout='vertical', contents=[ # title TextComponent(text='Brown Cafe', weight='bold', size='xl'), # review BoxComponent( layout='baseline', margin='md', contents=[ IconComponent( size='sm', url='https://example.com/gold_star.png'), IconComponent( size='sm', url='https://example.com/grey_star.png'), IconComponent( size='sm', url='https://example.com/gold_star.png'), IconComponent( size='sm', url='https://example.com/gold_star.png'), IconComponent( size='sm', url='https://example.com/grey_star.png'), TextComponent(text='4.0', size='sm', color='#999999', margin='md', flex=0) ]), # info BoxComponent( layout='vertical', margin='lg', spacing='sm', contents=[ BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent(text='Place', color='#aaaaaa', size='sm', flex=1), TextComponent(text='Shinjuku, Tokyo', wrap=True, color='#666666', size='sm', flex=5) ], ), BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent(text='Time', color='#aaaaaa', size='sm', flex=1), TextComponent( text="10:00 - 23:00", wrap=True, color='#666666', size='sm', flex=5, ), ], ), ], ) ], ), footer=BoxComponent( layout='vertical', spacing='sm', contents=[ # callAction, separator, websiteAction SpacerComponent(size='sm'), # callAction ButtonComponent( style='link', height='sm', action=URIAction(label='CALL', uri='tel:000000'), ), # separator SeparatorComponent(), # websiteAction ButtonComponent(style='link', height='sm', action=URIAction( label='WEBSITE', uri="https://example.com")) ]), ) message = FlexSendMessage(alt_text="hello", contents=bubble) line_bot_api.reply_message(event.reply_token, message) elif text == 'flex_update_1': bubble_string = """ { "type": "bubble", "body": { "type": "box", "layout": "vertical", "contents": [ { "type": "image", "url": "https://scdn.line-apps.com/n/channel_devcenter/img/flexsnapshot/clip/clip3.jpg", "position": "relative", "size": "full", "aspectMode": "cover", "aspectRatio": "1:1", "gravity": "center" }, { "type": "box", "layout": "horizontal", "contents": [ { "type": "box", "layout": "vertical", "contents": [ { "type": "text", "text": "Brown Hotel", "weight": "bold", "size": "xl", "color": "#ffffff" }, { "type": "box", "layout": "baseline", "margin": "md", "contents": [ { "type": "icon", "size": "sm", "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png" }, { "type": "icon", "size": "sm", "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png" }, { "type": "icon", "size": "sm", "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png" }, { "type": "icon", "size": "sm", "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png" }, { "type": "icon", "size": "sm", "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gray_star_28.png" }, { "type": "text", "text": "4.0", "size": "sm", "color": "#d6d6d6", "margin": "md", "flex": 0 } ] } ] }, { "type": "box", "layout": "vertical", "contents": [ { "type": "text", "text": "¥62,000", "color": "#a9a9a9", "decoration": "line-through", "align": "end" }, { "type": "text", "text": "¥42,000", "color": "#ebebeb", "size": "xl", "align": "end" } ] } ], "position": "absolute", "offsetBottom": "0px", "offsetStart": "0px", "offsetEnd": "0px", "backgroundColor": "#00000099", "paddingAll": "20px" }, { "type": "box", "layout": "vertical", "contents": [ { "type": "text", "text": "SALE", "color": "#ffffff" } ], "position": "absolute", "backgroundColor": "#ff2600", "cornerRadius": "20px", "paddingAll": "5px", "offsetTop": "10px", "offsetEnd": "10px", "paddingStart": "10px", "paddingEnd": "10px" } ], "paddingAll": "0px" } } """ message = FlexSendMessage(alt_text="hello", contents=json.loads(bubble_string)) line_bot_api.reply_message(event.reply_token, message) elif text == 'quick_reply': line_bot_api.reply_message( event.reply_token, TextSendMessage( text='Quick reply', quick_reply=QuickReply(items=[ QuickReplyButton( action=PostbackAction(label="label1", data="data1")), QuickReplyButton( action=MessageAction(label="label2", text="text2")), QuickReplyButton(action=DatetimePickerAction( label="label3", data="data3", mode="date")), QuickReplyButton(action=CameraAction(label="label4")), QuickReplyButton(action=CameraRollAction(label="label5")), QuickReplyButton(action=LocationAction(label="label6")), ]))) elif text == 'link_token' and isinstance(event.source, SourceUser): link_token_response = line_bot_api.issue_link_token( event.source.user_id) line_bot_api.reply_message(event.reply_token, [ TextSendMessage(text='link_token: ' + link_token_response.link_token) ]) elif text == 'insight_message_delivery': today = datetime.date.today().strftime("%Y%m%d") response = line_bot_api.get_insight_message_delivery(today) if response.status == 'ready': messages = [ TextSendMessage(text='broadcast: ' + str(response.broadcast)), TextSendMessage(text='targeting: ' + str(response.targeting)), ] else: messages = [TextSendMessage(text='status: ' + response.status)] line_bot_api.reply_message(event.reply_token, messages) elif text == 'insight_followers': today = datetime.date.today().strftime("%Y%m%d") response = line_bot_api.get_insight_followers(today) if response.status == 'ready': messages = [ TextSendMessage(text='followers: ' + str(response.followers)), TextSendMessage(text='targetedReaches: ' + str(response.targeted_reaches)), TextSendMessage(text='blocks: ' + str(response.blocks)), ] else: messages = [TextSendMessage(text='status: ' + response.status)] line_bot_api.reply_message(event.reply_token, messages) elif text == 'insight_demographic': response = line_bot_api.get_insight_demographic() if response.available: messages = [ "{gender}: {percentage}".format(gender=it.gender, percentage=it.percentage) for it in response.genders ] else: messages = [TextSendMessage(text='available: false')] line_bot_api.reply_message(event.reply_token, messages) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.message.text))
def handle_text_message(event): inp_raw = event.message.text inp = inp_raw.lower() inp_split = inp.split() profile = susunhurufbot.get_profile(event.source.user_id) def reply_txt(msg): susunhurufbot.reply_message(event.reply_token,TextSendMessage(text=msg)) def reply_img(link): susunhurufbot.reply_message(event.reply_token,ImageSendMessage(original_content_url=link,preview_image_url=link)) if inp == '/help': carousel_template_message = TemplateSendMessage( alt_text='Bantuan umum', template=CarouselTemplate( columns=[ CarouselColumn( thumbnail_image_url='https://example.com/item1.jpg', title='Susun Kata Game', text='Tap salah satu', actions=[ MessageTemplateAction( label='Mulai Sekarang', text='/play' ), MessageTemplateAction( label='Aturan Main', text='/rule' ), MessageTemplateAction( label='Leaderboards', text='/leaderboard')]), CarouselColumn( thumbnail_image_url='https://example.com/item4.jpg', title='Lain - lain', text='Tap salah satu', actions=[ MessageTemplateAction( label='Tentang admin', text='/admin' ), MessageTemplateAction( label='Keluarkan aku', text='/leave' ), URITemplateAction( label='Kirim feedback', uri='http://s.id/FeedbackSusunHurufBot')]) ] ) ) susunhurufbot.reply_message(event.reply_token, carousel_template_message) # ------------------------------------------- Lain - Lain ------------------------------------------ # if inp == '/admin': about_button = TemplateSendMessage( alt_text='Info Admin', template=ButtonsTemplate( thumbnail_image_url='https://dl.dropboxusercontent.com/s/xjgb1az7tt7p7h3/admin_logo.png', title='Admin Susun Huruf Bot', text= 'Pradipta Gitaya (21 Tahun)', actions=[ MessageTemplateAction( label='Hubungi Admin', text= '/contactadmin' ), MessageTemplateAction( label='Catatan Admin', text= '/adminnotes' ),])) susunhurufbot.reply_message(event.reply_token, about_button) elif inp == '/adminnotes': reply_txt(admin_note_msg) elif inp == '/contactadmin': reply_txt(about_msg) elif inp == '/leave': def kick(): confirm_template = ConfirmTemplate(text='Keluarkan bot dari obrolan?', actions=[ MessageTemplateAction(label='Iya', text='Pergi sana!'), MessageTemplateAction(label='Tidak', text='Jangan keluarkan!'),]) template_message = TemplateSendMessage(alt_text='Konfirmasi kick', template=confirm_template) return susunhurufbot.reply_message(event.reply_token, template_message) if isinstance(event.source, SourceGroup): kick() elif isinstance(event.source, SourceRoom): kick() else: reply_txt('Ini chat 1:1 , gimana caranya aku bisa keluar dari sini coba :(') elif inp == ('Pergi sana!'.lower()): # Bot kick confirmation reply_txt('Sampai jumpa ~') if isinstance(event.source, SourceGroup): susunhurufbot.leave_group(event.source.group_id) elif isinstance(event.source, SourceRoom): susunhurufbot.leave_room(event.source.room_id) elif inp == ('Jangan keluarkan!'.lower()): # Bot kick confirmation return 'OK'
def handle_text_message(event): text = event.message.text cancel_message = 'type "cancel" to cancel search' if text == 'profile': if isinstance(event.source, SourceUser): profile = line_bot_api.get_profile(event.source.user_id) line_bot_api.reply_message( event.reply_token, [ TextSendMessage( text='Display name: ' + profile.display_name ), TextSendMessage( text='Status message: ' + profile.status_message ) ] ) else: line_bot_api.reply_message( event.reply_token, TextMessage(text="Bot can't use profile API without user ID")) elif text == 'bye': if isinstance(event.source, SourceGroup): line_bot_api.reply_message( event.reply_token, TextMessage(text='Leaving group')) line_bot_api.leave_group(event.source.group_id) elif isinstance(event.source, SourceRoom): line_bot_api.reply_message( event.reply_token, TextMessage(text='Leaving group')) line_bot_api.leave_room(event.source.room_id) else: line_bot_api.reply_message( event.reply_token, TextMessage(text="Bot can't leave from 1:1 chat")) 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 == 'carousel': carousel_template = CarouselTemplate(columns=[ CarouselColumn(text='hoge1', title='fuga1', actions=[ URITemplateAction( label='Go to line.me', uri='https://line.me'), PostbackTemplateAction(label='ping', data='ping') ]), CarouselColumn(text='hoge2', title='fuga2', actions=[ PostbackTemplateAction( label='ping with text', data='ping', text='ping'), MessageTemplateAction(label='Translate Rice', text='米') ]), ]) template_message = TemplateSendMessage( alt_text='Carousel alt text', template=carousel_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 == 'Find egg': #Actionnya masih gak ngerti gimana caranya actionnya text Category: Arabian aja image_carousel_template = ImageCarouselTemplate(columns=[ ImageCarouselColumn(image_url='https://www.theurbanlist.com/content/article/wysiwyg/three-williams-eggs.png', action=PostbackTemplateAction(label='Arabian egg\nRp 25.000,00',data='arabian-egg')), ImageCarouselColumn(image_url='https://www.fritzmag.com.au/wp-content/uploads/2016/12/Get-Your-Googie-On-With-South-Australian-Eggs-2.jpg', action=DatetimePickerTemplateAction(label='Australian egg\nRp 25.000,00', data='australian-egg')) ]) template_message = TemplateSendMessage( alt_text='ImageCarousel alt text', template=image_carousel_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'cancel': line_bot_api.reply_message( event.reply_token, TextMessage(text="Welcome...")) elif text == 'Category: Arabian': #Belum bisa actionnya juga image_carousel_template = ImageCarouselTemplate(columns=[ ImageCarouselColumn(image_url='https://www.theurbanlist.com/content/article/wysiwyg/three-williams-eggs.png', 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 == 'Choose Arabian egg': message = 'Arabian egg\n\nPrice: Rp. 25,000.00\nStore location: Yogya karapitan (Bandung)\nCondition: Good\n\nTo buy this product type "Buy Arabian egg"' line_bot_api.reply_message( event.reply_token, TextSendMessage(text=message)) elif text == 'Findstore Yogya': message = 'Search result for "Yogya"\n1. Yogya Karapitan\n2. Yogya Riau Junction\n3. Yogya Sunda\n4. Yogya Minimarket\n\nType number to choose shope e.g: 1 to choose Yogya Karapitan' line_bot_api.reply_message( event.reply_token, TextSendMessage(text=message)) elif text == '1': message = 'You choose Yogya Karapitan\n\nTo search products, type "Find <product name>\n\nTo view other instructions type "help"' line_bot_api.reply_message( event.reply_token, TextSendMessage(text=message)) elif text == 'list transactions': #Actionnya belum bisa nanti actionnya ke view transaction 15022 aja image_carousel_template = ImageCarouselTemplate(columns=[ ImageCarouselColumn(image_url='https://www.theurbanlist.com/content/article/wysiwyg/three-williams-eggs.png', action=DatetimePickerTemplateAction(label='date', data='date_postback', mode='date')), ImageCarouselColumn(image_url='https://www.fritzmag.com.au/wp-content/uploads/2016/12/Get-Your-Googie-On-With-South-Australian-Eggs-2.jpg', 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 == 'view transaction 15022': #Edit aja gambarnya + actionnya juga + labelnya juga masih dummy ini image_carousel_template = ImageCarouselTemplate(columns=[ ImageCarouselColumn(image_url='https://www.theurbanlist.com/content/article/wysiwyg/three-williams-eggs.png', action=DatetimePickerTemplateAction(label='date', data='date_postback', mode='date')), ]) elif text == 'Compare': image_carousel_template = ImageCarouselTemplate(columns=[ ImageCarouselColumn(image_url='https://www.theurbanlist.com/content/article/wysiwyg/three-williams-eggs.png', action=DatetimePickerTemplateAction(label='datetime', data='datetime_postback', mode='datetime')), ImageCarouselColumn(image_url='https://www.fritzmag.com.au/wp-content/uploads/2016/12/Get-Your-Googie-On-With-South-Australian-Eggs-2.jpg', action=DatetimePickerTemplateAction(label='date', data='date_postback', mode='date')) ]) template_message = TemplateSendMessage( alt_text='Choose one of these products to compare with <current_product>', template=image_carousel_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'Display all': line_bot_api.reply_message( event.reply_token, TextMessage(text="Arabian egg vs Mysterious egg\n\nShell:\nSpike shell vs Smooth shell\n\nShape:\nRound shape vs Oval shape\n\nSize:10inch vs 18inch\n\nColor:\nRed vs Cream.\n\nMysterious egg's exclusive properties:\nDoes not break when thrown with a force.\nIs not known if it's an actual egg.\n\nAustralian egg's exclusive properties:\n-")) elif text == 'Change': carousel_template = CarouselTemplate(columns=[ CarouselColumn(text='Mysterious egg', title='1', actions=[ URITemplateAction( label='Go to line.me', uri='https://line.me'), PostbackTemplateAction(label='ping', data='ping') ]), CarouselColumn(text='Arabian egg', title='2', actions=[ PostbackTemplateAction( label='ping with text', data='ping', text='ping'), MessageTemplateAction(label='Translate Rice', text='米') ]), ]) template_message = TemplateSendMessage( alt_text='Choose which one to replace.', template=carousel_template) line_bot_api.reply_message(event.reply_token, template_message)
print("Specify LINE_CHANNEL_SECRET as environment variable.") sys.exit(1) if channel_access_token is None: print("Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.") sys.exit(1) line_bot_api = LineBotApi(channel_access_token) parser = WebhookParser(channel_secret) canmessage = TemplateSendMessage( alt_text='Buttons template', template=ButtonsTemplate(thumbnail_image_url='https://ppt.cc/[email protected]', title='請問需要什麼服務?', text='如需更多功能請按其他鍵或輸入"其他"', actions=[ MessageTemplateAction(label='今日運勢', text='今日運勢'), MessageTemplateAction(label='火車訂票', text='火車訂票'), MessageTemplateAction(label='高鐵訂票', text='高鐵訂票'), MessageTemplateAction(label='其他', text='其他') ])) canmessage1 = TemplateSendMessage( alt_text='Buttons template', template=ButtonsTemplate(thumbnail_image_url='https://ppt.cc/[email protected]', title='請問需要什麼服務?', text='如需返回上一頁請按返回鍵或輸入"返回"', actions=[ MessageTemplateAction(label='今日各地天氣預報', text='今日各地天氣預報'), MessageTemplateAction(label='不要按我', text='不要按我'),
def handle_text_message(event): text = event.message.text if text == 'profile': if isinstance(event.source, SourceUser): profile = line_bot_api.get_profile(event.source.user_id) line_bot_api.reply_message(event.reply_token, [ TextSendMessage(text='Display name: ' + profile.display_name), TextSendMessage(text='Status message: ' + profile.status_message) ]) else: line_bot_api.reply_message( event.reply_token, TextSendMessage( text="Bot can't use profile API without user ID")) elif text == 'bye': if isinstance(event.source, SourceGroup): line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Leaving group')) line_bot_api.leave_group(event.source.group_id) elif isinstance(event.source, SourceRoom): line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Leaving group')) line_bot_api.leave_room(event.source.room_id) else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="Bot can't leave from 1:1 chat")) elif text == 'image': url = request.url_root + '/static/logo.png' app.logger.info("url=" + url) line_bot_api.reply_message(event.reply_token, ImageSendMessage(url, url)) elif text == 'confirm': confirm_template = ConfirmTemplate(text='Do it?', actions=[ MessageAction(label='Yes', text='Yes!'), MessageAction(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=[ URIAction(label='Go to line.me', uri='https://line.me'), PostbackAction(label='ping', data='ping'), PostbackAction(label='ping with text', data='ping', text='ping'), MessageAction(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 == 'carousel': carousel_template = CarouselTemplate(columns=[ CarouselColumn(text='hoge1', title='fuga1', actions=[ URIAction(label='Go to line.me', uri='https://line.me'), PostbackAction(label='ping', data='ping') ]), CarouselColumn(text='hoge2', title='fuga2', actions=[ PostbackAction(label='ping with text', data='ping', text='ping'), MessageAction(label='Translate Rice', text='米') ]), ]) template_message = TemplateSendMessage(alt_text='Carousel alt text', template=carousel_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=DatetimePickerAction(label='datetime', data='datetime_postback', mode='datetime')), ImageCarouselColumn( image_url='https://via.placeholder.com/1024x1024', action=DatetimePickerAction( 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 == 'flex': bubble = BubbleContainer( direction='ltr', hero=ImageComponent(url='https://example.com/cafe.jpg', size='full', aspect_ratio='20:13', aspect_mode='cover', action=URIAction(uri='http://example.com', label='label')), body=BoxComponent( layout='vertical', contents=[ # title TextComponent(text='Brown Cafe', weight='bold', size='xl'), # review BoxComponent( layout='baseline', margin='md', contents=[ IconComponent( size='sm', url='https://example.com/gold_star.png'), IconComponent( size='sm', url='https://example.com/grey_star.png'), IconComponent( size='sm', url='https://example.com/gold_star.png'), IconComponent( size='sm', url='https://example.com/gold_star.png'), IconComponent( size='sm', url='https://example.com/grey_star.png'), TextComponent(text='4.0', size='sm', color='#999999', margin='md', flex=0) ]), # info BoxComponent( layout='vertical', margin='lg', spacing='sm', contents=[ BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent(text='Place', color='#aaaaaa', size='sm', flex=1), TextComponent(text='Shinjuku, Tokyo', wrap=True, color='#666666', size='sm', flex=5) ], ), BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent(text='Time', color='#aaaaaa', size='sm', flex=1), TextComponent( text="10:00 - 23:00", wrap=True, color='#666666', size='sm', flex=5, ), ], ), ], ) ], ), footer=BoxComponent( layout='vertical', spacing='sm', contents=[ # callAction, separator, websiteAction SpacerComponent(size='sm'), # callAction ButtonComponent( style='link', height='sm', action=URIAction(label='CALL', uri='tel:000000'), ), # separator SeparatorComponent(), # websiteAction ButtonComponent(style='link', height='sm', action=URIAction( label='WEBSITE', uri="https://example.com")) ]), ) message = FlexSendMessage(alt_text="hello", contents=bubble) line_bot_api.reply_message(event.reply_token, message) elif text == 'quick_reply': line_bot_api.reply_message( event.reply_token, TextSendMessage( text='Quick reply', quick_reply=QuickReply(items=[ QuickReplyButton( action=PostbackAction(label="label1", data="data1")), QuickReplyButton( action=MessageAction(label="label2", text="text2")), QuickReplyButton(action=DatetimePickerAction( label="label3", data="data3", mode="date")), QuickReplyButton(action=CameraAction(label="label4")), QuickReplyButton(action=CameraRollAction(label="label5")), QuickReplyButton(action=LocationAction(label="label6")), ]))) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.message.text))
def handle_message(event): m = re.match(r'^([01][0-9]|2[0-3]):[0-5][0-9]$', event.message.text) conn = psycopg2.connect(DATABASE_URL) c = conn.cursor() if m != None: sql = "SELECT departure_time, arrival_time FROM time_record WHERE departure_time > '" + \ m.group(0)+"' limit 5;" c.execute(sql) ret = c.fetchall() if len(ret) == 3: line_bot_api.reply_message( event.reply_token, messages=TemplateSendMessage( alt_text="時刻検索結果", template=ButtonsTemplate( text="バス時刻表検索", actions=[ PostbackTemplateAction( label=ret[0][0].strftime("%H:%M") + "発 " + ret[0][1].strftime("%H:%M") + "着", data="is_show=0"), PostbackTemplateAction( label=ret[1][0].strftime("%H:%M") + "発 " + ret[1][1].strftime("%H:%M") + "着", data="is_show=1"), PostbackTemplateAction( label=ret[2][0].strftime("%H:%M") + "発 " + ret[2][1].strftime("%H:%M") + "着", data="is_show=2") ]))) elif len(ret) == 2: line_bot_api.reply_message( event.reply_token, messages=TemplateSendMessage( alt_text="時刻検索結果", template=ButtonsTemplate( text="バス時刻表検索", actions=[ PostbackTemplateAction( label=ret[0][0].strftime("%H:%M") + "発 " + ret[0][1].strftime("%H:%M") + "着", data="is_show=0"), PostbackTemplateAction( label=ret[1][0].strftime("%H:%M") + "発 " + ret[1][1].strftime("%H:%M") + "着", data="is_show=1") ]))) elif len(ret) == 1: line_bot_api.reply_message( event.reply_token, messages=TemplateSendMessage( alt_text="時刻検索結果", template=ButtonsTemplate( text="バス時刻表検索", actions=[ PostbackTemplateAction( label=ret[0][0].strftime("%H:%M") + "発 " + ret[0][1].strftime("%H:%M") + "着", data="is_show=0") ]))) elif len(ret) == 0: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="入力された時刻以降のバスはありません。")) else: line_bot_api.reply_message( event.reply_token, messages=TemplateSendMessage( alt_text="時刻検索結果", template=ButtonsTemplate( text="バス時刻表検索", actions=[ PostbackTemplateAction( label=ret[0][0].strftime("%H:%M") + "発 " + ret[0][1].strftime("%H:%M") + "着", data="is_show=0"), PostbackTemplateAction( label=ret[1][0].strftime("%H:%M") + "発 " + ret[1][1].strftime("%H:%M") + "着", data="is_show=1"), PostbackTemplateAction( label=ret[2][0].strftime("%H:%M") + "発 " + ret[2][1].strftime("%H:%M") + "着", data="is_show=2"), PostbackTemplateAction( label=ret[3][0].strftime("%H:%M") + "発 " + ret[3][1].strftime("%H:%M") + "着", data="is_show=3") ]))) else: line_bot_api.reply_message( event.reply_token, TextSendMessage( text= "出発したい時間を入力してください!\nその後の直近4件の発着時刻を教えます。\n(例)09:00, 12:00, 15:30\n※スクールバスや文◎の付いたバスは含んでいません。" ))
def handle_message(event): global website_name global question global registering_question global registered global during_survey global done global point global ans_count global tips if (event.message.text != 'ยัง'): if (registered == False): # table = get_table('users') print("Answer: " + event.message.text) if (len(registering_question) != 0): messages = [registering_question.pop(0)] # if (event.message.text == 'ช'): # table.update_item(Key={'user-id': get_current_user_id()}, AttributeUpdates={'gender': {'Value':'male','Action':'PUT'}}) # elif (event.message.text == '10/04/1992'): # table.update_item(Key={'user-id': get_current_user_id()}, AttributeUpdates={'dob': {'Value': event.message.text, 'Action': 'PUT'}, 'age':{'Value': 25, 'Action': 'PUT'}}) # elif (event.message.type == 'location'): # table.update_item(Key={'user-id': get_current_user_id()}, AttributeUpdates={'address': {'Value':event.message.address, 'Action':'PUT'}, 'latitude': {'Value':event.message.latitude, 'Action':'PUT'}, 'longitude': {'Value':event.message.longitude, 'Action':'PUT'}}) else: # if (event.message.text == '4'): # table.update_item(Key={'user-id': get_current_user_id()}, AttributeUpdates={'family-mem-no': {'Value':event.message.text, 'Action': 'PUT'}}) registered = True messages = [ 'ยินดีด้วย คุณได้กรอกประวัติเรียบร้อยแล้ว!', 'หากพร้อมแล้ว สามารถพิม "เริ่ม" ได้เลย' ] else: if (during_survey == True or event.message.text == 'เริ่ม'): # table = get_table('survey-answer') if not question and done is False: question = get_questionnaire(get_current_user_id()) if (len(question) != 0): during_survey = True messages = [question.pop(0)] if (len(question) == 0): done = True if (event.message.text != 'เริ่ม'): ans_count = ans_count + 1 print("Answer: " + event.message.text) # table.put_item(Item={'survey-id':'s001', 'answer-id': ans_count, 'user-id': 1, 'ans': event.message.text}) else: ans_count = ans_count + 1 print("Answer: " + event.message.text) # table.put_item(Item={'survey-id':'s001', 'answer-id': ans_count, 'user-id': 1, 'ans': event.message.text}) done = False during_survey = False point = point + 10 messages = [ 'Done!', 'ยินดีด้วย คุณได้ {} points!'.format(point), 'สามารถเช็คคะแนนล่าสุดของตัวเองได้โดยพิมว่า "คะแนน"' ] elif (event.message.text == 'คะแนน'): messages = [ 'ตอนนี้คุณมีคะแนนอยู่ทั้งหมด {} คะแนน'.format(point), 'หากต้องการแลกรางวัล สามารถพิม "{} ได้ทันที"'.format( 'แลกรางวัล') ] elif (event.message.text == 'แลกรางวัล'): messages = ['แลกได้ที่ www.{}.com/redeem'.format(website_name)] elif (event.message.text == 'tips'): messages = [random.choice(tips)['text']] else: messages = [ 'พิม "เริ่ม" ได้เสมอ เมื่อต้องการเริ่มเก็บคะแนนจากการทำแบบสอบถาม' ] else: messages = ['หากพร้อมแล้ว สามารถพิมคำว่า "สมัคร" ได้ตลอดเวลา'] if (messages[0] != 'do you love energy'): line_bot_api.reply_message( event.reply_token, [TextSendMessage(text=msg) for msg in messages]) else: line_bot_api.reply_message( event.reply_token, TemplateSendMessage(alt_text='Buttons template', template=ButtonsTemplate( title=messages[0], text='Please select', actions=[ MessageTemplateAction(label='A lot', text='3'), MessageTemplateAction(label='so so', text='2'), MessageTemplateAction(label='nah', text='1') ])))
def message_text(event): # check bot prefix if event.message.text.startswith(BOT_PREFIX): # seperate message contents as command and arguments message_body = event.message.text.strip()[1:].split() command = message_body[0] if(len(message_body) >= 2): arguments_list = message_body[1:] arguments_string = ' '.join(arguments_list) else: arguments_list = [] arguments_string = '' # echo command: reply arguments to user if command == 'echo': if(arguments_string != ''): line_bot_api.reply_message( event.reply_token, TextSendMessage(text=arguments_string) ) elif command == 'flex': bubble = BubbleContainer( direction='ltr', hero=ImageComponent( url='https://img.wongnai.com/p/1920x0/2017/12/30/19f2934940cf47669b2d1336feea0b97.jpg', size='full', aspect_ratio='4:3', aspect_mode='cover', action=URIAction(uri='https://github.com/miner46er/python-line-bot-sparta', label='label') ), body=BoxComponent( layout='vertical', contents=[ # title TextComponent(text='Brown Cafe', weight='bold', size='xl'), # review BoxComponent( layout='baseline', margin='md', contents=[ IconComponent(size='sm', url='https://cdn2.iconfinder.com/data/icons/default-1/100/.svg-4-512.png'), IconComponent(size='sm', url='https://freeiconshop.com/wp-content/uploads/edd/star-curved-outline.png'), IconComponent(size='sm', url='https://cdn2.iconfinder.com/data/icons/default-1/100/.svg-4-512.png'), IconComponent(size='sm', url='https://cdn2.iconfinder.com/data/icons/default-1/100/.svg-4-512.png'), IconComponent(size='sm', url='https://freeiconshop.com/wp-content/uploads/edd/star-curved-outline.png'), TextComponent(text='4.0', size='sm', color='#999999', margin='md', flex=0) ] ), # info BoxComponent( layout='vertical', margin='lg', spacing='sm', contents=[ BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent( text='Place', color='#aaaaaa', size='sm', flex=1 ), TextComponent( text='Shinjuku, Tokyo', wrap=True, color='#666666', size='sm', flex=5 ) ], ), BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent( text='Time', color='#aaaaaa', size='sm', flex=1 ), TextComponent( text="10:00 - 23:00", wrap=True, color='#666666', size='sm', flex=5, ), ], ), ], ) ], ), footer=BoxComponent( layout='vertical', spacing='sm', contents=[ # callAction, separator, websiteAction SpacerComponent(size='sm'), # callAction ButtonComponent( style='link', height='sm', action=URIAction(label='CALL', uri='tel:000000'), ), # separator SeparatorComponent(), # websiteAction ButtonComponent( style='link', height='sm', action=URIAction(label='WEBSITE', uri="https://github.com/miner46er/python-line-bot-sparta") ) ] ), ) message = FlexSendMessage(alt_text="hello", contents=bubble) line_bot_api.reply_message( event.reply_token, message ) elif command == 'buttons': buttons_template = ButtonsTemplate( title='My buttons sample', text='Hello, my buttons', actions=[ URIAction(label='Go to line.me', uri='https://line.me'), PostbackAction(label='ping', data='ping'), PostbackAction(label='ping with text', data='ping', text='ping'), MessageAction(label='Translate Rice', text='米') ]) menu_pesan = TemplateSendMessage( alt_text='Buttons alt text', template=buttons_template) line_bot_api.reply_message(event.reply_token, menu_pesan) elif command == 'pesan': order_memo = BOT_PREFIX + command + ' ' + arguments_string if len(arguments_list) == 0: pilihan_menu = ImageCarouselTemplate(columns=[ ImageCarouselColumn( image_url='https://via.placeholder.com/512x512', action=MessageAction(label='Nasi Putih', text=BOT_PREFIX + command + ' putih') ), ImageCarouselColumn( image_url='https://via.placeholder.com/512x512', action=MessageAction(label='Nasi Umami', text=BOT_PREFIX + command + ' umami') ) ]) menu_pesan = TemplateSendMessage( alt_text='Menu pesanan', template=pilihan_menu) line_bot_api.reply_message(event.reply_token, menu_pesan) elif len(arguments_list) == 1: if RICE_TYPE.count(arguments_list[0]) == 1: pilihan_menu = ImageCarouselTemplate(columns=[ ImageCarouselColumn( image_url='https://via.placeholder.com/512x512', action=MessageAction(label='Ayam', text=order_memo + ' ayam') ), ImageCarouselColumn( image_url='https://via.placeholder.com/512x512', action=MessageAction(label='Cumi', text=order_memo + ' cumi') ), ImageCarouselColumn( image_url='https://via.placeholder.com/512x512', action=MessageAction(label='Campur', text=order_memo + ' campur') ) ]) menu_pesan = TemplateSendMessage( alt_text='Menu pesanan', template=pilihan_menu) line_bot_api.reply_message(event.reply_token, menu_pesan) else: order_mistake(event) elif 2 <= len(arguments_list) <= 5 and arguments_list[-1] != 'selesai': if validate_order(arguments_list, -1): sauce_template = ImageCarouselTemplate(columns=[ ImageCarouselColumn( image_url='https://via.placeholder.com/512x512', action=MessageAction(label='XO', text=order_memo + ' xo') ), ImageCarouselColumn( image_url='https://via.placeholder.com/512x512', action=MessageAction(label='Mayonnaise', text=order_memo + ' mayo') ), ImageCarouselColumn( image_url='https://via.placeholder.com/512x512', action=MessageAction(label='Bumbu Bali', text=order_memo + ' bali') ), ImageCarouselColumn( image_url='https://via.placeholder.com/512x512', action=MessageAction(label='Blackpepper', text=order_memo + ' blackpepper') ) ]) sauce_choice = TemplateSendMessage( alt_text='Menu saus', template=sauce_template) confirm_button = ButtonsTemplate( text=('Pesananmu sekarang:' + '\nNasi : ' + arguments_list[0] + '\nTopping : ' + arguments_list[1] + '\nSaus(max 4): ' + ', '.join(arguments_list[2:])), actions=[ MessageAction(label='Selesai memesan', text=order_memo + ' selesai') ]) order_confirm = TemplateSendMessage( alt_text='Pesanan saat ini', template=confirm_button) line_bot_api.reply_message(event.reply_token, [sauce_choice, order_confirm]) else: order_mistake(event) elif (len(arguments_list) == 6) and (arguments_list[-1] != 'selesai'): if validate_order(arguments_list, -1): summary_button = ButtonsTemplate( text=('Apakah pesanan sudah benar?' + '\nNasi : ' + arguments_list[0] + '\nTopping : ' + arguments_list[1] + '\nSaus(max 4): ' + ', '.join(arguments_list[2:])), actions=[ MessageAction(label='Selesai memesan', text=order_memo + ' selesai') ]) order_summary = TemplateSendMessage( alt_text='Konfirmasi pesanan', template=summary_button) line_bot_api.reply_message(event.reply_token, order_summary) elif len(arguments_list) >= 3 and arguments_list[-1] == 'selesai': if validate_order(arguments_list, -2): line_bot_api.reply_message( event.reply_token, TextSendMessage(text='Pesanan dikirim!') ) else: order_mistake(event) else: order_mistake(event)
def get_template(input_text): endDate = datetime.today().strftime('%Y-%m-%d') startDate = (datetime.today() - timedelta(days=30)).strftime('%Y-%m-%d') if input_text == "[reset]": return TextSendMessage( text='你可以輸入任何人名,例如:蔡英文,我就會統計出他/她最近最常發生的事件種類, 並提供進一步查詢。', quick_reply=QuickReply( items=[ QuickReplyButton( action=MessageAction(label="蔡英文", text="蔡英文") ), QuickReplyButton( action=MessageAction(label="韓國瑜", text="韓國瑜") ), QuickReplyButton( action=MessageAction(label="郭台銘", text="郭台銘") )] )) elif ":" not in input_text: events = get_events(input_text, startDate, endDate) if len(events) == 0: return TextSendMessage( text='沒有這個人,或他/她的新聞數太少QAQ') elif len(events) <= 9: all_columns = [] all_actions = [] for i in range(len(events)): all_actions.append(MessageTemplateAction( label="...".join(events[i]['term'].split()) + " (" + str(events[i]["freq"]) + ")", text=input_text + ":" + events[i]['term'] )) if (i + 1) % 3 == 0: all_columns.append(CarouselColumn( title='{}相關新聞事件'.format(input_text), text='點選可獲得相關新聞', actions=all_actions )) all_actions = [] else: events = events[:8] all_columns = [] all_actions = [] for i in range(9): if i == 8: all_actions.append(MessageTemplateAction( label="more", text="更多事件" + ":" + str(8) + ":" + input_text )) else: all_actions.append(MessageTemplateAction( label="...".join(events[i]['term'].split()) + " (" + str(events[i]["freq"]) + ")", text=input_text + ":" + events[i]['term'] )) if (i + 1) % 3 == 0: all_columns.append(CarouselColumn( title='{}相關新聞事件'.format(input_text), text='點選可獲得相關新聞', actions=all_actions )) all_actions = [] buttons_template = TemplateSendMessage( alt_text='Carousel template', template=CarouselTemplate( columns=all_columns ) ) return buttons_template elif "更多事件" in input_text: _, id_event, input_text = input_text.split(":") id_event = int(id_event) events = get_events(input_text, startDate, endDate) action_lst = [] for i in range(3): action_lst.append(MessageTemplateAction( label="...".join(events[id_event + i]['term'].split()) + " (" + str(events[id_event]["freq"]) + ")", text=input_text + ":" + events[id_event + i]['term'] )) if len(events[id_event + 3:]) > 3: action_lst.append(MessageTemplateAction( label="more", text="更多事件" + ":" + str(id_event + 3) + ":" + input_text )) buttons_template = TemplateSendMessage( alt_text='Buttons Template', template=ButtonsTemplate( title='{}相關新聞事件'.format(input_text), text='點選可獲得相關新聞', actions=action_lst ) ) return buttons_template elif "more" in input_text: _, id, key, events = input_text.split(":") id = int(id) news = get_news(key, events, startDate, endDate) news_lst = news["data"][id:id + 3] id = id + 3 isMore = len(news["data"][id:]) != 0 flex_template = news_template_flex(news_lst, events, key, id, isMore) return flex_template else: key, events = input_text.split(":") news = get_news(key, events, startDate, endDate) news_lst = news["data"][:3] id = 3 isMore = len(news["data"]) > 3 flex_template = news_template_flex(news_lst, events, key, id, isMore) return flex_template
def handle_text_message(event): text = event.message.text if text == 'profile': if isinstance(event.source, SourceUser): profile = line_bot_api.get_profile(event.source.user_id) line_bot_api.reply_message(event.reply_token, [ TextSendMessage(text='Display name: ' + profile.display_name), TextSendMessage(text='Status message: ' + profile.status_message) ]) else: line_bot_api.reply_message( event.reply_token, TextSendMessage( text="Bot can't use profile API without user ID")) elif text == 'bye': if isinstance(event.source, SourceGroup): line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Leaving group')) line_bot_api.leave_group(event.source.group_id) elif isinstance(event.source, SourceRoom): line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Leaving group')) line_bot_api.leave_room(event.source.room_id) else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="Bot can't leave from 1:1 chat")) elif text == 'confirm': confirm_template = ConfirmTemplate(text='Do it?', actions=[ MessageAction(label='Yes', text='Yes!'), MessageAction(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=[ URIAction(label='Go to line.me', uri='https://line.me'), PostbackAction(label='ping', data='ping'), PostbackAction(label='ping with text', data='ping', text='ping'), MessageAction(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 == 'carousel': carousel_template = CarouselTemplate(columns=[ CarouselColumn(text='hoge1', title='fuga1', actions=[ URIAction(label='Go to line.me', uri='https://line.me'), PostbackAction(label='ping', data='ping') ]), CarouselColumn(text='hoge2', title='fuga2', actions=[ PostbackAction(label='ping with text', data='ping', text='ping'), MessageAction(label='Translate Rice', text='米') ]), ]) template_message = TemplateSendMessage(alt_text='Carousel alt text', template=carousel_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=DatetimePickerAction(label='datetime', data='datetime_postback', mode='datetime')), ImageCarouselColumn( image_url='https://via.placeholder.com/1024x1024', action=DatetimePickerAction( 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 else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.message.text))
def message_text(event): text = event.message.text acak = np.arange(14) np.random.shuffle(acak) if text == 'Kategori': buttons_template = ButtonsTemplate( text='Daftar Kategori Berita', actions=[ MessageTemplateAction(label='Tekno', text='tekno'), MessageTemplateAction(label='Bisnis', text='bisnis'), MessageTemplateAction(label='Otomotif', text='otomotif'), MessageTemplateAction(label='Bantuan', text='bantu') ]) template_message = TemplateSendMessage(alt_text='Daftar Kategori', template=buttons_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'bye astro' or text == 'Bye Astro': if isinstance(event.source, SourceGroup): line_bot_api.reply_message(event.reply_token, TextMessage(text='Kakak jahat :(')) line_bot_api.leave_group(event.source.group_id) elif isinstance(event.source, SourceRoom): line_bot_api.reply_message(event.reply_token, TextMessage(text='Jahat :(')) line_bot_api.leave_room(event.source.room_id) else: line_bot_api.reply_message(event.reply_token, TextMessage(text="gabisa ih :p")) elif text == 'creator' or text == 'Creator': if isinstance(event.source, SourceGroup): line_bot_api.reply_message( event.reply_token, TextMessage(text='http://line.me/ti/p/OdcxbZg6gQ')) elif text == 'tekno': databerita = listBerita("http://tekno.kompas.com/business") daftarberita = databerita.daftarBerita() carousel_template = CarouselTemplate(columns=[ CarouselColumn( text=daftarberita[acak[0]]['judul'], actions=[ PostbackTemplateAction(label="Ringkas", data=daftarberita[acak[0]]['link'], text='ringkas'), URITemplateAction(label='Baca berita asli', uri=daftarberita[acak[0]]['link']) ]), CarouselColumn( text=daftarberita[acak[1]]['judul'], actions=[ PostbackTemplateAction(label="Ringkas", data=daftarberita[acak[1]]['link'], text='ringkas'), URITemplateAction(label='Baca berita asli', uri=daftarberita[acak[1]]['link']) ]), CarouselColumn( text=daftarberita[acak[2]]['judul'], actions=[ PostbackTemplateAction(label="Ringkas", data=daftarberita[acak[2]]['link'], text='ringkas'), URITemplateAction(label='Baca berita asli', uri=daftarberita[acak[2]]['link']) ]), CarouselColumn( text=daftarberita[acak[3]]['judul'], actions=[ PostbackTemplateAction(label="Ringkas", data=daftarberita[acak[3]]['link'], text='ringkas'), URITemplateAction(label='Baca berita asli', uri=daftarberita[acak[3]]['link']) ]) ]) template_message = TemplateSendMessage(alt_text='Daftar Berita Tekno', template=carousel_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'bisnis': databerita = listBerita("http://bisniskeuangan.kompas.com/bisnis") daftarberita = databerita.daftarBerita() carousel_template = CarouselTemplate(columns=[ CarouselColumn( text=daftarberita[acak[0]]['judul'], actions=[ PostbackTemplateAction(label="Ringkas", data=daftarberita[acak[0]]['link'], text='ringkas'), URITemplateAction(label='Baca berita asli', uri=daftarberita[acak[0]]['link']) ]), CarouselColumn( text=daftarberita[acak[1]]['judul'], actions=[ PostbackTemplateAction(label="Ringkas", data=daftarberita[acak[1]]['link'], text='ringkas'), URITemplateAction(label='Baca berita asli', uri=daftarberita[acak[1]]['link']) ]), CarouselColumn( text=daftarberita[acak[2]]['judul'], actions=[ PostbackTemplateAction(label="Ringkas", data=daftarberita[acak[2]]['link'], text='ringkas'), URITemplateAction(label='Baca berita asli', uri=daftarberita[acak[2]]['link']) ]), CarouselColumn( text=daftarberita[acak[3]]['judul'], actions=[ PostbackTemplateAction(label="Ringkas", data=daftarberita[acak[3]]['link'], text='ringkas'), URITemplateAction(label='Baca berita asli', uri=daftarberita[acak[3]]['link']) ]) ]) template_message = TemplateSendMessage(alt_text='Daftar Berita Bisnis', template=carousel_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'otomotif': databerita = listBerita("http://otomotif.kompas.com/news") daftarberita = databerita.daftarBerita() carousel_template = CarouselTemplate(columns=[ CarouselColumn( text=daftarberita[acak[0]]['judul'], actions=[ PostbackTemplateAction(label="Ringkas", data=daftarberita[acak[0]]['link'], text='ringkas'), URITemplateAction(label='Baca berita asli', uri=daftarberita[acak[0]]['link']) ]), CarouselColumn( text=daftarberita[acak[1]]['judul'], actions=[ PostbackTemplateAction(label="Ringkas", data=daftarberita[acak[1]]['link'], text='ringkas'), URITemplateAction(label='Baca berita asli', uri=daftarberita[acak[1]]['link']) ]), CarouselColumn( text=daftarberita[acak[2]]['judul'], actions=[ PostbackTemplateAction(label="Ringkas", data=daftarberita[acak[2]]['link'], text='ringkas'), URITemplateAction(label='Baca berita asli', uri=daftarberita[acak[2]]['link']) ]), CarouselColumn( text=daftarberita[acak[3]]['judul'], actions=[ PostbackTemplateAction(label="Ringkas", data=daftarberita[acak[3]]['link'], text='ringkas'), URITemplateAction(label='Baca berita asli', uri=daftarberita[acak[3]]['link']) ]) ]) template_message = TemplateSendMessage( alt_text='Daftar Berita Otomotif', template=carousel_template) line_bot_api.reply_message(event.reply_token, template_message) elif "kompas.com/read" in text: linkBerita = Berita(text) rangkuman = linkBerita.rangkumanBerita() teks = ' '.join(rangkuman) if (len(teks) > 2): line_bot_api.reply_message(event.reply_token, TextSendMessage(text=teks)) else: line_bot_api.reply_message( event.reply_token, TextSendMessage( text="maaf, link yang anda kirim tidak valid ")) elif text == 'Bantu' or text == 'bantu': line_bot_api.reply_message( event.reply_token, TextSendMessage( text= '\'Kategori\' >> untuk list Kategori \n\'Bantu\' >> list command yang ada \n\'bye astro\' >> mengusirku dari group \n\'Ping\' >> ngecek aku masih hidup ato nggak :P' )) elif text == 'ringkas': line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Meringkas...')) elif text == 'Ping' or text == 'ping': buttons_template = ButtonsTemplate( text='Ping aku', actions=[PostbackTemplateAction(label='ping', data='ping')]) template_message = TemplateSendMessage(alt_text='ping', template=buttons_template) line_bot_api.reply_message(event.reply_token, template_message) else: profile = line_bot_api.get_profile(event.source.user_id) line_bot_api.reply_message( event.reply_token, TextSendMessage(text="Hi " + profile.display_name + "\n" + event.message.text + ":)")) '''