async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='(주)나눔로또에서 제공하는 "로또당첨번호 서비스"에요.' # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element(image_url=BRICK_DEFAULT_IMAGE, title='로또당첨번호 서비스', subtitle='(주)나눔로또에서 제공하는 "로또당첨번호 서비스"에요.') ]))) ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() num = input_data['store'][0]['value'] if self.fb.log_id is None: self.fb.log_id = 'FBSendMessage|%d' % int(time.time() * 1000) res = requests.get( url= 'http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=%s' % num) save_a_log_to_server({ 'log_id': self.fb.log_id, 'user_id': self.fb.user_id, 'os': '', 'application': 'facebook', 'api_code': 'lotto', 'api_provider_code': 'chatbrick', 'origin': 'webhook_server', 'end': int(time.time() * 1000), 'remark': '외부 로또 당첨번호 조회 API 요청을 보냄' }) parsed_result = res.json() await self.brick_db.delete() await self.fb.send_message(message=Message( text= '두구두구두구 ~\n조회하신 {drwNo}회 당첨번호는 {drwtNo1},{drwtNo2},{drwtNo3},{drwtNo4},{drwtNo5},{drwtNo6} 에 보너스번호는 {bnusNo} 이에요.\n부디 1등이길!!' .format(**parsed_result), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem(title='다른회차검색', payload='brick|lotto|get_started') ]))) return None
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='geniecontents에서 제공하는 "띠별 오늘의 운세 서비스"에요.' # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element( image_url=BRICK_DEFAULT_IMAGE, title='띠별 오늘의 운세 서비스', subtitle='geniecontents에서 제공하는 "띠별 오늘의 운세 서비스"에요.') ]))) ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() num = input_data['store'][0]['value'] now = datetime.datetime.today() res = requests.get( url= 'https://www.geniecontents.com/fortune/internal/v1/daily?birthYear=%s&targetYear=%s&targetMonth=%s&targetDay=%s' % (num, now.year, now.month, now.day)) try: parsed_result = res.json() parsed_result.update(parsed_result['list'][0]) send_message = [ Message(text='조회된 결과에요'), Message(attachment=ImageAttachment( url='https:%s' % parsed_result['animalImgUrl'])), Message( text= '출생년도 : {year}\n운세 : {summary}\n자세한 내용 : {description}' .format(**parsed_result), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 운세검색', payload='brick|luck|get_started') ])) ] except: send_message = [Message(text='조회된 결과가 없습니다.')] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
def make_the_bricks_for_facebook(self): designer_brick = [] elements = [] for brick in self.data['brick']: self.brick_data[brick['id']] = brick['data'] designer_brick.append( FacebookBrick(brick_type='postback', value=brick['id'], actions=[ FacebookBrickAction(brick_id=brick['id'], data=brick['data']) ])) if 'keywords' in brick: for keyword in brick['keywords']: if len(keyword) == 0 or len(keyword) > 8: raise RuntimeError('키워드를 최대 8자 이내로 입력해주세요.') designer_brick.append( FacebookBrick(brick_type='text', value=keyword, actions=[ FacebookBrickAction( brick_id=brick['id'], data=brick['data']) ])) for brick_rec in self.bricks: if brick_rec['id'] == brick['id']: elements.append( Element(title=brick_rec['name'], subtitle=brick_rec['api']['desc'], image_url=brick_rec['img'], buttons=[ PostBackButton(title='선택', payload=brick['id']) ])) break designer_brick.append( FacebookBrick( brick_type='postback', value='get_started', actions=[ FacebookGeneralAction(message=Message( text=self.data['custom_settings']['get_started'])), FacebookGeneralAction(message=Message( attachment=TemplateAttachment(payload=GenericTemplate( elements=elements)))) ])) return designer_brick
async def facebook(self, command): if command == 'get_started': send_message = [ Message( attachment=ImageAttachment( url=BRICK_DEFAULT_IMAGE ) ), Message( text='안녕하세요. 장소 테스트입니다.' ), Message( text='현재위치를 보내주세요.', quick_replies=QuickReply( quick_reply_items=[ QuickReplyLocationItem() ] ) ) ] await self.fb.send_messages(send_message) return None
async def facebook(self, command): if command == 'get_started': await self.brick_db.save() elif command == 'cancel': await self.brick_db.delete() await self.fb.send_message(message=Message(text='메일 보내기를 취소했어요.', ) ) elif command == 'final': input_data = await self.brick_db.get() await self.fb.send_message(message=Message(text='메일전송 요청이 완료되었습니다') ) msg = MIMEText(input_data['store'][1]['value']) msg['Subject'] = '%s로부터 이메일입니다.' % input_data['store'][0]['value'] msg['To'] = input_data['data']['to'] # if self.fb.log_id is None: # self.fb.log_id = 'FBSendMessage|%d' % int(time.time() * 1000) self.smtp.ehlo() self.smtp.starttls() self.smtp.login(self.sender_email, self.sender_password) self.smtp.sendmail(self.sender_email, input_data['data']['to'], msg.as_string()) # save_a_log_to_server({ # 'log_id': self.fb.log_id, # 'user_id': self.fb.user_id, # 'os': '', # 'application': 'facebook', # 'api_code': 'mail', # 'api_provider_code': 'chatbrick', # 'origin': 'webhook_server', # 'end': int(time.time() * 1000), # 'remark': 'SMTP 통신으로 이메일 전송함' # }) await self.brick_db.delete() return None
def web_hook(request): print(request) if request.method == 'GET': if request.GET.get('hub.verify_token') == verify_token: return HttpResponse(request.GET.get('hub.challenge')) elif request.method == 'POST': print(request.body) data = json.loads(request.body.decode('UTF-8')) for entry in data['entry']: for message in entry['messaging']: receiver = message['sender']['id'] if 'message' in message: if 'quick_reply' in message['message']: payload = message['message']['quick_reply']['payload'] if payload == '1': send_message = Message(text='1. 평일 아침 8시 이전 주문건까지 대부분 당일 배송됩니다. \n\n2. 8시 이후 주문건은 다음날 배송됩니다. \n금요일 8시 이후 주문건은 다음주 월요일에 배송됩니다.\n\n3. 브라운백 커피는 CJ 대한통운을 통해 커피를 보내드립니다.\n쇼핑몰에서 구매하신 경우, 택배 출고시 문자메시지로 송장 번호를 안내해드립니다. \n문자로 받으신 송장번호를 복사하셔서 아래 CJ 대한통운 배송조회 사이트에서 조회해주시면 됩니다.\n\n4. 콜드브루와 원두를 같이 주문하시면 각각 다른 곳에서 배송되어, 택배를 두개로 나눠 받으십니다.\n\n더 궁금하신 점은 언제든 문의주세요. 감사합니다^^') elif payload == '2': send_message = Message(text='1. 샘플 신청 : 아래 링크를 눌러 샘플 발송에 필요한 정보를 입력해주시면 됩니다.\n맛 보시고 궁금하신 사항이나 추가 요청 사항이 있으시면 언제든 문의주세요!\n\n2. 샘플 배송 : 신청해주신 후 2~3일 이내 배송이 시작됩니다. \n신청이 들어온 순서대로 순차적으로 배송해드리오니 조금만 기다려주세요^^ \n\n더 궁금하신 점은 언제든 문의주세요. 감사합니다^^') else: text = message['message']['text'] if text =='선택': quick_replies = [QuickReplyTextItem(title='제품 배송 일정', payload='1', image_url=None), QuickReplyTextItem(title='샘플 신청 방법과 샘플 배송', payload='2', image_url=None)] send_message = Message(text='원하시는 버튼을 선택해주세요', quick_replies=QuickReply(quick_reply_items=quick_replies)) else : send_message = Message(text='안녕하세요. 브라운백 커피입니다.\n궁금하신 점은 본 공식 카카오톡 아이디 / 공식 전화 1644-1530 로 연락 주시면 언제든지 친절히 답변드리겠습니다! \n\n"선택"을 입력해주세요.') req.send_message(RequestDataFormat(recipient=Recipient(recipient_id=receiver), message=send_message)) return JsonResponse(data) return HttpResponse('Failed to request', status=404)
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='한국전력공사에서 제공하는 "전기차충전소 조회 서비스"에요.' # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element(image_url=BRICK_DEFAULT_IMAGE, title='전기차충전소 조회 서비스', subtitle='한국전력공사에서 제공하는 "전기차충전소 조회 서비스"에요.') ]))) ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() place = input_data['store'][0]['value'] res = requests.get( url= 'http://openapi.kepco.co.kr/service/evInfoService/getEvSearchList?serviceKey=%s&numOfRows=100&pageSize=100&pageNo=1&startPage=1&addr=%s' % (input_data['data']['api_key'], urllib.parse.quote_plus(place))) items = get_items_from_xml(res) if type(items) is dict: if items.get('code', '00') == '99' or items.get('code', '00') == '30': send_message = [ Message( text= 'chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [Message(text=UNKNOWN_ERROR_MSG)] else: if len(items) == 0: send_message = [ Message(text='조회된 결과가 없습니다.', quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 지역검색', payload='brick|electric|get_started') ])) ] else: sending_message = '' for item in items: sending_message += '충전소명 : {csNm}\n충전소ID : {cpId}\n충전타입 : {cpNm}\n상태 : {cpStat}\n주소 : {addr}\n\n'.format( **item) send_message = [ Message(text=sending_message, quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 충전소 검색', payload='brick|electric|get_started') ])) ] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='인천국제공항공사에서 제공하는 "출국장 대기인원 조회 서비스"에요.' # ), # Message( # attachment=TemplateAttachment( # payload=GenericTemplate( # elements=[ # Element( # image_url='https://www.chatbrick.io/api/static/brick/img_brick_13_002.png', # title='제 1여객터미널', # subtitle='제 1여객터미널의 게이트별 대기인원을 알려드려요.', # buttons=[ # PostBackButton( # title='1여객터미널 조회', # payload='brick|icn|1' # ) # ] # ), # Element( # image_url='https://www.chatbrick.io/api/static/brick/img_brick_13_002.png', # title='제 2여객터미널', # subtitle='제 2여객터미널의 게이트별 대기인원을 알려드려요.', # buttons=[ # PostBackButton( # title='2여객터미널 조회', # payload='brick|icn|2' # ) # ] # ) # ] # ) # ) # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element( image_url=BRICK_DEFAULT_IMAGE, title='출국장 대기인원 조회 서비스', subtitle='인천국제공항공사에서 제공하는 "출국장 대기인원 조회 서비스"에요.') ]))), Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element( image_url= 'https://www.chatbrick.io/api/static/brick/img_brick_13_002.png', title='제 1여객터미널', subtitle='제 1여객터미널의 게이트별 대기인원을 알려드려요.', buttons=[ PostBackButton(title='1여객터미널 조회', payload='brick|icn|1') ]), Element( image_url= 'https://www.chatbrick.io/api/static/brick/img_brick_13_002.png', title='제 2여객터미널', subtitle='제 2여객터미널의 게이트별 대기인원을 알려드려요.', buttons=[ PostBackButton(title='2여객터미널 조회', payload='brick|icn|2') ]) ]))) ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == '1' or command == '2': input_data = await self.brick_db.get() res = requests.get( url= 'http://openapi.airport.kr/openapi/service/StatusOfDepartures/getDeparturesCongestion?serviceKey=%s&terno=%s' % (input_data['data']['api_key'], command), headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' }) items = get_items_from_xml(res) if type(items) is dict: if items.get('code', '00') == '99' or items.get('code', '00') == '30': send_message = [ Message( text= 'chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [Message(text=UNKNOWN_ERROR_MSG)] else: if command == '1': the_other = '2' else: the_other = '1' raw_data = items[0] sending_message = '제 {terno} 여객터미널\n조회날짜 : {cgtdt}\n조회시간 : {cgthm}'.format( **raw_data) if command == '1': sending_message += '\n2번 출국장: %s명 (%s)' % ( raw_data['gateinfo1'], GATE_INFO[raw_data['gate1']]) sending_message += '\n3번 출국장: %s명 (%s)' % ( raw_data['gateinfo2'], GATE_INFO[raw_data['gate2']]) sending_message += '\n4번 출국장: %s명 (%s)' % ( raw_data['gateinfo3'], GATE_INFO[raw_data['gate3']]) sending_message += '\n5번 출국장: %s명 (%s)' % ( raw_data['gateinfo4'], GATE_INFO[raw_data['gate4']]) elif command == '2': sending_message += '\n1번 출국장: %s명 (%s)' % ( raw_data['gateinfo1'], GATE_INFO[raw_data['gate1']]) sending_message += '\n2번 출국장: %s명 (%s)' % ( raw_data['gateinfo2'], GATE_INFO[raw_data['gate2']]) send_message = [ Message( text=sending_message, quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem(title='새로고침', payload='brick|icn|%s' % command), QuickReplyTextItem(title='제%s여객터미널 조회' % the_other, payload='brick|icn|%s' % the_other) ])) ] await self.fb.send_messages(send_message) return None
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='한국천문연구원에서 제공하는 "쉬는날 조회 서비스"에요.' # ), # Message( # attachment=TemplateAttachment( # payload=GenericTemplate( # elements=[ # Element( # image_url='https://www.chatbrick.io/api/static/brick/img_brick_11_002.png', # title='이번달에 쉬는날', # subtitle='이번달에 공휴일을 알려드려요.', # buttons=[ # PostBackButton( # title='이번달조회', # payload='brick|holiday|this_month' # ) # ] # ), # Element( # image_url='https://www.chatbrick.io/api/static/brick/img_brick_11_002.png', # title='지정한 년/월에 쉬는날', # subtitle='입력하신 년/월의 공휴일을 알려드려요.', # buttons=[ # PostBackButton( # title='조회할 년/월 입력', # payload='brick|holiday|specify_month' # ) # ] # ) # ] # ) # ) # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element(image_url=BRICK_DEFAULT_IMAGE, title='쉬는날 조회 서비스', subtitle='한국천문연구원에서 제공하는 "쉬는날 조회 서비스"에요.') ]))), Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element( image_url= 'https://www.chatbrick.io/api/static/brick/img_brick_11_002.png', title='이번달에 쉬는날', subtitle='이번달에 공휴일을 알려드려요.', buttons=[ PostBackButton( title='이번달조회', payload='brick|holiday|this_month') ]), Element( image_url= 'https://www.chatbrick.io/api/static/brick/img_brick_11_002.png', title='지정한 년/월에 쉬는날', subtitle='입력하신 년/월의 공휴일을 알려드려요.', buttons=[ PostBackButton( title='조회할 년/월 입력', payload='brick|holiday|specify_month') ]) ]))) ] await self.fb.send_messages(send_message) elif command == 'specify_month': await self.brick_db.save() elif command == 'final' or command == 'next_month' or command == 'prev_month' or command == 'this_month': if command == 'this_month': await self.brick_db.save(is_pass=True) input_data = await self.brick_db.get() year = input_data['store'][0]['value'] month = input_data['store'][1]['value'] if year.strip() == 'pass' or month.strip() == 'pass': today = datetime.datetime.today() year = today.year month = today.month if command == 'next_month': plus_month = dateutil.parser.parse( '%s %s 01' % (year, month)) + relativedelta(months=1) year = plus_month.year month = plus_month.month elif command == 'prev_month': plus_month = dateutil.parser.parse( '%s %s 01' % (year, month)) - relativedelta(months=1) year = plus_month.year month = plus_month.month if command == 'next_month' or command == 'prev_month': rslt = await self.brick_db.update({ '$set': { 'store.0.value': str(year), 'store.1.value': str(month) } }) if self.fb.log_id is None: self.fb.log_id = 'FBSendMessage|%d' % int(time.time() * 1000) res = requests.get( url= 'http://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getRestDeInfo?serviceKey=%s&solYear=%s&solMonth=%s' % (input_data['data']['api_key'], year, str(month).rjust(2, '0'))) save_a_log_to_server({ 'log_id': self.fb.log_id, 'user_id': self.fb.user_id, 'os': '', 'application': 'facebook', 'api_code': 'holiday', 'api_provider_code': 'chatbrick', 'origin': 'webhook_server', 'end': int(time.time() * 1000), 'remark': '쉬는날 조회 외부 API 요청을 보냄' }) items = get_items_from_xml(res) if type(items) is dict: if items.get('code', '00') == '99' or items.get('code', '00') == '30': send_message = [ Message( text= 'chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [Message(text=UNKNOWN_ERROR_MSG)] else: if len(items) == 0: if command == 'prev_month' or command == 'this_month': send_message = [ Message(attachment=TemplateAttachment( payload=ButtonTemplate( text='%s-%s\n조회된 결과가 없습니다.' % (year, month), buttons=[ PostBackButton( title='이전달 조회', payload='brick|holiday|prev_month' ), PostBackButton( title='다음달 조회', payload='brick|holiday|next_month') ]))) ] else: send_message = [ Message( text='조회된 결과가 없습니다.', quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 달 조회하기', payload='brick|holiday|get_started') ])) ] else: sending_message = [] for item in items: sending_message.append( '날짜: {locdate}\n공휴일 유무: {isHoliday}\n공휴일 내용: {dateName}' .format(**item)) send_message = [ Message(attachment=TemplateAttachment( payload=ButtonTemplate( text='\n\n'.join(sending_message), buttons=[ PostBackButton( title='이전달 조회', payload='brick|holiday|prev_month'), PostBackButton( title='다음달 조회', payload='brick|holiday|next_month') ]))) ] await self.fb.send_messages(send_message) return None
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='중앙응급의료센터에서 제공하는 "응급실검색 서비스"에요.' # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element(image_url=BRICK_DEFAULT_IMAGE, title='응급실검색 서비스', subtitle='중앙응급의료센터에서 제공하는 "응급실검색 서비스"에요.') ]))) ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() state = input_data['store'][0]['value'] town = input_data['store'][1]['value'] res = requests.get( url= 'http://apis.data.go.kr/B552657/ErmctInfoInqireService/getEgytListInfoInqire?serviceKey=%s&Q0=%s&Q1=%s&ORD=NAME&pageNo=1&startPage=1&numOfRows=3&pageSize=3' % (input_data['data']['api_key'], state, town)) items = get_items_from_xml(res) if type(items) is dict: if items.get('code', '00') == '99' or items.get('code', '00') == '30': send_message = [ Message( text= 'chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [Message(text=UNKNOWN_ERROR_MSG)] else: if len(items) == 0: send_message = [ Message(text='조회된 결과가 없습니다.', quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 지역검색', payload='brick|emergency|get_started') ])) ] else: send_message = [ Message(text='조회된 결과에요'), Message( text= '{dutyName}\n{dutyEmclsName}\n{dutyAddr}\n{dutyTel1}\n{dutyTel3}' .format(**items[0]), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 지역검색', payload='brick|emergency|get_started') ])) ] if len(items) > 1: for surplus_item in items[1:]: send_message.insert( 1, Message( text= '{dutyName}\n{dutyEmclsName}\n{dutyAddr}\n{dutyTel1}\n{dutyTel3}' .format(**surplus_item))) await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='IBM Bluemix에서 제공하는 "자소서를 분석해주는 서비스"에요.' # ) # ] send_message = [ Message( attachment=TemplateAttachment( payload=GenericTemplate( elements=[ Element(image_url=BRICK_DEFAULT_IMAGE, title='자소서를 분석해주는 서비스', subtitle='IBM Bluemix에서 제공하는 "자소서를 분석해주는 서비스"에요.') ] ) ) ) ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() contents = input_data['store'][0]['value'] try: parsed_result = await PersonalityInsight.get_data(input_data['data'], contents) sending_message = '두구두구!\n자소서에 분석결과\n\n총 단어수 {word_count}\n'.format( word_count=parsed_result.get('word_count', '0')) for item in parsed_result.get('personality', [])[:5]: sending_message += '{name} : {percentile}\n'.format(**item) sending_message += '\n' for item in parsed_result.get('warnings', []): sending_message += '\n{warning_id}\n{message}\n'.format(**item) send_message = [ Message( text='조회된 결과에요.' ), Message( text=sending_message, quick_replies=QuickReply( quick_reply_items=[ QuickReplyTextItem( title='다른 자소서분석', payload='brick|personality|get_started' ) ] ) ) ] except Exception as ex: send_message = [ Message( text='에러가 발생했습니다.\n최소 100단어 이상인 자소서 글을 입력하시거나 잠시 후에 다시 시도해주세요.\n\n에러 메시지: %s' % str(ex) )] await self.fb.send_messages(send_message) await self.brick_db.delete() return None
from blueforge.apis.facebook import CreateFacebookApiClient, RequestDataFormat, Recipient, Message, QuickReplyTextItem, \ QuickReply client = CreateFacebookApiClient( access_token='d') recipient = Recipient(recipient_id='1053565541409779') quick_replies = [QuickReplyTextItem(title='예', payload='yes', image_url=None), QuickReplyTextItem(title='아니요', payload='no', image_url=None)] message = Message(text='Hard Study', quick_replies=QuickReply(quick_reply_items=quick_replies)) final_message = RequestDataFormat(recipient=recipient, message=message) print(client.send_message(final_message))
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='Microsoft Azure-AI Cognitive에서 제공하는 "두장의 사진이 얼마나 닮았는지 알려드리는 서비스"에요.' # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element( image_url=BRICK_DEFAULT_IMAGE, title='두장의 사진이 얼마나 닮았는지 알려드리는 서비스', subtitle= 'Microsoft Azure-AI Cognitive에서 제공하는 "두장의 사진이 얼마나 닮았는지 알려드리는 서비스"에요.' ) ]))) ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() face_1 = input_data['store'][0]['value'] face_2 = input_data['store'][1]['value'] face_1_res = await Face.get_face_id(input_data['data'], face_1) face_2_res = await Face.get_face_id(input_data['data'], face_2) if type(face_2_res) is dict and face_2_res.get('error', False): send_message = [ Message( text='에러가 발생했습니다.\n다시 시도해주세요.\n\nCode: %s\nMessage: %s' % (face_2_res['error'].get('code'), face_2_res['error'].get('message')), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 얼굴비교', payload='brick|face|get_started') ])) ] elif type(face_1_res) is dict and face_1_res.get('error', False): send_message = [ Message( text='에러가 발생했습니다.\n다시 시도해주세요.\n\nCode: %s\nMessage: %s' % (face_1_res['error'].get('code'), face_1_res['error'].get('message')), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 얼굴비교', payload='brick|face|get_started') ])) ] else: if len(face_1_res) == 0 or len(face_2_res) == 0: send_message = [ Message(text='얼굴 감지를 실패했습니다.\n다시 시도해주세요.', quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 얼굴비교', payload='brick|face|get_started') ])) ] else: face_compare = await Face.get_data(input_data['data'], face_1_res[0]['faceId'], face_2_res[0]['faceId']) if len(face_compare) == 0: send_message = [ Message( text='도대체 닮은 구석을 찾으려야 찾을 수가 없네요.', quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 얼굴비교', payload='brick|face|get_started') ])) ] else: send_message = [ Message( text= '조회된 결과에요.\n1이 만점이에요.\n예) 0.37508 은 37% 닮은거에요.' ), Message( text='두구두구!! 딱 이정도 닮았네요.\n닮음수치: {confidence}'. format(**face_compare[0]), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 얼굴비교', payload='brick|face|get_started') ])) ] await self.fb.send_messages(send_message) await self.brick_db.delete() return None
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='인터넷우체국팀에서 제공하는 "우편번호찾기 서비스"에요.' # ) # ] send_message = [ Message( attachment=TemplateAttachment( payload=GenericTemplate( elements=[ Element(image_url=BRICK_DEFAULT_IMAGE, title='우편번호찾기 서비스', subtitle='인터넷우체국팀에서 제공하는 "우편번호찾기 서비스"에요.') ] ) ) ) ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() add_type = input_data['store'][0]['value'] address = input_data['store'][1]['value'] if add_type == '지번': a_type = 'dong' else: a_type = 'road' res = requests.get( url='http://openapi.epost.go.kr/postal/retrieveNewAdressAreaCdService/retrieveNewAdressAreaCdService/getNewAddressListAreaCd?_type=json&serviceKey=%s&searchSe=%s&srchwrd=%s&countPerPage=10¤tPage=1' % ( input_data['data']['api_key'], a_type, urllib.parse.quote_plus(address))) parsed_data = res.json() items = [] if parsed_data.get('NewAddressListResponse', False): if parsed_data['NewAddressListResponse'].get('newAddressListAreaCd', False): if type(parsed_data['NewAddressListResponse']['newAddressListAreaCd']) is dict: items.append(parsed_data['NewAddressListResponse']['newAddressListAreaCd']) else: items = parsed_data['NewAddressListResponse']['newAddressListAreaCd'] items.reverse() if len(items) == 0: send_message = [ Message( text='조회된 결과가 없습니다.', quick_replies=QuickReply( quick_reply_items=[ QuickReplyTextItem( title='다시 검색하기', payload='brick|address|get_started' ) ] ) ) ] else: sending_message = [] for item in items: sending_message.append('{zipNo}\n{lnmAdres}\n{rnAdres}'.format(**item)) send_message = [ Message( text='조회된 결과에요' ), Message( text='\n\n'.join(sending_message), quick_replies=QuickReply( quick_reply_items=[ QuickReplyTextItem( title='다른 우편번호검색', payload='brick|address|get_started' ) ] ) ) ] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
def make_the_bricks(self): designer_brick = [] # get_started (1.1, 1.2) designer_brick.append( FacebookBrick( brick_type='postback', value='get_started', actions=[ FacebookGeneralAction(message=Message( text=self.data['custom_settings']['get_started'])), FacebookGeneralAction(message=Message( attachment=TemplateAttachment(payload=ListTemplate( top_element_style='LARGE', elements=[ Element(title=self.data['basic']['name'], image_url=self.data['basic'] ['profile_image'], buttons=[ PostBackButton( payload='VIEW_PROFILE', title='View') ]), Element(title='Portfolio', subtitle='%s님의 포트폴리오를 보고 싶은가요?' % self.data['basic']['name'], buttons=[ PostBackButton( payload='VIEW_PORTFOLIO', title='View') ]), Element(title='Contact', subtitle='%s님에게 이메일을 보내고 싶은가요?' % self.data['basic']['name'], buttons=[ PostBackButton(payload='CONTACT', title='View') ]) ])))) ])) # Profile(1) / 2 designer_brick.append( FacebookBrick( brick_type='postback', value='VIEW_PROFILE', actions=[ FacebookGeneralAction(message=Message( attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element( title=self.data['basic']['name'], subtitle='{special}\n{residence}'.format( **self.data['basic']), image_url=self.data['basic'] ['profile_image'], buttons=[ PostBackButton( title='Work', payload='VIEW_USERS_WORK'), PostBackButton( title='Specialties', payload='VIEW_USERS_SPECIALTIES'), PostBackButton( title='Summary', payload='VIEW_USERS_SUMMARY'), ], default_action={ 'type': 'web_url', 'url': self.data['basic']['social'], 'webview_height_ratio': 'tall' }) ])))) ])) # Work / 2.1.1 if len(self.data['work']): work_element = [ Element(title='Work', subtitle='%s님의 경력 사항입니다.' % self.data['basic']['name'], image_url=WORK_IMAGE_URL) ] for work in self.data['work']: work_element.append( Element(title=work['name'], subtitle='{period}\n{field}'.format(**work))) designer_brick.append( FacebookBrick( brick_type='postback', value='VIEW_USERS_WORK', actions=[ FacebookGeneralAction(message=Message( attachment=TemplateAttachment(payload=ListTemplate( elements=work_element, top_element_style='LARGE', buttons=[ PostBackButton(title='Menu', payload='get_started') ])))) ])) else: designer_brick.append( FacebookBrick(brick_type='postback', value='VIEW_USERS_WORK', actions=[ FacebookGeneralAction(message=Message( text='%s님이 아직 Work 항목을 입력하지 않았습니다.' % self.data['basic']['name'])) ])) # Specialties / 2.1.2 if len(self.data['specialties']): special_element = [ Element(title='Specialties', subtitle='%s님의 보유기술 및 능력입니다.' % self.data['basic']['name'], image_url=SPECIALTIES_IMAGE_URL) ] for special in self.data['specialties']: special_element.append( Element(title=special['name'], subtitle=special['detail'])) designer_brick.append( FacebookBrick( brick_type='postback', value='VIEW_USERS_SPECIALTIES', actions=[ FacebookGeneralAction(message=Message( attachment=TemplateAttachment(payload=ListTemplate( elements=special_element, top_element_style='LARGE', buttons=[ PostBackButton(title='Menu', payload='get_started') ])))) ])) else: designer_brick.append( FacebookBrick( brick_type='postback', value='VIEW_USERS_SPECIALTIES', actions=[ FacebookGeneralAction(message=Message( text='%s님이 아직 Specialties 항목을 입력하지 않았습니다.' % self.data['basic']['name'])) ])) # Summary / 2.1.3 if self.data['summary']: designer_brick.append( FacebookBrick(brick_type='postback', value='VIEW_USERS_SUMMARY', actions=[ FacebookGeneralAction(message=Message( attachment=ImageAttachment( url=SUMMARY_IMAGE_URL))), FacebookGeneralAction(message=Message( text=self.data['summary'])) ])) else: designer_brick.append( FacebookBrick(brick_type='postback', value='VIEW_USERS_SUMMARY', actions=[ FacebookGeneralAction(message=Message( text='%s님이 아직 Summary 항목을 입력하지 않았습니다.' % self.data['basic']['name'])) ])) # Contact / 4 if self.data['basic'].get('email', False): designer_brick.append( FacebookBrick( brick_type='postback', value='CONTACT', actions=[ FacebookGeneralAction(message=Message( attachment=TemplateAttachment( payload=GenericTemplate(elements=[ Element( title='Contact', subtitle= '자세한 문의는 아래의 메일보내기 버튼을 이용해주세요.', image_url=CONTACT_IMAGE_URL, buttons=[ PostBackButton( title='Send E-Mail', payload='SEND_EMAIL_TO_USER') ]) ])))) ])) else: designer_brick.append( FacebookBrick(brick_type='postback', value='CONTACT', actions=[ FacebookGeneralAction(message=Message( text='%s님이 아직 이메일을 입력하지 않았습니다.' % self.data['basic']['name'])) ])) if self.data.get('portfolio', False) and self.data['portfolio']: temp_element = [] for portfolio in self.data['portfolio'][:10]: res = requests.get(portfolio, headers={ 'User-Agent': 'TelegramBot (like TwitterBot)', 'Accept': 'text/html' }) soup = BeautifulSoup(res.text, 'lxml') temp_element.append( Element(title=soup.find('meta', { 'property': 'og:title' }).get('content'), subtitle=soup.find('meta', { 'property': 'og:description' }).get('content'), image_url=soup.find('meta', { 'property': 'og:image' }).get('content'), buttons=[UrlButton(title='View', url=portfolio)])) designer_brick.append( FacebookBrick(brick_type='postback', value='VIEW_PORTFOLIO', actions=[ FacebookGeneralAction(message=Message( attachment=TemplateAttachment( payload=GenericTemplate( elements=temp_element)))) ])) else: designer_brick.append( FacebookBrick( brick_type='postback', value='VIEW_PORTFOLIO', actions=[ FacebookGeneralAction(message=Message( text='%s님이 아직 Portfolio 항목을 입력하지 않았습니다.' % self.data['basic']['name'])) ])) designer_brick.append( FacebookBrick( brick_type='postback', value='SEND_EMAIL_TO_USER', actions=[FacebookBrickAction(brick_id='mailer', data=[])])) return designer_brick
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='Microsoft Azure-AI Cognitive에서 제공하는 "사진속 감정을 읽어드리는 서비스"에요.' # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element( image_url=BRICK_DEFAULT_IMAGE, title='사진속 감정을 읽어드리는 서비스', subtitle= 'Microsoft Azure-AI Cognitive에서 제공하는 "사진속 감정을 읽어드리는 서비스"에요.' ) ]))) ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() face_1 = input_data['store'][0]['value'] res = await Emotion.get_data(input_data['data'], face_1) if type(res) is dict and res.get('error', False): send_message = [ Message( text= '[에러발생]\nCode: {code}\nMessage: {message}\n\n관리자에게 문의 바랍니다.\[email protected]' .format(**res['error']), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 사진분석', payload='brick|emotion|get_started') ])) ] else: if len(res) == 0: send_message = [ Message(text='감정을 알 수 없어요 ㅜㅜ\n다시 시도해주세요.', quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 사진분석', payload='brick|emotion|get_started') ])) ] else: res_face = res[0]['faceAttributes']['emotion'] sorted_score = sorted(res_face.items(), key=operator.itemgetter(1), reverse=True) send_message = [ Message(text='조회된 결과에요.'), Message(text='두구두구!!\n사진 속의 사람의 감정은 %s이네요.' % EMOTION[sorted_score[0][0]], quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 사진분석', payload='brick|emotion|get_started') ])) ] await self.fb.send_messages(send_message) await self.brick_db.delete() return None
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='인사혁신처에서 제공하는 "공공취업정보검색 서비스"에요.' # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element(image_url=BRICK_DEFAULT_IMAGE, title='공공취업정보검색 서비스', subtitle='인사혁신처에서 제공하는 "공공취업정보검색 서비스"에요.') ]))) ] await self.fb.send_messages(send_message) await self.brick_db.save() await self.facebook('final') elif command == 'final': input_data = await self.brick_db.get() res = await PublicJobs.get_data(input_data) items = get_items_from_xml(res) if type(items) is dict: if items.get('code', '00') == '99' or items.get('code', '00') == '30': send_message = [ tg.SendMessage( text= 'chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [tg.SendMessage(text=UNKNOWN_ERROR_MSG)] else: if len(items) == 0: send_message = [ Message( text='조회된 결과가 없습니다.', quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다시 시도하기', payload='brick|public_jobs|get_started') ])) ] else: sending_message = [] for item in items: sending_message.append( '*{title}*\n{deptName}\n{regdate} ~ {enddate}'. format(**item)) send_message = [ Message(text='조회된 결과에요'), Message( text='\n\n'.join(sending_message), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='새로고침', payload='brick|public_jobs|get_started') ])) ] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='외교부에서 제공하는 "해외국가정보 서비스"에요.' # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element(image_url=BRICK_DEFAULT_IMAGE, title='해외국가정보 서비스', subtitle='외교부에서 제공하는 "해외국가정보 서비스"에요.') ]))) ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() country = input_data['store'][0]['value'] res = requests.get( url= 'http://apis.data.go.kr/1262000/CountryBasicService/getCountryBasicList?serviceKey=%s&numOfRows=10&pageSize=10&pageNo=1&startPage=1&countryName=%s' % (input_data['data']['api_key'], urllib.parse.quote_plus(country))) items = get_items_from_xml(res) if type(items) is dict: if items.get('code', '00') == '99' or items.get('code', '00') == '30': send_message = [ Message( text= 'chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [Message(text=UNKNOWN_ERROR_MSG)] else: if len(items) == 0: send_message = [ Message(text='조회된 결과가 없습니다.', quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 국가검색', payload='brick|country|get_started') ])) ] else: items[0]['basic'] = remove_html_tag(items[0]['basic']) send_message = [ Message(attachment=ImageAttachment( url=download_and_save_image(items[0]['imgUrl']))), Message( text= '{continent}\n*{countryName}({countryEnName})*\n{basic}' .format(**items[0]), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 국가검색', payload='brick|country|get_started') ])) ] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def facebook(self, command): if command == 'get_started': send_message = [ Message( attachment=ImageAttachment( url=BRICK_DEFAULT_IMAGE ) ), Message( text='경찰청에서 제공하는 "습득물조회 서비스"에요. 분류/지역/기간으로 조회기능과 위치기반으로 조회 기능을 제공해요.' ), Message( attachment=TemplateAttachment( payload=GenericTemplate( elements=[ Element( image_url='https://www.chatbrick.io/api/static/brick/img_brick_02_002.png', title='분류/지역/기간으로 조회', subtitle='습득한 물품에 대한 분류, 지역, 기간 정보를 조회할 수 있어요.', buttons=[ PostBackButton( title='조회하기', payload='brick|lostnfound|Menu1' ) ] ), Element( image_url='https://www.chatbrick.io/api/static/brick/img_brick_02_002.png', title='위치기반으로 조회', subtitle='현재 위치주소와 근처에 위치한 지구대의 습득물 정보를 조회 할 수 있어요.', buttons=[ PostBackButton( title='조회하기', payload='brick|lostnfound|Menu2' ) ] ) ] ) ) ) ] await self.fb.send_messages(send_message) await self.brick_db.save(show_msg=False) elif command == 'Menu1': pass elif command == 'final': input_data = await self.brick_db.get() keyword = input_data['store'][0]['value'] to = datetime.datetime.today() today = '%d-%02d-%02d' % (to.year, to.month, to.day) res = requests.get( url='http://openapi.mpm.go.kr/openapi/service/RetrievePblinsttEmpmnInfoService/getList?serviceKey=%s&pageNo=1&startPage=1&numOfRows=20&pageSize=20&Pblanc_ty=e01&Begin_de=%s&Sort_order=1&Kwrd=%s' % ( input_data['data']['api_key'], today, keyword)) items = get_items_from_xml(res) if len(items) == 0: send_message = [ Message( text='조회된 결과가 없습니다.', quick_replies=QuickReply( quick_reply_items=[ QuickReplyTextItem( title='다른 키워드검색', payload='brick|public_jobs|get_started' ) ] ) ) ] else: sending_message = [] for item in items: sending_message.append('*{title}*\n{deptName}\n{regdate} ~ {enddate}'.format(**item)) send_message = [ Message( text='조회된 결과에요' ), Message( text='\n\n'.join(sending_message), quick_replies=QuickReply( quick_reply_items=[ QuickReplyTextItem( title='다른 키워드검색', payload='brick|public_jobs|get_started' ) ] ) ) ] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='한국수출입은행에서 제공하는 "환율정보 서비스"에요.' # ), # Message( # text='chatbrick에서 제공하는 금융정보는 한국수출입은행으로부터 받는 정보로 투자 참고사항이며, 오류가 발생하거나 지연될 수 있습니다.\nchatbrick은 제공된 정보에 의한 투자결과에 법적책임을 지지 않습니다. 게시된 정보는 무단으로 배포할 수 없습니다.' # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element(image_url=BRICK_DEFAULT_IMAGE, title='환율정보 서비스', subtitle='한국수출입은행에서 제공하는 "환율정보 서비스"에요.') ]))), Message( text= 'chatbrick에서 제공하는 금융정보는 한국수출입은행으로부터 받는 정보로 투자 참고사항이며, 오류가 발생하거나 지연될 수 있습니다.\nchatbrick은 제공된 정보에 의한 투자결과에 법적책임을 지지 않습니다. 게시된 정보는 무단으로 배포할 수 없습니다.' ) ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() currency = input_data['store'][0]['value'] rslt = await Currency.get_data(input_data['data']['api_key']) if len(rslt) == 0: send_message = [Message(text='금일의 통화 정보가 없습니다.')] else: send_message = [] for money in rslt: try: if money['cur_unit'] == CURRENCY_UNIT['%02d' % int(currency)]: send_message = [ Message( text= '국가/통화명 : {cur_nm}\n통화코드 : {cur_unit}\n송금 받을 때 (1 {cur_nm} 기준) : {ttb}원\n송금 보낼 때 (1 {cur_nm} 기준) : {tts}원\n매매 기준율 : {deal_bas_r} 원\n장부가격 : {bkpr}\n\n년환가료율 : {yy_efee_r}\n10일환가료율 : {ten_dd_efee_r}\n서울외국환중계 매매기준율 : {kftc_deal_bas_r}\n서울외국환중계 장부가격 : {kftc_bkpr}' .format(**money), quick_replies=QuickReply( quick_reply_items=[ QuickReplyTextItem( title='다른 환율정보조회', payload= 'brick|currency|get_started') ])) ] break except ValueError as ex: send_message = [ Message( text='숫자만 입력하셔야 되요.\n에러 메시지: %s' % str(ex), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 환율정보조회', payload='brick|currency|get_started') ])) ] if len(send_message) == 0: send_message = [Message(text='검색된 결과가 없습니다.')] await self.fb.send_messages(send_message) await self.brick_db.delete() return None
def make_the_bricks(self): designer_brick = [] hackathon_name = self.data['basic']['name'] # get_started (1, 2) - 참가 신청 날짜 일 때, designer_brick.append( FacebookBrick(brick_type='postback', value='get_started', condition=[ { 'type': 'date_between', 'data': { 'start_date': self.data['date']['application_period']['start'], 'end_data': self.data['date']['application_period']['end'] } } ], actions=[ FacebookGeneralAction(message=Message( text=self.data['custom_settings']['get_started'] )), FacebookGeneralAction(message=Message( attachment=TemplateAttachment( payload=GenericTemplate(elements=[ Element(title='%s 안내' % hackathon_name, image_url=self.data['basic']['poster_image'], subtitle='%s에 대한 안내정보에요.' % hackathon_name, buttons=[ PostBackButton(title='일정 및 장소안내', payload='VIEW_SCHEDULE_AND_PLACE'), PostBackButton(title='참가요건', payload='VIEW_REQUIREMENTS'), PostBackButton(title='시상 및 참가혜택', payload='VIEW_PRIZE_AND_BENEFIT') ]), Element(title='%s 참가신청' % hackathon_name, image_url=WORK_IMAGE_URL, subtitle='우리 함께 %s에 참가해요.' % hackathon_name, buttons=[ UrlButton(title='참가 신청하기', url=self.data['application']['url']) ]), Element(image_url=WORK_IMAGE_URL, title='문의', subtitle='%s에 대해 궁금하신점을 말씀해주세요' % hackathon_name, buttons=[ PostBackButton(title='문의하기', payload='CONTACT') ]), Element(image_url=WORK_IMAGE_URL, title='주최/주관/후원 정보', subtitle='%s의 주최/주관/후원 정보에요.' % hackathon_name, buttons=[ PostBackButton(title='보기', payload='VIEW_SPONSOR') ]) ]) ) )) ]) ) # get_started (1, 2) - 참가 신청 날짜가 아닐 때, designer_brick.append( FacebookBrick(brick_type='postback', value='get_started', condition=[ { 'type': 'date_not_between', 'data': { 'start_date': self.data['date']['application_period']['start'], 'end_data': self.data['date']['application_period']['end'] } } ], actions=[ FacebookGeneralAction(message=Message( text=self.data['custom_settings']['get_started'] )), FacebookGeneralAction(message=Message( attachment=TemplateAttachment( payload=GenericTemplate(elements=[ Element(title='%s 안내' % hackathon_name, image_url=self.data['basic']['poster_image'], subtitle='%s에 대한 안내정보에요.' % hackathon_name, buttons=[ PostBackButton(title='일정 및 장소안내', payload='VIEW_SCHEDULE_AND_PLACE'), PostBackButton(title='참가요건', payload='VIEW_REQUIREMENTS'), PostBackButton(title='시상 및 참가혜택', payload='VIEW_PRIZE_AND_BENEFIT') ]), Element(title='%s 참가신청' % hackathon_name, image_url=WORK_IMAGE_URL, subtitle='우리 함께 %s에 참가해요.' % hackathon_name ), Element(image_url=WORK_IMAGE_URL, title='문의', subtitle='%s에 대해 궁금하신점을 말씀해주세요' % hackathon_name, buttons=[ PostBackButton(title='문의하기', payload='CONTACT') ]), Element(image_url=WORK_IMAGE_URL, title='주최/주관/후원 정보', subtitle='%s의 주최/주관/후원 정보에요.' % hackathon_name, buttons=[ PostBackButton(title='보기', payload='VIEW_SPONSOR') ]) ]) ) )) ]) ) # 일정 및 장소안내 / 3.1 place_button = [ PostBackButton(title='본행사 장소보기', payload='VIEW_PLACE_OF_MAIN_MEETING') ] if self.data['place'].get('pre-meeting', False): place_button.insert(0, PostBackButton(title='사전일정 장소보기', payload='VIEW_PLACE_OF_PRE_MEETING')) designer_brick.append( FacebookBrick( brick_type='postback', value='VIEW_SCHEDULE_AND_PLACE', actions=[ FacebookGeneralAction( message=Message( attachment=TemplateAttachment( payload=GenericTemplate( elements=[ Element(image_url=WORK_IMAGE_URL, title='%s의 진행 일정정보에요.' % hackathon_name, buttons=[ # 4 PostBackButton(title='일정보기', payload='VIEW_SCHEDULE') ]), Element(image_url=WORK_IMAGE_URL, title='%s이 진행되는 장소에요.' % hackathon_name, buttons=place_button) ] ) ) ) ) ] ) ) # 일정안내(1) / 4 schedule_action = [ FacebookGeneralAction( message=Message( attachment=ImageAttachment( url=self.data['basic']['poster_image'] ) ) ), FacebookGeneralAction( message=Message( text='참가 신청 일정\n%s ~ %s' % (self.data['date']['application_period']['start'], self.data['date']['application_period']['end']) ) ) ] if self.data['contents'].get('pre-meeting', False): schedule_action.insert(1, FacebookGeneralAction( message=Message( text='사전일정\n:%s\n사전일정 내용\n:%s' % (self.data['date']['pre-meeting'], self.data['contents']['pre-meeting']) ) )) now_date = dateutil.parser.parse(self.data['date']['main-meeting']['start']) for idx, content in enumerate(self.data['contents']['main-meeting']): if (idx+1) == len(self.data['contents']['main-meeting']): schedule_action.append( FacebookGeneralAction( message=Message( attachment=TemplateAttachment( payload=ButtonTemplate( text='본행사 %d년 %d월 %d일\n%s' % (now_date.year, now_date.month, now_date.day, content), buttons=[ UrlButton(title='참가신청하기', url=self.data['application']['url']) ] ) ) ) ) ) else: schedule_action.append( FacebookGeneralAction( message=Message( text='본행사 %d년 %d월 %d일\n%s' % (now_date.year, now_date.month, now_date.day, content) ) ) ) now_date = now_date + datetime.timedelta(days=1) designer_brick.append( FacebookBrick( brick_type='postback', value='VIEW_SCHEDULE', actions=schedule_action ) ) # 사전일정 장소안내 / 5 if self.data['place'].get('pre-meeting', False): designer_brick.append( FacebookBrick( brick_type='postback', value='VIEW_PLACE_OF_PRE_MEETING', actions=[ FacebookGeneralAction( message=Message( attachment=TemplateAttachment( payload=ButtonTemplate( text='{name}\n{address}'.format(**self.data['place']['pre-meeting']), buttons=[ UrlButton( title='지도보기', url=self.data['place']['pre-meeting']['url'] ) ] ) ) ) ) ] ) ) # 본행사 장소안내 / 6 if self.data['place'].get('main-meeting', False): designer_brick.append( FacebookBrick( brick_type='postback', value='VIEW_PLACE_OF_MAIN_MEETING', actions=[ FacebookGeneralAction( message=Message( attachment=TemplateAttachment( payload=ButtonTemplate( text='{name}\n{address}'.format(**self.data['place']['main-meeting']), buttons=[ UrlButton( title='지도보기', url=self.data['place']['main-meeting']['url'] ) ] ) ) ) ) ] ) ) # 참여요건 / 7 designer_brick.append( FacebookBrick( brick_type='postback', value='VIEW_REQUIREMENTS', actions=[ FacebookGeneralAction( message=Message( text=self.data['application']['requirements'] ) ), FacebookGeneralAction( message=Message( attachment=TemplateAttachment( payload=ButtonTemplate( text=self.data['application']['preparation'], buttons=[ UrlButton(title='참가신청하기', url=self.data['application']['url']) ] ) ) ) ) ] ) ) # 시상 및 참가혜택 / 8 prize_text = '시상\n======================\n' for prize in self.data['prize']: prize_text += '{name} / {desc} / {benefit}\n'.format(**prize) designer_brick.append( FacebookBrick( brick_type='postback', value='VIEW_PRIZE_AND_BENEFIT', actions=[ FacebookGeneralAction( message=Message( text=prize_text ) ), FacebookGeneralAction( message=Message( attachment=TemplateAttachment( payload=ButtonTemplate( text=self.data['benefit_of_participant'], buttons=[ UrlButton(title='참가신청하기', url=self.data['application']['url']) ] ) ) ) ) ] ) ) # 문의하기 / 10 designer_brick.append( FacebookBrick( brick_type='postback', value='CONTACT', actions=[ FacebookGeneralAction( message=Message( text='문의사항은 아래의 메일 / 전화를 이용해주세요.\n{email}\n{tel}'.format(**self.data['basic']) ) ) ] ) ) # 주최/주관/후원정보 / 11 sponsor_text = [] thanks = self.data['thanks'] if thanks.get('hoster', False): if thanks['hoster'].strip() != '': sponsor_text.append('주최\n:%s' % thanks['hoster']) if thanks.get('organizer', False): if thanks['organizer'].strip() != '': sponsor_text.append('주관\n:%s' % thanks['organizer']) if thanks.get('sponsor', False): if thanks['sponsor'].strip() != '': sponsor_text.append('협찬\n:%s' % thanks['sponsor']) designer_brick.append( FacebookBrick( brick_type='postback', value='VIEW_SPONSOR', actions=[ FacebookGeneralAction( message=Message( attachment=ImageAttachment(url=WORK_IMAGE_URL) ) ), FacebookGeneralAction( message=Message( text='\n\n'.join(sponsor_text) ) ) ] ) ) return designer_brick
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='과학기술정보통신부 우정사업본부에서 제공하는 "우체국택배조회 서비스"에요.' # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element( image_url=BRICK_DEFAULT_IMAGE, title='우체국택배조회 서비스', subtitle='과학기술정보통신부 우정사업본부에서 제공하는 "우체국택배조회 서비스"에요.' ) ]))) ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() delivery_tracking_code = input_data['store'][0]['value'] res = requests.get( url= 'http://openapi.epost.go.kr/trace/retrieveLongitudinalService/retrieveLongitudinalService/getLongitudinalDomesticList?_type=json&serviceKey=%s&rgist=%s' % (input_data['data']['api_key'], delivery_tracking_code)) parsed_data = res.json() items = [] send_message = [] if parsed_data.get('LongitudinalDomesticListResponse', False): if parsed_data['LongitudinalDomesticListResponse'][ 'cmmMsgHeader']['successYN'] == 'Y': if parsed_data['LongitudinalDomesticListResponse'].get( 'longitudinalDomesticList', False): if type(parsed_data['LongitudinalDomesticListResponse'] ['longitudinalDomesticList']) is dict: items.append( parsed_data['LongitudinalDomesticListResponse'] ['longitudinalDomesticList']) else: items = parsed_data[ 'LongitudinalDomesticListResponse'][ 'longitudinalDomesticList'] tracking_status = '받는분: {addrseNm} / 보내는분: {applcntNm}\n배송상태: {dlvySttus} ({dlvyDe})\n진행상황:\n'.format( **parsed_data['LongitudinalDomesticListResponse']) if len(items) == 0: tracking_status += '상태 기록 없음' else: for item in items: tracking_status += '{dlvyDate} {dlvyTime} {nowLc} {processSttus} {detailDc}\n'.format( **item) send_message = [ Message(text=tracking_status, quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 운송장번호조회', payload='brick|epost|get_started') ])) ] else: send_message = [ Message( text='에러코드: {returnCode}\n에러메시지: {errMsg}'.format( ** parsed_data['LongitudinalDomesticListResponse'] ['cmmMsgHeader'], ), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 운송장번호조회', payload='brick|epost|get_started') ])) ] if len(send_message) == 0: send_message = [Message(text='조회된 결과가 없습니다.')] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
def make_the_bricks_for_facebook(self): designer_brick = [] # get_started (1.1, 1.2) designer_brick.append(FacebookBrick(brick_type='postback', value='get_started', actions=[ FacebookGeneralAction(message=Message(text=self.data['custom_settings']['get_started'])), FacebookGeneralAction(message=Message( attachment=TemplateAttachment( payload=ListTemplate(top_element_style='LARGE', elements=[Element(title=self.data['basic']['name'], image_url=self.data['basic']['profile_image'], buttons=[PostBackButton(payload='VIEW_PROFILE', title='View')]), Element(title='Portfolio', subtitle='%s님의 포트폴리오를 보고 싶은가요?' % self.data['basic']['name'], buttons=[ PostBackButton(payload='VIEW_PORTFOLIO', title='View')]), Element(title='Contact', subtitle='%s님에게 이메일을 보내고 싶은가요?' % self.data['basic'][ 'name'], buttons=[PostBackButton(payload='CONTACT', title='View')]) ] ) ) ) ) ] ) ) # Profile(1) / 2 designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_PROFILE', actions=[ FacebookGeneralAction(message=Message( attachment=TemplateAttachment( payload=GenericTemplate(elements=[ Element(title=self.data['basic']['name'], subtitle='{special}\n{residence}'.format(**self.data['basic']), image_url=self.data['basic']['profile_image'], buttons=[ PostBackButton(title='Work', payload='VIEW_USERS_WORK'), PostBackButton(title='Specialties', payload='VIEW_USERS_SPECIALTIES'), PostBackButton(title='Summary', payload='VIEW_USERS_SUMMARY'), ], default_action={ 'type': 'web_url', 'url': self.data['basic']['social'], 'webview_height_ratio': 'tall' } ) ]) ) )) ])) # Work / 2.1.1 if self.data.get('work', False) and len(self.data['work']): work_element = [ Element(title='Work', subtitle='%s님의 경력 사항입니다.' % self.data['basic']['name'], image_url=WORK_IMAGE_URL) ] for work in self.data['work']: if work['name'].strip() == '': raise RuntimeError('경력의 근무 회사의 이름이 없어요.') work_element.append(Element(title=work['name'], subtitle='{period}\n{field}'.format(**work))) designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_USERS_WORK', actions=[ FacebookGeneralAction(message=Message( attachment=TemplateAttachment( payload=ListTemplate(elements=work_element, top_element_style='LARGE', buttons=[ PostBackButton(title='Menu', payload='get_started') ]) ) )) ])) else: designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_USERS_WORK', actions=[ FacebookGeneralAction(message=Message(text='%s님이 아직 Work 항목을 입력하지 않았습니다.' % self.data['basic']['name'])) ])) # Specialties / 2.1.2 if self.data.get('specialties', False) and len(self.data['specialties']): special_element = [ Element(title='Specialties', subtitle='%s님의 보유기술 및 능력입니다.' % self.data['basic']['name'], image_url=SPECIALTIES_IMAGE_URL) ] for special in self.data['specialties']: if special['name'].strip() == '': raise RuntimeError('보유 기술의 이름이 없어요.') if special['detail'].strip() == '': raise RuntimeError('보유 기술의 설명이 없어요.') special_element.append(Element(title=special['name'], subtitle=special['detail'])) designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_USERS_SPECIALTIES', actions=[ FacebookGeneralAction(message=Message( attachment=TemplateAttachment( payload=ListTemplate(elements=special_element, top_element_style='LARGE', buttons=[ PostBackButton(title='Menu', payload='get_started') ]) ) )) ])) else: designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_USERS_SPECIALTIES', actions=[ FacebookGeneralAction( message=Message(text='%s님이 아직 Specialties 항목을 입력하지 않았습니다.' % self.data['basic']['name'])) ])) # Summary / 2.1.3 if self.data.get('summary', False) and self.data['summary'].strip() != '': designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_USERS_SUMMARY', actions=[ FacebookGeneralAction(message=Message( attachment=ImageAttachment(url=SUMMARY_IMAGE_URL) )), FacebookGeneralAction(message=Message( text=self.data['summary'] )) ])) else: designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_USERS_SUMMARY', actions=[ FacebookGeneralAction( message=Message(text='%s님이 아직 Summary 항목을 입력하지 않았습니다.' % self.data['basic']['name'])) ])) # Contact / 4 if self.data['basic'].get('email', False) and self.data['basic']['email'].strip() != '': designer_brick.append(FacebookBrick(brick_type='postback', value='CONTACT', actions=[ FacebookGeneralAction(message=Message( attachment=TemplateAttachment( payload=GenericTemplate(elements=[ Element(title='Contact', subtitle='자세한 문의는 아래의 메일보내기 버튼을 이용해주세요.', image_url=CONTACT_IMAGE_URL, buttons=[ PostBackButton(title='Send E-Mail', payload='SEND_EMAIL_TO_USER') ] ) ]) ) )) ])) else: designer_brick.append(FacebookBrick(brick_type='postback', value='CONTACT', actions=[ FacebookGeneralAction( message=Message(text='%s님이 아직 이메일을 입력하지 않았습니다.' % self.data['basic']['name'])) ])) if self.data.get('portfolio', False) and len(self.data['portfolio']): temp_element = [] for portfolio in self.data['portfolio'][:10]: temp_element.append(Element(title=portfolio['title'], subtitle=portfolio['sub_title'], image_url=portfolio['image_url'], buttons=[ UrlButton(title='View', url=portfolio['url']) ] )) designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_PORTFOLIO', actions=[ FacebookGeneralAction(message=Message( attachment=TemplateAttachment( payload=GenericTemplate(elements=temp_element) ) )) ])) else: designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_PORTFOLIO', actions=[ FacebookGeneralAction( message=Message(text='%s님이 아직 Portfolio 항목을 입력하지 않았습니다.' % self.data['basic']['name'])) ])) designer_brick.append(FacebookBrick(brick_type='postback', value='SEND_EMAIL_TO_USER', actions=[ FacebookBrickAction( brick_id='mailerforset', data={ 'to': self.data['basic']['email'].strip() } ) ])) return designer_brick
def make_the_bricks(self): designer_brick = [] elements = [] for brick in self.data['brick']: designer_brick.append( FacebookBrick( brick_type='postback', value=brick['id'], actions=[ FacebookBrickAction( brick_id=brick['id'], data=brick['data'] ) ] ) ) for keyword in brick['keywords']: designer_brick.append( FacebookBrick( brick_type='text', value=keyword, actions=[ FacebookBrickAction( brick_id=brick['id'], data=brick['data'] ) ] ) ) for brick_rec in self.bricks: if brick_rec['id'] == brick['id']: elements.append( Element( title=brick_rec['name'], subtitle=brick_rec['api']['desc'], image_url=brick_rec['img'], buttons=[ PostBackButton( title='선택', payload=brick['id'] ) ] ) ) break designer_brick.append( FacebookBrick( brick_type='postback', value='get_started', actions=[ FacebookGeneralAction( message=Message( attachment=TemplateAttachment( payload=GenericTemplate( elements=elements ) ) ) ) ] ) ) return designer_brick
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='Naver Developers에서 제공하는 "사진속 유명인 찾기 서비스"에요.' # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element(image_url=BRICK_DEFAULT_IMAGE, title='사진속 유명인 찾기 서비스', subtitle= 'Naver Developers에서 제공하는 "사진속 유명인 찾기 서비스"에요.') ]))) ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() contents = input_data['store'][0]['value'] parsed_result = await Who.get_data(input_data['data'], contents) if parsed_result.get('faces', False): if len(parsed_result['faces']) == 0: send_message = [Message(text='탐지된 얼굴이 없습니다.')] else: send_message = [ Message( text= '조회된 결과에요.\n1이 만점이에요.\n예) 0.37508 은 37% 확률을 말하는거에요. 56%정도면 거의 동일인이라고 볼 수 있어요.' ), Message( text= '두구두구!!\n사진 속의 사람은 {celebrity[confidence]}의 확률로 {celebrity[value]}이네요.' .format(**parsed_result['faces'][0]), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem( title='다른 사진분석', payload='brick|who|get_started') ])) ] else: send_message = [ Message( text='에러코드: {errorCode}\n에러메시지: {errorMessage}'.format( **parsed_result), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem(title='다른 사진분석', payload='brick|who|get_started') ])) ] await self.fb.send_messages(send_message) await self.brick_db.delete() return None
async def facebook(self, command): if command == 'get_started': send_message = [ Message( attachment=ImageAttachment( url=BRICK_DEFAULT_IMAGE[1] ) ), Message( text='블루핵에서 제공하는 "메일보내기 서비스"예요.' ), Message( attachment=TemplateAttachment( payload=GenericTemplate( elements=[ Element(title='메일전송', subtitle='챗봇에서 메일을 보낼 수 있어요', buttons=[ PostBackButton( title='메일보내기', payload='brick|mailer|show_data' ) ]) ] ) ) ) ] await self.fb.send_messages(send_message) elif command == 'show_data': await self.brick_db.save() elif command == 'cancel': await self.brick_db.delete() await self.fb.send_message( message=Message( text='메일 보내기를 취소했어요.', quick_replies=QuickReply( quick_reply_items=[ QuickReplyTextItem( title='새 메일보내기', payload='brick|mailer|show_data' ) ] ) )) elif command == 'final': input_data = await self.brick_db.get() msg = MIMEText(input_data['store'][2]['value']) msg['Subject'] = '%s로부터 이메일입니다.' % input_data['store'][0]['value'] msg['To'] = input_data['store'][1]['value'] self.smtp.ehlo() self.smtp.starttls() self.smtp.login(self.sender_email, self.sender_password) self.smtp.sendmail(self.sender_email, input_data['store'][1]['value'], msg.as_string()) await self.fb.send_message( message=Message( text='메일 보내기가 완료되었어요.', quick_replies=QuickReply( quick_reply_items=[ QuickReplyTextItem( title='연속하여 메일보내기', payload='brick|mailer|show_data' ) ] ) )) return None
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='Naver Developers에서 제공하는 "URL 줄이기 서비스"에요.' # ), # Message( # attachment=TemplateAttachment( # payload=GenericTemplate( # elements=[ # Element( # image_url='https://www.chatbrick.io/api/static/brick/img_brick_23_002.png', # title='URL 줄이기', # subtitle='너무 길었던 URL을 줄여드려요.', # buttons=[ # PostBackButton( # title='줄이기', # payload='brick|shortener|short' # ) # ] # ) # ] # ) # ) # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element( image_url=BRICK_DEFAULT_IMAGE, title='URL 줄이기 서비스', subtitle='Naver Developers에서 제공하는 "URL 줄이기 서비스"에요.' ) ]))), Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element( image_url= 'https://www.chatbrick.io/api/static/brick/img_brick_23_002.png', title='URL 줄이기', subtitle='너무 길었던 URL을 줄여드려요.', buttons=[ PostBackButton(title='줄이기', payload='brick|shortener|short') ]) ]))) ] await self.fb.send_messages(send_message) elif command == 'short': await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() url = input_data['store'][0]['value'] result = await Shortener.get_short_url( input_data['data']['client_id'], input_data['data']['client_secret'], url) if result.get('errorCode', False): send_message = [Message(text='에러가 발생했습니다.\n다시 시도해주세요.')] logger.error(result) else: send_message = [ Message(text='줄여진 URL 결과에요.'), Message( text='%s' % result['result'].get('url', ''), quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem(title='다른 URL 줄이기', payload='brick|shortener|short') ])) ] await self.fb.send_messages(send_message) await self.brick_db.delete() return None
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='국토교통부에서 제공하는 "열차조회 서비스"에요. 코레일/SRT 모두 조회 가능해요.' # ), # Message( # attachment=TemplateAttachment( # payload=GenericTemplate( # elements=[ # Element( # image_url='https://www.chatbrick.io/api/static/brick/img_brick_01_002.png', # title='열차조회', # subtitle='코레일/SRT 모두 조회할 수 있어요', # buttons=[ # PostBackButton( # title='조회하기', # payload='brick|train|show_data' # ) # ] # ) # ] # ) # ) # ) # ] send_message = [ Message( attachment=TemplateAttachment( payload=GenericTemplate( elements=[ Element(image_url=BRICK_DEFAULT_IMAGE, title='열차조회 서비스', subtitle='국토교통부에서 제공하는 "열차조회 서비스"에요. 코레일/SRT 모두 조회 가능해요.') ] ) ) ), Message( attachment=TemplateAttachment( payload=GenericTemplate( elements=[ Element( image_url='https://www.chatbrick.io/api/static/brick/img_brick_01_002.png', title='열차조회', subtitle='코레일/SRT 모두 조회할 수 있어요', buttons=[ PostBackButton( title='조회하기', payload='brick|train|show_data' ) ] ) ] ) ) ) ] await self.fb.send_messages(send_message) elif command == 'show_data': await self.brick_db.save() elif command == 'final': input_data = await self.brick_db.get() departure_station = input_data['store'][0]['value'].strip() destination_station = input_data['store'][1]['value'].strip() departure_date = input_data['store'][2]['value'] train_type = input_data['store'][3]['value'] if STATION.get(departure_station) is None: send_message = [ Message( text='출발역이 조회할 수 없는 역입니다.', quick_replies=QuickReply( quick_reply_items=[ QuickReplyTextItem( title='다시 검색하기', payload='brick|train|show_data' ) ] ) ) ] elif STATION.get(destination_station) is None: send_message = [ Message( text='도착역이 조회할 수 없는 역입니다.', quick_replies=QuickReply( quick_reply_items=[ QuickReplyTextItem( title='다시 검색하기', payload='brick|train|show_data' ) ] ) ) ] else: res = requests.get( url='http://openapi.tago.go.kr/openapi/service/TrainInfoService/getStrtpntAlocFndTrainInfo?serviceKey=%s&numOfRows=500&pageSize=500&pageNo=1&startPage=1&depPlaceId=%s&arrPlaceId=%s&depPlandTime=%s&trainGradeCode=%s' % ( input_data['data']['api_key'], STATION[departure_station], STATION[destination_station], departure_date, train_type)) items = get_items_from_xml(res) if type(items) is dict: if items.get('code', '00') == '99' or items.get('code', '00') == '30': send_message = [ Message( text='chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [ Message( text=UNKNOWN_ERROR_MSG ) ] else: if len(items) == 0: send_message = [ Message( text='조회된 결과가 없습니다.', quick_replies=QuickReply( quick_reply_items=[ QuickReplyTextItem( title='다시 검색하기', payload='brick|train|show_data' ) ] ) ) ] else: result_message = '{depplacename} -> {arrplacename}\n\n'.format(**items[0]) for item in items: departure_train_datetime = dateutil.parser.parse(item['depplandtime']) arrive_train_datetime = dateutil.parser.parse(item['arrplandtime']) gap = Train.days_hours_minutes(arrive_train_datetime - departure_train_datetime) item['fromtodatetime'] = '%02d:%02d -> %02d:%02d' % ( departure_train_datetime.hour, departure_train_datetime.minute, arrive_train_datetime.hour, arrive_train_datetime.minute) item['time_delta'] = '%02d:%02d' % (gap[0], gap[1]) item['adultcharge_formmated'] = format(int(item['adultcharge']), ',') result_message += '{traingradename} {fromtodatetime} {time_delta} {adultcharge_formmated}\n'.format( **item) send_message = [ Message( text=result_message, quick_replies=QuickReply( quick_reply_items=[ QuickReplyTextItem( title='다시 검색하기', payload='brick|train|get_started' ) ] ) ) ] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def facebook(self, command): if command == 'get_started': # send_message = [ # Message( # attachment=ImageAttachment( # url=BRICK_DEFAULT_IMAGE # ) # ), # Message( # text='블루핵에서 제공하는 "메일보내기 서비스"예요.' # ), # Message( # attachment=TemplateAttachment( # payload=GenericTemplate( # elements=[ # Element(title='메일전송', # subtitle='챗봇에서 메일을 보낼 수 있어요', # image_url=BRICK_GENERIC_TEMPLATE_IMAGE, # buttons=[ # PostBackButton( # title='메일보내기', # payload='brick|mailer|show_data' # ) # ]) # ] # ) # ) # ) # ] send_message = [ Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element(image_url=BRICK_DEFAULT_IMAGE, title='메일보내기 서비스', subtitle='블루핵에서 제공하는 "메일보내기 서비스"예요.') ]))), Message(attachment=TemplateAttachment(payload=GenericTemplate( elements=[ Element(title='메일전송', subtitle='챗봇에서 메일을 보낼 수 있어요', image_url=BRICK_GENERIC_TEMPLATE_IMAGE, buttons=[ PostBackButton( title='메일보내기', payload='brick|mailer|show_data') ]) ]))) ] await self.fb.send_messages(send_message) elif command == 'show_data': await self.brick_db.save() elif command == 'cancel': await self.brick_db.delete() await self.fb.send_message(message=Message( text='메일 보내기를 취소했어요.', quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem(title='새 메일보내기', payload='brick|mailer|show_data') ]))) elif command == 'final': input_data = await self.brick_db.get() msg = MIMEText(input_data['store'][2]['value']) msg['Subject'] = '%s로부터 이메일입니다.' % input_data['store'][0]['value'] msg['To'] = input_data['store'][1]['value'] result = '메일 보내기가 완료되었어요.' if self.fb.log_id is None: self.fb.log_id = 'FBSendMessage|%d' % int(time.time() * 1000) try: self.smtp.ehlo() self.smtp.starttls() self.smtp.login(self.sender_email, self.sender_password) self.smtp.sendmail(self.sender_email, input_data['store'][1]['value'], msg.as_string()) except: result = '메일 전송을 실패했습니다.\n잠시 후 다시 시도해주세요.' save_a_log_to_server({ 'log_id': self.fb.log_id, 'user_id': self.fb.user_id, 'os': '', 'application': 'facebook', 'api_code': 'mail', 'api_provider_code': 'chatbrick', 'origin': 'webhook_server', 'end': int(time.time() * 1000), 'remark': 'SMTP 통신으로 이메일 전송함' }) await self.fb.send_message(message=Message( text=result, quick_replies=QuickReply(quick_reply_items=[ QuickReplyTextItem(title='연속하여 메일보내기', payload='brick|mailer|show_data') ]))) await self.brick_db.delete() return None