async def find_custom_brick(client, platform, brick_id, command, brick_data, msg_data, brick_config, log_id): if brick_config is not None: if brick_config.get(brick_id, False): brick_data['data'] = brick_config[brick_id] if BRICK_DEFAULT_CONFIG.get(brick_id, False): logger.info('기본 API Key로 변경') brick_default_data = BRICK_DEFAULT_CONFIG[brick_id] for key in brick_default_data.keys(): if brick_data['data'][key] == '': brick_data['data'][key] = brick_default_data[key] brick = BRICK.get(brick_id, False) if brick: if platform == 'facebook': user_id = msg_data['sender']['id'] fb = BrickFacebookAPIClient(fb=client, rep=Recipient(recipient_id=user_id), log_id=log_id, user_id=user_id) brick_input = BrickInputMessage(fb=fb, platform=platform, rep=fb.rep, brick_data=brick_data, log_id=log_id, user_id=user_id) if brick is SendEmail: email = SendEmail( receiver_email=brick_config['receiver_email'], title=brick_config['title']) return email.facebook(fb_token=client.access_token, psid=msg_data['sender']['id']) else: return await brick(fb=fb, brick_db=brick_input).facebook(command) elif platform == 'telegram': user_id = msg_data['from']['id'] tg = BrickTelegramAPIClient(tg=client, rep=user_id, log_id=log_id, user_id=user_id) brick_input = BrickInputMessage(fb=tg, platform=platform, rep=tg.rep, brick_data=brick_data, log_id=log_id, user_id=user_id) if brick_id == 'send_email': email = SendEmail( receiver_email=brick_config['receiver_email'], title=brick_config['title']) return email.telegram(sender=msg_data['from']) else: return await brick(fb=tg, brick_db=brick_input).telegram(command)
async def fb_message_poc(chat, fb, entry): try: for messaging in entry['messaging']: rep = Recipient(recipient_id=messaging['sender']['id']) if 'postback' in messaging: await find_brick(fb, chat, messaging, rep, 'postback', messaging['postback']['payload']) elif 'message' in messaging: if 'quick_reply' in messaging['message']: await find_brick(fb, chat, messaging, rep, 'postback', messaging['message']['quick_reply']['payload']) elif 'text' in messaging['message']: db = motor.motor_asyncio.AsyncIOMotorClient(os.environ['DB_CONFIG']).chatbrick text_input = await db.message_store.find_one({'id': rep.recipient_id, 'platform': 'facebook'}) if text_input: is_final = False final_store_idx = None store_len = len(text_input['store']) for idx, store in enumerate(text_input['store']): if store['value'] == '': logger.info(db.message_store.update_one({'_id': text_input['_id']}, { '$set': {'store.%d.value' % idx: messaging['message']['text']}})) logger.info(idx) logger.info(store_len) if (idx + 1) == store_len: is_final = True else: final_store_idx = idx + 1 logger.info(final_store_idx) break if is_final: messaging['command'] = 'final' await find_brick(fb, chat, messaging, rep, 'brick', text_input['brick_id']) else: await fb.send_message(RequestDataFormat(recipient=rep, message=text_input['store'][final_store_idx][ 'message'], message_type='RESPONSE')) else: await find_brick(fb, chat, messaging, rep, 'text', messaging['message']['text']) except Exception as e: traceback.print_exc() logger.error(e) logger.debug('에러 발생')
async def find_custom_brick(client, platform, brick_id, command, brick_data, msg_data): brick_config = brick_data.get('data', []) if platform == 'facebook': fb = BrickFacebookAPIClient(fb=client, rep=Recipient(recipient_id=msg_data['sender']['id'])) brick_input = BrickInputMessage(fb=fb, rep=fb.rep, brick_data=brick_data) if brick_id == 'send_email': email = SendEmail(receiver_email=brick_config['receiver_email'], title=brick_config['title']) return email.facebook(fb_token=client.access_token, psid=msg_data['sender']['id']) elif brick_id == 'mailer': mailer = Mailer( fb=fb, brick_db=brick_input ) return await mailer.facebook(command) elif platform == 'telegram': if brick_id == 'send_email': email = SendEmail(receiver_email=brick_config['receiver_email'], title=brick_config['title']) return email.telegram(sender=msg_data['from'])
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 fb_message_poc(chat, fb, entry): try: start = int(time.time() * 1000) log_id = 'FBSendMessage|%d' % start for messaging in entry['messaging']: rep = Recipient(recipient_id=messaging['sender']['id']) if 'postback' in messaging: await find_brick(fb, chat, messaging, rep, 'postback', messaging['postback']['payload'], log_id) elif 'message' in messaging: db = motor.motor_asyncio.AsyncIOMotorClient(os.environ['DB_CONFIG']).chatbrick text_input = await db.message_store.find_one({'id': rep.recipient_id, 'platform': 'facebook'}) is_not_find = True if 'quick_reply' in messaging['message']: await find_brick(fb, chat, messaging, rep, 'postback', messaging['message']['quick_reply']['payload'], log_id) elif 'text' in messaging['message']: logger.info('text_input') logger.info(text_input) if text_input: is_final = False final_store_idx = None is_go_on = False store_len = len(text_input['store']) for idx, store in enumerate(text_input['store']): logger.info(store) if store['value'] == '': if store.get('type', 'text') == 'text': is_not_find = False logger.info(db.message_store.update_one({'_id': text_input['_id']}, { '$set': {'store.%d.value' % idx: messaging['message']['text'].strip()}})) if store_len == 1 or ((idx + 1) == store_len): is_final = True else: final_store_idx = idx + 1 logger.info(final_store_idx) is_go_on = True break if is_go_on: if text_input['store'][final_store_idx]['value'] != '': is_final = True if is_final: messaging['command'] = 'final' await find_brick(fb, chat, messaging, rep, 'brick', text_input['brick_id'], log_id) elif is_go_on: if log_id is None: log_id = 'FBSendMessage|%d' % int(time.time() * 1000) await fb.send_message(RequestDataFormat(recipient=rep, message=text_input['store'][final_store_idx][ 'message'], message_type='RESPONSE')) log_id = save_a_log_to_server({ 'log_id': log_id, 'user_id': rep.recipient_id, 'os': '', 'application': 'facebook', 'task_code': detect_log_type(text_input['store'][final_store_idx]['message']), 'origin': 'webhook_server', 'end': int(time.time() * 1000), 'remark': '메시지 보냈습니다.' }) else: await find_brick(fb, chat, messaging, rep, 'text', messaging['message']['text'], log_id) elif 'attachments' in messaging['message']: for attachment in messaging['message']['attachments']: if attachment['type'] == 'image': logger.info('text_input') logger.info(text_input) if text_input: is_final = False final_store_idx = None is_go_on = False store_len = len(text_input['store']) logger.info(store_len) for idx, store in enumerate(text_input['store']): if store['value'] == '': if store.get('type', '') == 'image': logger.info(db.message_store.update_one({'_id': text_input['_id']}, { '$set': { 'store.%d.value' % idx: attachment['payload']['url'].strip()}})) logger.info(idx) logger.info(store_len) if store_len == 1 or ((idx + 1) == store_len): is_final = True else: final_store_idx = idx + 1 logger.info(final_store_idx) is_go_on = True break if is_final: messaging['command'] = 'final' await find_brick(fb, chat, messaging, rep, 'brick', text_input['brick_id'], log_id) elif is_go_on: if log_id is None: log_id = 'FBSendMessage|%d' % int(time.time() * 1000) await fb.send_message(RequestDataFormat(recipient=rep, message= text_input['store'][final_store_idx][ 'message'], message_type='RESPONSE')) log_id = save_a_log_to_server({ 'log_id': log_id, 'user_id': rep.recipient_id, 'os': '', 'application': 'facebook', 'task_code': detect_log_type(text_input['store'][final_store_idx]['message']), 'origin': 'webhook_server', 'end': int(time.time() * 1000), 'remark': '메시지 보냈습니다.' }) except Exception as e: traceback.print_exc() logger.error(e) logger.debug('에러 발생')
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))