def sendAdultMenu(event): #成人選單 try: message = TextSendMessage( text='未滿18歲請勿食用!', quick_reply=QuickReply( items=[ QuickReplyButton( action=MessageAction(label="我已滿18歲", text="@我已滿18歲") ), QuickReplyButton( action=MessageAction(label="我未滿18歲", text="@我未滿18歲") ), ] ) ) line_bot_api.reply_message(event.reply_token,message) except: line_bot_api.reply_message(event.reply_token,TextSendMessage(text='發生錯誤!\n聯絡我感恩!'))
def RegisRichmenu(event): userid = event.source.user_id disname = line_bot_api.get_profile(user_id=userid).display_name line_bot_api.link_rich_menu_to_user( userid, 'richmenu-073dc85eff8bb8351e8d53769c025029') button_1 = QuickReplyButton( action=MessageAction(lable='สวัสดี', text='สวัสดี')) answer_button = QuickReply(items=[button_1])
def scense3(subject, present_cnt, next_tag): # 場景名: first_question reply = [] reply_word = f"好的,我們一起來為 {subject} 挑禮物吧" messages0 = TextSendMessage(text=reply_word) reply.append(messages0) reply_word = f"候選禮物數:{present_cnt}" messages1 = TextSendMessage(text=reply_word) reply.append(messages1) reply_items = [] reply_word = f"您覺得 {subject} 對 {next_tag} 有興趣嗎?\n有/無(換一題)" reply_items.append(QuickReplyButton(action=MessageAction(label="有", text="有"))) reply_items.append(QuickReplyButton(action=MessageAction(label="無,換一題", text="無"))) messages2 = TextSendMessage(reply_word, quick_reply=QuickReply(items=reply_items)) reply.append(messages2) return reply
def phase_intermediate(event): color_dict = { 'red': '紅', 'orange': '橙', 'yellow': '黃', 'green': '綠', 'blue': '藍', 'purple': '紫' } reply_dict = { 'mode': '[2/4] 今晚,繼續來點雙色打光!\n請選擇色彩變化梯度:', 'gradient_factor': '[3/4] 今晚,還想來點雙色打光!\n請選擇第一道色彩:', 'first_tone': '[4/4] 今晚,最後來點雙色打光!\n請選擇第二道色彩:' } quick_button_dict = { 'mode': [ QuickReplyButton(action=PostbackAction( label=i, display_text=f'變化梯度:{i}', data=f'gradient_factor={i}')) for i in (5, 10, 50, 100) ], 'gradient_factor': [ QuickReplyButton(action=PostbackAction( label=j, display_text=f'第一道色彩:{j}', data=f'first_tone={i}')) for i, j in color_dict.items() ], 'first_tone': [ QuickReplyButton(action=PostbackAction( label=j, display_text=f'第二道色彩:{j}', data=f'second_tone={i}')) for i, j in color_dict.items() ] } user_id = event.source.user_id postback_data = event.postback.data current_phase = postback_data.split('=')[0] CallDatabase.update_record(user_id, current_phase, postback_data.split('=')[1]) line_bot_api.reply_message( event.reply_token, TextSendMessage( text=reply_dict[current_phase], quick_reply=QuickReply(items=quick_button_dict[current_phase])))
def insert(): thanks = [ '嬉しいわ。', 'お金はまだあるわよね?', '明日もがんばりなさいよ。', '今日はもうおしまいかしら?', 'まだ物足りないわね。', ] value = request.form['value']#大括弧なのに注意。 insert_column(value) #DBにアクセスして最新の貯金1件を取得 sql = "SELECT id FROM users;" with conn.cursor() as cur: cur.execute(sql) userID = cur.fetchall() IDs = [] for user in userID: IDs.append(user[0]) for id in IDs: line_bot_api.push_message( id,[ TextSendMessage( text = f'{value}円貯金してくれてありがとうね、{random.choice(thanks)}', quick_reply = QuickReply( items = [ QuickReplyButton( action = PostbackAction(label = "1週間分の貯金額",data = "1週間") ), QuickReplyButton( action = PostbackAction(label = "1ヶ月分の貯金額",data = "1ヶ月") ), QuickReplyButton( action = PostbackAction(label = "1年分の貯金額",data = "1年") ) ] ) ) ] ) return "Insert done." #Noneを返すとstatus code が500になる。
def postbackevent(event): answer = db.session.query(Answer).all() print(event.postback.data) print(answer[-1].answer) if event.postback.data == "retry": instruments = db.session.query(Instruments).filter(Instruments.userid == event.source.user_id).first() instruments.status = "registing" db.session.add(instruments) db.session.commit() line_bot_api.reply_message( event.reply_token, TextSendMessage(text="もう一度自己紹介を入力してね") ) elif event.postback.data == "ok": instruments = db.session.query(Instruments).filter(Instruments.userid == event.source.user_id).first() instruments.status = "registed" db.session.add(instruments) db.session.commit() line_bot_api.reply_message( event.reply_token, TextSendMessage(text="登録しました") ) elif event.postback.data == answer[-1].answer: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="正解!!!") ) elif event.postback.data != answer[-1].answer: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="違うよ!!") ) instruments = db.session.query(Instruments).filter(Instruments.status == "registed").all() quizmember = db.session.query(Instruments.userid).filter(Instruments.status == "registed").all() quizmembericon = db.session.query(Instruments.icon).filter(Instruments.status == "registed").all() count = len(instruments) memberinstruments = db.session.query(Instruments).filter(Instruments.userid == quizmember[num].userid).first() contents = [] for i in range(count): profile = line_bot_api.get_profile(quizmember[i].userid) quizmembername = profile.display_name item = QuickReplyButton(action=PostbackAction(imageUrl = quizmembericon[i].icon, label = quizmembername, display_text = quizmembername + "さん", data = quizmember[i].userid)) contents.append(item) message = TextSendMessage(text = memberinstruments.message, quick_reply=QuickReply(items = contents)) line_bot_api.reply_message( event.reply_token, message )
def handle_follow_event(event=None, line_bot_api=None): user_id = event.source.user_id dur() _text = "数あるダイエットサービスの中から選んでもらえてくれしいです。" line_bot_api.push_message(user_id, TextSendMessage(text=_text)) dur() _text = "あなたの最適なパートナーになれるように頑張ります♪これからよろしくお願いします♪" line_bot_api.push_message(user_id, TextSendMessage(text=_text)) dur() _text = "まずは、あなたのことを知りたいです!性別を教えてください!" Session_interface.set_waiting_mode(user_id=user_id, mode=MODE.AFTER_SEX) line_bot_api.push_message(user_id, TextSendMessage(text=_text, quick_reply=QuickReply( items=[ QuickReplyButton(action=PostbackAction(label="男性", data=MODE.AFTER_SEX.hash+"&男性", text="男性")), QuickReplyButton(action=PostbackAction(label="女性", data=MODE.AFTER_SEX.hash+"&女性", text="女性")), QuickReplyButton(action=PostbackAction(label="その他", data=MODE.AFTER_SEX.hash+"&その他", text="その他")) ] )))
def response_message(): language_list = ["Ruby", "Python", "PHP", "Java", "C"] items = [ QuickReplyButton( action=MessageAction(label=f"{language}", text=f"{language}が好き")) for language in language_list ] return items
def handle_join(event): profile=line_bot_api.get_profile(event.source.user_id) opening_text = f"👋👋👋👋 {profile.display_name} 您好\n\ 為了您有更好的系統體驗, 是否傳送您目前的居住位置呢 \ " line_bot_api.reply_message( event.reply_token, TextSendMessage(text=opening_text, quick_reply=QuickReply(items=[ QuickReplyButton(action=MessageAction(label="否, 下次再傳送", text="否, 下次再傳送")), QuickReplyButton(action=LocationAction(label="是的, 我很願意有更好的體驗")) ], ) ) )
def sendPizza(event): message = TextSendMessage( text='請選擇想查詢之商業司相關網站', quick_reply=QuickReply(items=[ QuickReplyButton(action=MessageAction( label="商工行政服務相關網站入口網", text="https://gcis.nat.gov.tw/mainNew/index.jsp")), QuickReplyButton(action=MessageAction( label="商工登記公示資料查詢服務", text= "https://findbiz.nat.gov.tw/fts/query/QueryBar/queryInit.do")), QuickReplyButton(action=MessageAction( label="縣市別與近十年度公司設立登記案件統計", text= "https://serv.gcis.nat.gov.tw/StatisticQry/cmpy/StaticFunction4.jsp" )), ])) line_bot_api.reply_message(event.reply_token, message)
def number_buttons(maxNumber, grade_classroom): quick_buttons = [] number = 1 while number <= maxNumber: quick_buttons.append(QuickReplyButton( action=PostbackAction( label=number, data=f"{grade_classroom}_" + str(number), display_text=number) )) number += 1 return quick_buttons
def sendTrainQuickReply(text,event): items=[] for key in list(TRAIN_STATION.keys())[:13]: items.append(QuickReplyButton(action=MessageAction(key,text+":"+key))) message=TextSendMessage(text=text,quick_reply=QuickReply(items)) line_bot_api.reply_message(event.reply_token,message)
def sendInstrucMsg(): msgObjs = [] msgObjs.append( TextSendMessage(text=config.get('instrucMsg', 'auth_complete'))) greetImgUrl = getPicUrl('greeting_pic_url') msgObjs.append( ImageSendMessage(type="image", original_content_url=greetImgUrl, preview_image_url=greetImgUrl)) msgObjs.append( TextSendMessage( text=config.get('instrucMsg', 'instruc'), quick_reply=QuickReply(items=[ QuickReplyButton( action=MessageAction(label="跳過教學", text="跳過教學")), QuickReplyButton( action=MessageAction(label="好的!顯示使用說明", text="好的!顯示使用說明")) ]))) return msgObjs
def handle_follow(event): # get profile profile = line_bot_api.get_profile(event.source.user_id) # check if user exists in Muda Beo try: line_bot_api.get_group_member_profile( lfm_muda_beo_id, event.source.user_id) user_type = 1 except LineBotApiError as err: print(err.error.message) user_type = 0 # add said profile to database add_follower(profile.user_id, profile.display_name, user_type) if user_type == 1: welcome_reply = 'Halo, {}! Kenalkan aku Samantha, bot untuk membantu kru LFM. Kalau penasaran aku bisa membantu apa saja, kirim aja \n`?Help`'.format( profile.display_name) onboarding_reply = 'Oh iya, coba dulu yuk kirim `?Agenda` atau `?NowShowing`, atau pencet aja menu yang udah disediain!' privacy_notice = "Omong-omong, aku akan merekam kapan dan fitur apa yang kalian gunakan ya. Kalau kalian tidak mau, karena belum ada sistem untuk opt-out, berkabar saja supaya rekamannya dihapus ya." quick_reply_onboard = QuickReply(items=[ QuickReplyButton(action=MessageAction( label="Help 🙋", text="?Help")), QuickReplyButton(action=MessageAction( label="Agenda 📅", text="?Agenda")), QuickReplyButton(action=MessageAction( label="Now Showing 🍿", text="?NowShowing")) ]) all_reply = [TextSendMessage(text=welcome_reply), StickerSendMessage(package_id='11537', sticker_id='52002734'), TextSendMessage(text=onboarding_reply, ), TextSendMessage(text=privacy_notice, quick_reply=quick_reply_onboard)] elif user_type == 0: welcome_reply = 'Halo, {}! Kenalkan aku Samantha, bot untuk membantu kru LFM. Tampaknya kamu tidak ada di Muda Beo. Maaf, aku tidak bisa membantumu.'.format( profile.display_name) all_reply = [TextSendMessage(text=welcome_reply)] # send a welcoming message and onboarding line_bot_api.reply_message(event.reply_token, all_reply)
def sendQuickreply(event): #快速選單 try: message = TextSendMessage( text='請選擇您現在想吃的種類', quick_reply=QuickReply( items=[ QuickReplyButton( action=MessageAction(label="飯類", text="飯類") ), QuickReplyButton( action=MessageAction(label="麵類", text="麵類") ), QuickReplyButton( action=MessageAction(label="沙拉", text="沙拉") ), QuickReplyButton( action=MessageAction(label="麵包", text="麵包") ), QuickReplyButton( action=MessageAction(label="飲料", text="飲料") ), QuickReplyButton( action=MessageAction(label="關東煮", text="關東煮") ), QuickReplyButton( action=MessageAction(label="甜點", text="甜點") ), QuickReplyButton( action=MessageAction(label="湯類", text="湯類") ), QuickReplyButton( action=MessageAction(label="水果", text="水果") ), QuickReplyButton( action=MessageAction(label="其他", text="其他") ), ] ) ) line_bot_api.reply_message(event.reply_token,TextSendMessage(text='發生錯誤!'), message) except: line_bot_api.reply_message(event.reply_token,TextSendMessage(text='發生錯誤!'))
def get_result(self, text): if self.first is None: if text == "ประวัติ": self.first = "ประวัติ" return self.history_test(text) elif text == "รายรับรายจ่าย": self.first = "รายรับรายจ่าย" return self.get_response_1(text) elif text == "คงเหลือ": return self.get_remaining() elif text == "ลบ": self.delete_all() return TextSendMessage(text="Deleted") elif text == "Test": self.first = "Test" return self.delete_movement(text) else: THIRD_PROMPT = TextSendMessage( text="คุณต้องการทำรายการอะไร", quick_reply=QuickReply(items=[ QuickReplyButton(action=MessageAction( label="ประวัติรายรับรายจ่าย", text="ประวัติ")), QuickReplyButton(action=MessageAction( label="รายรับรายจ่าย", text="รายรับรายจ่าย")), QuickReplyButton(action=MessageAction( label="เงินคงเหลือ", text="คงเหลือ")), QuickReplyButton(action=MessageAction( label="ลบข้อมูลรายรับรายจ่าย", text="ลบ")), QuickReplyButton(action=MessageAction( label="เลือกลบรายรับรายจ่าย", text="Test")) ])) return THIRD_PROMPT else: if self.first == "ประวัติ": return self.history_test(text) elif self.first == "รายรับรายจ่าย": return self.get_response_1(text) elif text == "คงเหลือ": return self.get_remaining() elif self.first == "Test": return self.delete_movement(text)
def AskEnd(lineBotApi, userId, mode='default'): currentTime = datetime.now() if mode == 'default': lineBotApi.push_message( userId, TextSendMessage( text="該出發了吧?", quick_reply=QuickReply(items=[ QuickReplyButton( action={ "type": "datetimepicker", "label": "選擇出發時間", "data": "action=pick_time", "mode": "time", "initial": currentTime.strftime("%H:%M"), "max": "23:59", "min": "00:00" }), QuickReplyButton( action=MessageAction(label="我還要", text="更多景點")), QuickReplyButton( action=MessageAction(label="看一下選了什麼", text="查看目前清單")), ]))) elif mode == 'preview': lineBotApi.push_message( userId, TextSendMessage( text="該出發了吧?", quick_reply=QuickReply(items=[ QuickReplyButton( action={ "type": "datetimepicker", "label": "選擇出發時間", "data": "action=pick_time", "mode": "time", "initial": currentTime.strftime("%H:%M"), "max": "23:59", "min": "00:00" }), QuickReplyButton( action=MessageAction(label="一鍵清除", text="清除目前清單")), ])))
def scense5(subject, present_cnt, next_tag, tags): # 場景名: question_loop_True reply = [] str_tags = tags[0] if len(tags)>1: for i in range(1,len(tags)): str_tags = str_tags + "、"+tags[i] reply_word = f"他有興趣的元素:{str_tags}\n候選禮物數:{present_cnt}" messages0 = TextSendMessage(text=reply_word) reply.append(messages0) # quick btn reply_items = [] reply_word = f"您覺得 {subject} 對 {next_tag} 有興趣嗎?有/無(換一題)" reply_items.append(QuickReplyButton(action=MessageAction(label="有", text="有"))) reply_items.append(QuickReplyButton(action=MessageAction(label="無,換一題", text="無"))) messages2 = TextSendMessage(reply_word, quick_reply=QuickReply(items=reply_items)) reply.append(messages2) return reply
def create_quick_replies(reply_text, replies): items = [] for quick_reply in replies: quick_label = quick_reply[0] quick_text = quick_reply[1] button = QuickReplyButton( action=MessageAction(label=quick_label, text=quick_text)) items.append(button) message = TextSendMessage(text=reply_text, quick_reply=QuickReply(items=items)) return message
def nanikashitai(): texts = ['今日はなんの日だっけ?', '近々なにかある?'] names = ['adalo', 'timetree'] items = [ QuickReplyButton(action=PostbackAction( label=f"{text}", display_text=f"{text}", data=f"{name}")) for text, name in zip(texts, names) ] return items
def generateFAQCategories(confirm=False): if confirm: return [ QuickReplyButton(action=PostbackAction( label='特になし', text='特になし', data='faq_done=1')) ] + [ QuickReplyButton( action=PostbackAction(label=FAQs[category_id]['category'], text=FAQs[category_id]['category'], data='category_id=' + str(category_id))) for category_id in FAQs ] else: return [ QuickReplyButton( action=PostbackAction(label=FAQs[category_id]['category'], text=FAQs[category_id]['category'], data='category_id=' + str(category_id))) for category_id in FAQs ]
def handle_other_message(event): line_bot_api.reply_message( event.reply_token, TextSendMessage( text = 'ごめんなさいね。\nこのアカウントはユーザー様とテキストメッセージを使ってやり取りを行うアカウントなのよ。\n対応しているメッセージについては、「ヘルプ」とメッセージを送って参照してちょうだいね。', quick_reply = QuickReply( items = [ QuickReplyButton( action = PostbackAction(label = "1週間分の貯金額",data = "1週間") ), QuickReplyButton( action = PostbackAction(label = "1ヶ月分の貯金額",data = "1ヶ月") ), QuickReplyButton( action = PostbackAction(label = "1年分の貯金額",data = "1年") ) ] ) ) )
def __command_list(self): command_list = [ QuickReplyButton(action=MessageAction(label=command, text=command)) for command in self.command_dict.keys() ] self.line_bot_api.reply_message( self.event.reply_token, TextSendMessage( text="機器人指令集", quick_reply=QuickReply(items=command_list), ), )
def quick_message(event): menu_list = ["BBS", "MOVIE"] menu_items = [ QuickReplyButton(action=MessageAction(label=f"{menu}", text=f"{menu}")) for menu in menu_list ] messages1 = TextSendMessage(text="どれを参照しますか?", quick_reply=QuickReply(items=menu_items)) line_bot_api.reply_message(event.reply_token, messages=messages1)
def message_type(event): # ตอบ user ที่ user พิมพ์เข้ามาเป็น Text # print(event) # texts = event['message']['type'] texts = event.message.text print("Your Message :",texts) # userId = event_handler_add()[0] userId = event.message.id print("Your UserId :",userId) replyToken = event.reply_token print("Your replyToken :",replyToken) # TextSendMessage(text= 'สวัสดี 😀') if texts == "ไง": line_bot_api.reply_message(event.reply_token, TextSendMessage(text='กรุณาเลือกหัวข้อ', quick_reply=QuickReply(items=[ QuickReplyButton(image_url="https://media2.giphy.com/media/R3IxJW14a3QNa/giphy.gif?cid=ecf05e47ptuw3dl3x03u0i97mqhit3ryu9m5zipi90sokouz&rid=giphy.gif",action=MessageAction(label="สวัสดี", text="ยินดีต้อนรับ")), QuickReplyButton(image_url="https://static.wixstatic.com/media/afc648_7e70f2fcc96443efaa236f0fe18ac3d0~mv2.gif",action=CameraAction(label="ถ่ายภาพ")) ]))) elif texts: word = chatBot(texts) line_bot_api.reply_message(replyToken, TextSendMessage(text=word))
def sendQuickReply_FB(event, q_num): items = [ QuickReplyButton(action=PostbackAction(label=option[0], text=option[0], data='qid=' + str(q_num) + '&ans=' + str(option[1]))) for option in fb_options[q_num] ] line_bot_api.reply_message( event.reply_token, TextSendMessage(text=fb_questions[q_num], quick_reply=QuickReply(items=items)))
def QR_ExtraFood(event): try: print("### QuickReplyButton.QR_ExtraFood_Start\n") message = TextSendMessage( text='請選擇「模糊搜尋」或「精準搜尋」:', quick_reply=QuickReply( items=[ QuickReplyButton( action=PostbackAction(label="模糊搜尋", data="fuzzySearch") ), QuickReplyButton( action=PostbackAction(label="精準搜尋", data="preciseSearch") ) ] ) ) print("### QuickReplyButton.QR_ExtraFood.message: ", message) print("### QuickReplyButton.QR_ExtraFood_End\n") line_bot_api.reply_message(event.reply_token,message) except: line_bot_api.reply_message(event.reply_token,TextSendMessage(text='發生錯誤!'))
def handle_image_message(event): account = LineAccount.query.filter_by( account_id=event.source.user_id).first() if account: if account.img_soon and account.tweet_phase == "img": if util.check_timeout(account.last_tweet_req, 300): account.tweet_phase = "confirm " + event.message.id line_bot_api.reply_message( event.reply_token, TextSendMessage( f"❗❗CONFIRMATION❗❗\n\n{account.next_tweet_msg}\n\n" f"/send to tweet {get_emoji_str('0x1000A5')}\n" f"/canceltweet to cancel ❌", quick_reply=QuickReply(items=[ QuickReplyButton( action=MessageAction("SEND", "/send")), QuickReplyButton( action=MessageAction("CANCEL", "/canceltweet")) ]))) account.last_tweet_req = util.datetime_now_string() db.session.commit()
def handle_message(event): ### RECEIVE MESSAGE text = str(event.message.text).strip() ### GET MODE & REPLY FROM TEXT mode, reply = get_reply(text) ### GET USER INFO & INSERT INTO SQL LOG profile = line_bot_api.get_profile(event.source.user_id) if profile.display_name != '': date_now = get_time_now() con, cursor = connect_sql('nozomibot') cursor.execute( f"INSERT INTO log_line (date, mode, text, username, userid) VALUES (%s, %s, %s, %s, %s);", (date_now, mode, text, profile.display_name, profile.user_id)) con.commit() con.close() ### SEND REPLY if reply != None: line_bot_api.reply_message(event.reply_token, TextSendMessage(text=reply)) elif mode == 'JOSHI_START': items = [ QuickReplyButton(action=PostbackAction( label="Kakujoshi 5 ข้อ", data="action=joshi&type=格助詞&num=5")), QuickReplyButton(action=PostbackAction( label="10 ข้อ", data="action=joshi&type=格助詞&num=10")), QuickReplyButton(action=PostbackAction( label="All joshi 5 ข้อ", data="action=joshi&type=all&num=5")), QuickReplyButton(action=PostbackAction( label="10 ข้อ", data="action=joshi&type=all&num=10")) ] message = TextSendMessage(text="เลือกจำนวนข้อ", quick_reply=QuickReply(items=items)) line_bot_api.reply_message(event.reply_token, message) else: reply = 'ขอโทษครับ บอทนี้เป็นบอทอัตโนมัติ ไม่สามารถคุยกันได้' line_bot_api.reply_message(event.reply_token, TextSendMessage(text=reply))
def get_quick_reply(self, morning_dt, noon_dt, evening_dt): now = datetime.utcnow() return QuickReply(items=[ QuickReplyButton(action=PostbackAction( label="1時間後", display_text="1時間後", data=f"{(now + timedelta(hours=1)).strftime('%Y-%m-%dT%H:%M')}" )), QuickReplyButton(action=PostbackAction( label="🐓", display_text="🐓朝", data= f"{self.to_remind_at(morning_dt, now).strftime('%Y-%m-%dT%H:%M')}" )), QuickReplyButton(action=PostbackAction( label="☀️", display_text="☀️昼", data= f"{self.to_remind_at(noon_dt, now).strftime('%Y-%m-%dT%H:%M')}" )), QuickReplyButton(action=PostbackAction( label="🌙", display_text="🌙夜", data= f"{self.to_remind_at(evening_dt, now).strftime('%Y-%m-%dT%H:%M')}" )), QuickReplyButton(action=DatetimePickerAction( label="日時を選択", mode="datetime", data="picker")), QuickReplyButton(action=PostbackAction( label="キャンセル", display_text="キャンセル", data="cancel")), ])