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='국토교통부에서 제공하는 "열차조회 서비스"에요. 코레일/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( # 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[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='한국천문연구원에서 제공하는 "쉬는날 조회 서비스"에요.' # ), # 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
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에서 제공하는 "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
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 = [] 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='경찰청에서 제공하는 "습득물조회 서비스"에요. 분류/지역/기간으로 조회기능과 위치기반으로 조회 기능을 제공해요.' ), 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
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='블루핵에서 제공하는 "메일보내기 서비스"예요.' # ), # 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