async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage(text='한국수출입은행에서 제공하는 "환율정보 서비스"에요.', ), tg.SendMessage( 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 = [tg.SendMessage(text='금일의 통화 정보가 없습니다.')] else: send_message = [] for money in rslt: try: if money['cur_unit'] == CURRENCY_UNIT['%02d' % int(currency)]: send_message = [ tg.SendMessage( 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), reply_markup=tg.MarkUpContainer( inline_keyboard=[[ tg.CallbackButton( text='다른 환율정보조회', callback_data= 'BRICK|currency|get_started') ]])) ] break except ValueError as ex: send_message = [ tg.SendMessage( text='숫자만 입력해야 되요.\n에러 메시지: %s' % str(ex), reply_markup=tg.MarkUpContainer( inline_keyboard=[[ tg.CallbackButton( text='다른 환율정보조회', callback_data= 'BRICK|currency|get_started') ]])) ] if len(send_message) == 0: send_message = [tg.SendMessage(text='검색된 결과가 없습니다.')] await self.fb.send_messages(send_message) await self.brick_db.delete() return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage(text='외교부에서 제공하는 "해외에서 SOS 서비스"에요.') ] 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/ContactService/getContactList?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 = [ tg.SendMessage( text= 'chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [tg.SendMessage(text=UNKNOWN_ERROR_MSG)] else: if len(items) == 0: send_message = [tg.SendMessage(text='조회된 결과가 없습니다.')] else: sending_message = [] for item in items: item['contact'] = remove_html_tag(item['contact']) sending_message.append( '*{countryName}*\n구분 : {continent}\n내용 : \n{contact}' .format(**item)) send_message = [ tg.SendMessage( text='\n\n'.join(sending_message), parse_mode='Markdown', reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 국가조회', callback_data='BRICK|broad_sos|get_started' ) ]])) ] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage(text='한국전력공사에서 제공하는 "전기차충전소 조회 서비스"에요.') ] 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 = [ tg.SendMessage( text= 'chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [tg.SendMessage(text=UNKNOWN_ERROR_MSG)] else: if len(items) == 0: send_message = [tg.SendMessage(text='조회된 결과가 없습니다.')] else: sending_message = '' for item in items: sending_message += '*{csNm}*\n충전소ID : {cpId}\n충전타입 : {cpNm}\n상태 : {cpStat}\n주소 : {addr}\n[구글지도](https://www.google.com/maps/?q={lat},{longi})\n\n'.format( **item) send_message = [ tg.SendMessage( text=sending_message, parse_mode='Markdown', disable_web_page_preview=True, reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 충전소 검색', callback_data='BRICK|electric|get_started') ]])) ] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage(text='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 = [ tg.SendMessage(text='조회된 결과에요'), tg.SendPhoto(photo='https:%s' % parsed_result['animalImgUrl']), tg.SendMessage( text= '출생년도 : {year}\n운세 : {summary}\n자세한 내용 : {description}' .format(**parsed_result), reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 운세검색', callback_data='BRICK|luck|get_started') ]])) ] except: send_message = [tg.SendMessage(text='조회된 결과가 없습니다.')] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto( photo=BRICK_DEFAULT_IMAGE ), tg.SendMessage( text='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) except Exception as ex: sending_message = '에러가 발생했습니다.\n최소 100단어 이상인 자소서 글을 입력하시거나 잠시 후에 다시 시도해주세요.\n\n에러 메시지: %s' % str(ex) await self.fb.send_message( tg.SendMessage( text=sending_message, reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='다른 자소서분석', callback_data='BRICK|personality|get_started' ) ] ] ) )) await self.brick_db.delete() return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage( text='Naver Developers에서 제공하는 "사진속 유명인 찾기 서비스"에요.') ] await self.fb.send_messages(send_message) await self.brick_db.save() elif command == 'final': logger.info(self.fb.send_action('goSendMessage')) 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 = [tg.SendMessage(text='탐지된 얼굴이 없습니다.')] else: send_message = [ tg.SendMessage( text= '조회된 결과에요.\n1이 만점이에요.\n예) 0.37508 은 37% 확률을 말하는거에요. 56%정도면 거의 동일인이라고 볼 수 있어요.' ), tg.SendMessage( text= '두구두구!!\n사진 속의 사람은 {celebrity[confidence]}의 확률로 {celebrity[value]}이네요.' .format(**parsed_result['faces'][0]), reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 사진분석', callback_data='BRICK|who|get_started') ]])) ] else: send_message = [ tg.SendMessage( text='에러코드: {errorCode}\n에러메시지: {errorMessage}'.format( **parsed_result), reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 사진분석', callback_data='BRICK|who|get_started') ]])) ] await self.fb.send_messages(send_message) await self.brick_db.delete() return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage(text='(주)나눔로또에서 제공하는 "로또당첨번호 서비스"에요.') ] 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 = 'SendMessage|%d' % int(time.time() * 1000) res = requests.get( url= 'http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=%s' % num, verify=False) save_a_log_to_server({ 'log_id': self.fb.log_id, 'user_id': self.fb.user_id, 'os': '', 'application': 'telegram', '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( tg.SendMessage( text= '두구두구두구 ~\n조회하신 {drwNo}회 당첨번호는 {drwtNo1},{drwtNo2},{drwtNo3},{drwtNo4},{drwtNo5},{drwtNo6} 에 보너스번호는 {bnusNo} 이에요.\n부디 1등이길!!' .format(**parsed_result), reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른회차검색', callback_data='BRICK|lotto|get_started') ]]))) return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto( photo=BRICK_DEFAULT_IMAGE ), tg.SendMessage( text='안녕하세요. 장소 테스트입니다.' ), tg.SendMessage( text='위치를 보내주세요.' ) ] await self.fb.send_messages(send_message) return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage( text='Naver Developers에서 제공하는 "URL 줄이기 서비스"에요.', reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='URL 줄이기', callback_data='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 = [tg.SendMessage(text='에러가 발생했습니다.\n다시 시도해주세요.')] logger.error(result) else: send_message = [ tg.SendMessage(text='줄여진 URL 결과에요.'), tg.SendMessage( text='%s' % result['result'].get('url', ''), reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 URL 줄이기', callback_data='BRICK|shortener|short') ]])) ] await self.fb.send_messages(send_message) await self.brick_db.delete() return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage( text='한국천문연구원에서 제공하는 "쉬는날 조회 서비스"에요.', reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='이번달에 쉬는날', callback_data='BRICK|holiday|this_month'), tg.CallbackButton( text='조회할 년/월 입력', callback_data='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 = 'SendMessage|%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': 'telegram', '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 = [ tg.SendMessage( text= 'chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [tg.SendMessage(text=UNKNOWN_ERROR_MSG)] else: if len(items) == 0: if command == 'prev_month' or command == 'this_month': send_message = [ tg.SendMessage( text='*%s년 %s월*\n조회된 결과가 없습니다.' % (year, month), parse_mode='Markdown', reply_markup=tg. MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='이전달 조회', callback_data='BRICK|holiday|prev_month' ), tg.CallbackButton( text='이전달 조회', callback_data='BRICK|holiday|next_month' ) ]])) ] else: send_message = [ tg.SendMessage( text='*%s년 %s월*\n조회된 결과가 없습니다.' % (year, month), parse_mode='Markdown', reply_markup=tg.MarkUpContainer( inline_keyboard=[[ tg.CallbackButton( text='다른 달 조회하기', callback_data= 'BRICK|holiday|get_started') ]])) ] else: sending_message = [] for item in items: sending_message.append( '*{locdate}*\n공휴일 유무: {isHoliday}\n공휴일 내용: {dateName}' .format(**item)) send_message = [ tg.SendMessage( text='\n\n'.join(sending_message), parse_mode='Markdown', reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='이전달 조회', callback_data= 'BRICK|holiday|prev_month') ], [ tg.CallbackButton( text='다음달 조회', callback_data= 'BRICK|holiday|next_month') ] ])) ] await self.fb.send_messages(send_message) return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage( text= '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 = [ tg.SendMessage( text= '*[에러발생]*\nCode: {code}\nMessage: {message}\n\n관리자에게 문의 바랍니다.\[email protected]' .format(**res['error']), parse_mode='Markdown', reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 사진분석', callback_data='BRICK|emotion|get_started') ]])) ] else: if len(res) == 0: send_message = [ tg.SendMessage( text='감정을 알 수 없어요 ㅜㅜ\n다시 시도해주세요.', reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 사진분석', callback_data='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 = [ tg.SendMessage(text='조회된 결과에요.'), tg.SendMessage( text='두구두구!!\n사진 속의 사람의 감정은 %s이네요.' % EMOTION[sorted_score[0][0]], reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 사진분석', callback_data='BRICK|emotion|get_started') ]])) ] await self.fb.send_messages(send_message) await self.brick_db.delete() return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage(text='중앙응급의료센터에서 제공하는 "응급실검색 서비스"에요.') ] 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 = [ tg.SendMessage( text= 'chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [tg.SendMessage(text=UNKNOWN_ERROR_MSG)] else: if len(items) == 0: send_message = [tg.SendMessage(text='조회된 결과가 없습니다.')] else: send_message = [ tg.SendMessage(text='조회된 결과에요.'), tg.SendMessage( text= '*{dutyName}*\n{dutyEmclsName}\n{dutyAddr}\n{dutyTel1}\n{dutyTel3}' .format(**items[0]), parse_mode='Markdown', reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 지역검색', callback_data='BRICK|emergency|get_started' ) ]])) ] if len(items) > 1: for surplus_item in items[1:]: send_message.insert( 1, tg.SendMessage( text= '*{dutyName}*\n{dutyEmclsName}\n{dutyAddr}\n{dutyTel1}\n{dutyTel3}' .format(**surplus_item), parse_mode='Markdown')) await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto( photo=BRICK_DEFAULT_IMAGE ), tg.SendMessage( text='인사혁신처에서 제공하는 "공공취업정보검색 서비스"에요.' ) ] await self.fb.send_messages(send_message) await self.brick_db.save() 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 = [ tg.SendMessage( text='조회된 결과가 없습니다.', reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='다른 키워드검색', callback_data='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 = [ tg.SendMessage( text='조회된 결과에요.' ), tg.SendMessage( text='\n\n'.join(sending_message), parse_mode='Markdown', reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='다른 키워드검색', callback_data='BRICK|public_jobs|get_started' ) ] ] ) ) ] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto( photo=BRICK_DEFAULT_IMAGE ), tg.SendMessage( text='인터넷우체국팀에서 제공하는 "우편번호찾기 서비스"에요.' ) ] 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 = [ tg.SendMessage( text='조회된 결과가 없습니다.' ) ] else: sending_message = [] for item in items: sending_message.append('*{zipNo}*\n{lnmAdres}\n{rnAdres}'.format(**item)) send_message = [ tg.SendMessage( text='조회된 결과에요.' ), tg.SendMessage( text='\n\n'.join(sending_message), parse_mode='Markdown', reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='다른 우편번호검색', callback_data='BRICK|address|get_started' ) ] ] ) ) ] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage( text= '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 = [ tg.SendMessage( text='에러가 발생했습니다.\n다시 시도해주세요.\n\nCode: %s\nMessage: %s' % (face_2_res['error'].get('code'), face_2_res['error'].get('message')), reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 얼굴비교', callback_data='BRICK|face|get_started') ]])) ] elif type(face_1_res) is dict and face_1_res.get('error', False): send_message = [ tg.SendMessage( text='에러가 발생했습니다.\n다시 시도해주세요.\n\nCode: %s\nMessage: %s' % (face_1_res['error'].get('code'), face_1_res['error'].get('message')), reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 얼굴비교', callback_data='BRICK|face|get_started') ]])) ] else: if len(face_1_res) == 0 or len(face_2_res) == 0: send_message = [ tg.SendMessage( text='얼굴 감지를 실패했습니다.\n다시 시도해주세요.', reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 얼굴비교', callback_data='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 = [ tg.SendMessage( text='도대체 닮은 구석을 찾으려야 찾을 수가 없네요.', reply_markup=tg. MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 얼굴비교', callback_data='BRICK|face|get_started') ]])) ] else: send_message = [ tg.SendMessage( text= '조회된 결과에요.\n1이 만점이에요.\n예) 0.37508 은 37% 닮은거에요.' ), tg.SendMessage( text='두구두구!! 딱 이정도 닮았네요.\n닮음수치: {confidence}'. format(**face_compare[0]), reply_markup=tg. MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 얼굴비교', callback_data='BRICK|face|get_started') ]])) ] await self.fb.send_messages(send_message) await self.brick_db.delete() return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage(text='과학기술정보통신부 우정사업본부에서 제공하는 "우체국택배조회 서비스"에요.') ] 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 = [ tg.SendMessage( text=tracking_status, parse_mode='Markdown', reply_markup=tg. MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 운송장번호조회', callback_data='BRICK|epost|get_started' ) ]])) ] else: send_message = [ tg.SendMessage( text='에러코드: {returnCode}\n에러메시지: {errMsg}'.format( ** parsed_data['LongitudinalDomesticListResponse'] ['cmmMsgHeader']), reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 운송장번호조회', callback_data='BRICK|epost|get_started') ]])) ] if len(send_message) == 0: send_message = [tg.SendMessage(text='조회된 결과가 없습니다.')] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
def make_the_bricks_for_telegram(self): designer_brick = [] designer_brick.append( TelegramBrick( brick_type='bot_command', value='start', actions=[ TelegramGeneralAction( message=tg.SendMessage( text=self.data['custom_settings']['get_started'] ) ), TelegramGeneralAction( message=tg.SendPhoto( photo=self.data['basic']['profile_image'], ) ), TelegramGeneralAction( message=tg.SendMessage( text='*[{name}]*'.format( **self.data['basic']), parse_mode='Markdown', reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='Profile', callback_data='profile' ), tg.CallbackButton( text='Portfolio', callback_data='portfolio' ) ], [ tg.CallbackButton( text='Contact', callback_data='contact' ) ] ] ) ) ) ] ) ) work_text = '%s님의 경력사항입니다.' % self.data['basic']['name'] for work in self.data['work']: work_text += '\n\n*{name}*\n{period}\n{field}'.format(**work) special_text = '%s님의 보유기술 및 능력입니다' % self.data['basic']['name'] for spc in self.data['specialties']: special_text += '\n\n*{name}*\n{detail}'.format(**spc) reply_markup = tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='Profile', callback_data='EDIT|profile|3' ), tg.CallbackButton( text='Work', callback_data='EDIT|profile|0' ) ], [ tg.CallbackButton( text='Specialties', callback_data='EDIT|profile|1' ), tg.CallbackButton( text='Summary', callback_data='EDIT|profile|2' ) ] ] ) designer_brick.append( TelegramBrick( brick_type='callback', value='profile', actions=[ TelegramGeneralAction( message=tg.SendMessage( text='*{name}*\n{special}\n{residence}\n[{social}]({social})'.format(**self.data['basic']), parse_mode='Markdown', reply_markup=reply_markup ) ) ], edits=[ TelegramGeneralAction( message=tg.EditMessageText( text=work_text, parse_mode='Markdown', reply_markup=reply_markup ) ), TelegramGeneralAction( message=tg.EditMessageText( text=special_text, parse_mode='Markdown', reply_markup=reply_markup ) ), TelegramGeneralAction( message=tg.EditMessageText( text=self.data['summary'], parse_mode='Markdown', reply_markup=reply_markup ) ), TelegramGeneralAction( message=tg.EditMessageText( text='*{name}*\n{special}\n{residence}\n[{social}]({social})'.format(**self.data['basic']), parse_mode='Markdown', reply_markup=reply_markup ) ) ] ) ) designer_brick.append( TelegramBrick( brick_type='bot_command', value='profile', actions=[ TelegramGeneralAction( message=tg.SendMessage( text='*{name}*\n{special}\n{residence}\n[{social}]({social})'.format(**self.data['basic']), parse_mode='Markdown', reply_markup=reply_markup ) ) ], edits=[ TelegramGeneralAction( message=tg.EditMessageText( text=work_text, parse_mode='Markdown', reply_markup=reply_markup ) ), TelegramGeneralAction( message=tg.EditMessageText( text=special_text, parse_mode='Markdown', reply_markup=reply_markup ) ), TelegramGeneralAction( message=tg.EditMessageText( text=self.data['summary'], parse_mode='Markdown', reply_markup=reply_markup ) ), TelegramGeneralAction( message=tg.EditMessageText( text='*{name}*\n{special}\n{residence}\n[{social}]({social})'.format(**self.data['basic']), parse_mode='Markdown', reply_markup=reply_markup ) ) ] ) ) if self.data.get('portfolio', False) and self.data['portfolio']: temp_element = [] for idx, portfolio in enumerate(self.data['portfolio'][:10]): temp_element.append( tg.CallbackButton( text=portfolio['title'], callback_data='VIEW_PORTFOLIO_%d' % idx ) ) caption = '*%s*\n%s' % (portfolio['title'], portfolio['sub_title']) if len(caption) > 200: caption = caption[:196] + '...' designer_brick.append( TelegramBrick( brick_type='callback', value='VIEW_PORTFOLIO_%d' % idx, actions=[ TelegramGeneralAction( message=tg.SendPhoto( photo=portfolio['image_url'], caption=caption, parse_mode='Markdown', reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.UrlButton( text='View', url=portfolio['url'] ) ], [ tg.CallbackButton( text='Prev', callback_data='VIEW_PORTFOLIO_%d' % (idx - 1) ), tg.CallbackButton( text='Next', callback_data='VIEW_PORTFOLIO_%d' % (idx + 1) ) ] ] ) ) ) # TelegramGeneralAction( # message=tg.SendPhoto( # photo=portfolio['image_url'] # ) # ), # TelegramGeneralAction( # message=tg.SendMessage( # text='*%s*\n%s' % (portfolio['title'], # portfolio['sub_title']), # parse_mode='Markdown', # reply_markup=tg.MarkUpContainer( # inline_keyboard=[ # [ # tg.UrlButton( # text='View', # url=portfolio['url'] # ) # ] # ] # ) # ) # ) ] ) ) temp_idx = 0 temp_len = len(temp_element) temp_array = [] for i in range(0, round(temp_len / 2)): temp_sub_array = [] for a in range(0, 2): if temp_idx == temp_len: break temp_sub_array.append(temp_element[temp_idx]) temp_idx += 1 temp_array.append(temp_sub_array) designer_brick.append( TelegramBrick( brick_type='callback', value='portfolio', actions=[ TelegramGeneralAction( message=tg.SendMessage( text='Portfolio', reply_markup=tg.MarkUpContainer( inline_keyboard=temp_array ) ) ) ] ) ) designer_brick.append( TelegramBrick( brick_type='bot_command', value='portfolio', actions=[ TelegramGeneralAction( message=tg.SendMessage( text='Portfolio', reply_markup=tg.MarkUpContainer( inline_keyboard=temp_array ) ) ) ] ) ) else: designer_brick.append( TelegramBrick( brick_type='callback', value='portfolio', actions=[ TelegramGeneralAction( message=tg.SendMessage( text='아직 Portfolio 항목을 입력하지 않았습니다.', ) ) ] ) ) designer_brick.append( TelegramBrick( brick_type='bot_command', value='portfolio', actions=[ TelegramGeneralAction( message=tg.SendMessage( text='아직 Portfolio 항목을 입력하지 않았습니다.', ) ) ] ) ) if self.data['basic'].get('email', False): designer_brick.append( TelegramBrick( brick_type='callback', value='contact', actions=[ TelegramGeneralAction( message=tg.SendMessage( text='자세한 문의는 아래의 메일보내기 버튼을 이용해주세요.', parse_mode='Markdown', reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='Send E-Mail', callback_data='send_email' ) ] ] ) ) ) ] ) ) designer_brick.append( TelegramBrick( brick_type='bot_command', value='contact', actions=[ TelegramGeneralAction( message=tg.SendMessage( text='자세한 문의는 아래의 메일보내기 버튼을 이용해주세요.', parse_mode='Markdown', reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='Send E-Mail', callback_data='send_email' ) ] ] ) ) ) ] ) ) else: designer_brick.append( TelegramBrick( brick_type='callback', value='contact', actions=[ TelegramGeneralAction( message=tg.SendMessage( text='이메일이 입력되어 있지 않습니다.', parse_mode='Markdown' ) ) ] ) ) designer_brick.append( TelegramBrick( brick_type='bot_command', value='contact', actions=[ TelegramGeneralAction( message=tg.SendMessage( text='이메일이 입력되어 있지 않습니다.', parse_mode='Markdown' ) ) ] ) ) designer_brick.append( TelegramBrick( brick_type='bot_command', value='send_email', actions=[ TelegramBrickAction( brick_id='mailerforset', data={ 'to': self.data['basic']['email'].strip() } ) ] ) ) designer_brick.append( TelegramBrick( brick_type='callback', value='send_email', actions=[ TelegramBrickAction( brick_id='mailerforset', data={ 'to': self.data['basic']['email'].strip() } ) ] ) ) return designer_brick
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage(text='외교부에서 제공하는 "여행경보 조회 서비스"에요.') ] 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/TravelWarningService/getTravelWarningList?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 = [ tg.SendMessage( text= 'chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [tg.SendMessage(text=UNKNOWN_ERROR_MSG)] else: if len(items) == 0: send_message = [ tg.SendMessage( text='조회된 결과가 없습니다.', reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='다른 국가검색', callback_data= 'BRICK|safe_journey|get_started') ]])) ] else: try: send_message = [ tg.SendPhoto( photo=download_and_save_image( items[0]['imgUrl2']), reply_markup=tg.MarkUpContainer( inline_keyboard=[[ tg.CallbackButton( text='다른 국가검색', callback_data= 'BRICK|safe_journey|get_started') ]])) ] except: send_message = [ tg.SendMessage(text='이미지 전송 중 오류가 발생했습니다.') ] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage( text='인천국제공항공사에서 제공하는 "출국장 대기인원 조회 서비스"에요.', reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton(text='제1여객터미널', callback_data='BRICK|icn|1'), tg.CallbackButton(text='제2여객터미널', callback_data='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 = [ tg.SendMessage( text= 'chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [tg.SendMessage(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 = [ tg.SendMessage( text=sending_message, parse_mode='Markdown', reply_markup=tg.MarkUpContainer(inline_keyboard=[ [ tg.CallbackButton( text='새로고침', callback_data='BRICK|icn|%s' % command) ], [ tg.CallbackButton( text='제%s여객터미널 조회' % the_other, callback_data='BRICK|icn|%s' % the_other) ] ])) ] await self.fb.send_messages(send_message) return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto( photo=BRICK_DEFAULT_IMAGE ), tg.SendMessage( text='국토교통부에서 제공하는 "열차조회 서비스"에요. 코레일/SRT 모두 조회 가능해요.', reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='열차 조회하기', callback_data='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 = [ tg.SendMessage( text='출발역이 조회할 수 없는 역입니다.', reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='다시 조회하기', callback_data='BRICK|train|show_data' ) ] ] ) ) ] elif STATION.get(destination_station) is None: send_message = [ tg.SendMessage( text='도착역이 조회할 수 없는 역입니다.', reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='다시 조회하기', callback_data='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 = [ tg.SendMessage( text='chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.', ) ] else: send_message = [ tg.SendMessage( text=UNKNOWN_ERROR_MSG ) ] else: if len(items) == 0: send_message = [ tg.SendMessage( text='조회된 결과가 없습니다.', reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='다시 조회하기', callback_data='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 = [ tg.SendMessage( text=result_message, parse_mode='Markdown', reply_markup=tg.MarkUpContainer( inline_keyboard=[ [ tg.CallbackButton( text='다시 조회하기', callback_data='BRICK|train|show_data' ) ] ] ) ) ] await self.brick_db.delete() await self.fb.send_messages(send_message) return None
async def telegram(self, command): if command == 'get_started': send_message = [ tg.SendPhoto(photo=BRICK_DEFAULT_IMAGE), tg.SendMessage( text='블루핵에서 제공하는 "메일보내기 서비스"예요.', reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='메일 보내기', callback_data='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( tg.SendMessage( text='메일보내기를 취소했습니다.', reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='메일 보내기', callback_data='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 = 'SendMessage|%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': 'telegram', 'api_code': 'mail', 'api_provider_code': 'chatbrick', 'origin': 'webhook_server', 'end': int(time.time() * 1000), 'remark': 'SMTP 통신으로 이메일 전송함' }) await self.fb.send_message( tg.SendMessage( text=result, reply_markup=tg.MarkUpContainer(inline_keyboard=[[ tg.CallbackButton( text='연속하여 메일보내기', callback_data='BRICK|mailer|show_data') ]]))) await self.brick_db.delete() return None