def card_registration_confirm(sender, message, last_sender_message): message = message.replace('.', '') message = message.replace(' ', '') session = main.get_authorized_session( last_sender_message['encodedLoginPass']) phone = last_sender_message['mobileNumber'] token = last_sender_message['token'] url_confirmation = 'https://post.kz/mail-app/api/intervale/card/registration/confirm/' + token data = {'blockedAmount': message, 'phone': phone} r = session.post(url_confirmation, json=data) d = r.json() if d['state'] == 'confirmation': main.reply( sender, "Вы ввели неправильную сумму, осталось " + str(d['attempts']) + " попытки. Введите сумму ещё раз") return "wrongamount" if d['state'] == 'result': status = d['result']['status'] if status == 'success': res = "Поздравляю! Карта успешно добавлена!" main.reply(sender, res) if status == 'fail': main.reply(sender, "Карта не была добавлена. Попробуйте снова") main.reply_main_menu_buttons(sender, last_sender_message) return "ok"
def handle_messages_when_deactivated(sender, data, last_sender_message): try: sticker_id = data['entry'][0]['messaging'][0]['message']['sticker_id'] data_quick_replies = { "recipient": { "id": sender }, "message": { "text": "Вы хотите включить бота?", "quick_replies": [{ "content_type": "text", "title": "Да, включить бота", "payload": "activate.bot" }, { "content_type": "text", "title": "Нет", "payload": "deactivate.bot" }] } } requests.post(fb_url, json=data_quick_replies) return except: pass try: payload = data['entry'][0]['messaging'][0]['message']['quick_reply'][ 'payload'] if payload == 'activate.bot': last_sender_message['isBotActive'] = True main.mongo_update_record(last_sender_message) main.reply(sender, "Бот включен") main.reply_main_menu_buttons(sender, last_sender_message) if payload == 'deactivate.bot': main.reply( sender, "Хорошо! Если Вы хотите включить бота, нажмите кнопку (y)") except: return
def reply_addcard_startAdding(sender, message, last_sender_message): if not helper.check_csc(message): main.reply( sender, "Вы неправильно ввели трёхзначный код CSC/CVV2 на обратной стороне карты, введите заново" ) return "ok" main.reply(sender, "Идет обработка добавления карты...") main.reply_typing_on(sender) try: # 1 - авторизация на post.kz url_login = '******' headers = { "Authorization": "Basic " + last_sender_message['encodedLoginPass'], 'Content-Type': 'application/json' } # 2 - создаём токен session = requests.Session() r = session.get(url_login, headers=headers) mobileNumber = r.json()['mobileNumber'] # 3 - инициируем start registration url_login2 = 'https://post.kz/mail-app/api/intervale/token' data = {"phone": mobileNumber} r = session.post(url_login2, json=data) token = r.json()['token'] # 4 - передаём все данные карты для регистрации карты url_login3 = 'https://post.kz/mail-app/api/intervale/card/registration/start/' + token data = { "phone": mobileNumber, "returnUrl": "https://post.kz/static/return.html" } r = session.post(url_login3, json=data) # 4 - передаём все данные карты для регистрации карты url_login5 = 'https://openapi-entry.intervale.ru/api/v3/' + portal_id_2 + '/card/registration/' url_login5 += token + '/card-page-submit?fallback=https%3A%2F%2Fpost.kz%2Fstatic%2Freturn.html' data = { 'pan': last_sender_message['addcard_cardnumber'], 'expiry': last_sender_message['addcard_expiredate'], 'csc': message, 'cardholder': last_sender_message['addcard_cardowner'].lower(), 'pageType': 'reg' } r = session.post(url_login5, data=data) result = r.json() try: if result['error'] == 'ALREADY_REGISTERED': main.reply( sender, "Эта карта уже добавлена в вашем профиле на post.kz") main.reply_main_menu_buttons(sender, last_sender_message) return "ALREADY_REGISTERED" except: pass # 5 - дергаём статус, вытаскиваем url для 3DSecure url_login4 = 'https://post.kz/mail-app/api/intervale/card/registration/status/' + token data = {"phone": mobileNumber} r = session.post(url_login4, json=data) d = r.json() if d['state'] == 'redirect': main.reply_send_redirect_url(sender, d['url']) time.sleep(9) if d['state'] == 'confirmation': message = 'Для подтверждения карты, введите сумму, блокированную на вашей карте.\n' message += 'Блокированную сумму можно узнать через интернет-банкинг или call-центр вашего банка.\n' message += 'Осталось попыток: 3' main.reply(sender, message) last_sender_message['token'] = token last_sender_message['mobileNumber'] = mobileNumber last_sender_message['payload'] = 'addcard.confirmation' main.mongo_update_record(last_sender_message) return "confirmation" timer = 0 while timer < timeout: time.sleep(1) r = session.post(url_login4, json=data) d = r.json() if d['state'] == 'result': status = d['result']['status'] if status == 'success': res = "Поздравляю! Карта успешно добавлена!" main.reply(sender, res) if status == 'fail': main.reply(sender, "Карта не была добавлена. Попробуйте снова") main.reply_main_menu_buttons(sender, last_sender_message) return "ok" last_sender_message = main.mongo_get_by_sender(sender) if last_sender_message['payload'] == 'addcard.csc': strminutes = str(timeout // 60) main.reply( sender, "Прошло больше " + strminutes + " минут: добавление карты отменяется") main.reply_main_menu_buttons(sender, last_sender_message) return "time exceed" except: logging.error(helper.PrintException()) main.reply(sender, "Произошла непредвиденная ошибка, попробуйте позднее") main.reply_main_menu_buttons(sender, last_sender_message) return "fail"
def reply_card2card_startPayment(sender, message, last_sender_message): if not helper.check_csc(message): main.reply(sender, "Вы неправильно ввели трёхзначный код CSC/CVV2 на обратной стороне карты, введите заново") return "ok" main.reply(sender, "Идет обработка перевода...") main.reply_typing_on(sender) # 1 - авторизация на post.kz try: session = main.get_authorized_session(last_sender_message['encodedLoginPass']) mobileNumber = last_sender_message['mobileNumber'] # 2 - вызов getCards() url_login6 = 'https://post.kz/mail-app/api/intervale/card?device=mobile' sd2 = {"blockedAmount": "", "phone": mobileNumber, "paymentId": "", "returnUrl": "", "transferId": ""} r = session.post(url_login6, json=sd2) card = r.json()[last_sender_message['chosenCardIndex']] # 3 - вызов getToken() url_login4 = url + portal_id + '/token' headers = {'Content-Type': 'application/x-www-form-urlencoded', 'X-Channel-Id': x_channel_id, 'X-IV-Authorization': 'Identifier ' + mobileNumber} r = session.post(url_login4, headers=headers) token = r.json()['token'] # 4 - вызов startPayment() amount = last_sender_message['amount'] data = {'paymentId': 'MoneyTransfer_KazPost_Card2Card', 'currency': 'KZT', 'amount': str(amount) + '00', 'commission': str(last_sender_message['commission']) + '00', 'total': str(last_sender_message['total']) + '00', 'src.type': 'card_id', 'src.cardId': card['id'], 'src.csc': message, 'dst.type': 'card', 'dst.pan': last_sender_message['lastCardDst'], 'returnUrl': 'https://transfer.post.kz/?token=' + token} url_login5 = url + portal_id + '/payment/' + token + '/start' r = session.post(url_login5, data=data, headers=headers) # 5 - вызов statusPayment() url_login10 = url + portal_id + '/payment/' + token r = session.post(url_login10, headers=headers) data = r.json() state = data['state'] if state == 'redirect': main.reply_send_redirect_url(sender, data['url']) card_w_spaces = helper.insert_4_spaces(last_sender_message['lastCardDst']) timer = 0 while timer < timeout: time.sleep(1) r = session.post(url_login10, headers=headers) data = r.json() try: result_status = data['result']['status'] if result_status == 'fail': main.reply(sender, "Платеж не был завершен успешно. Попробуйте снова") elif result_status == 'success': res = "Поздравляю! Платеж был проведен успешно, карта " + card_w_spaces + " пополнена на сумму " + str( amount) + " тг.\n" res += "Номер квитанции: " + str(data['result']['trxId']) res += ", она доступна в профиле post.kz в разделе История платежей" main.reply(sender, res) main.reply_main_menu_buttons(sender, last_sender_message) return "ok" except: pass timer += 1 last_sender_message = main.mongo_get_by_sender(sender) if last_sender_message['payload'] == 'card2card.startPayment': strminutes = str(timeout // 60) main.reply(sender, "Прошло больше " + strminutes + " минут: платеж отменяется") main.reply_main_menu_buttons(sender, last_sender_message) return "time exceed" except: main.reply(sender, "Произошла непредвиденная ошибка, попробуйте позднее") main.reply_main_menu_buttons(sender, last_sender_message) logging.error(helper.PrintException()) return "fail"
def reply_mobile_startPayment(sender, message, last_sender_message): main.reply(sender, "Идет обработка платежа...") main.reply_typing_on(sender) # 1 - авторизация на post.kz try: url_login = '******' headers = {"Authorization": "Basic " + last_sender_message['encodedLoginPass'], 'Content-Type': 'application/json'} session = requests.Session() r = session.get(url_login, headers=headers) # 2 - вызов createSubscription() из PaymentAPI url_login2 = 'https://post.kz/mail-app/api/v2/subscriptions' login = last_sender_message['login'] operatorId = last_sender_message['mobileOperator'] phoneToRefill = last_sender_message['phoneToRefill'] amount = last_sender_message['amount'] sd2 = {"id": "", "login": login, "operatorId": operators_dict[operatorId], "data": phoneToRefill, "name": "", "invoiceIds": ""} r = session.post(url_login2, json=sd2) data = r.json() subscriptionId = str(data['subscriptionData']['id']) invoiceId = data['subscriptionData']['invoiceIds'][0] # 3 - вызов getInvoices() из PaymentAPI url_login3 = 'https://post.kz/mail-app/api/v2/subscriptions/' + subscriptionId + '/invoices' r = session.get(url_login3) body = r.json()['invoiceData'][0] # 4 - вызов getToken() url_login4 = 'https://post.kz/mail-app/api/intervale/token?device=mobile' mobileNumber = last_sender_message['mobileNumber'] sd2 = {"blockedAmount": "", "phone": mobileNumber, "paymentId": "", "returnUrl": "", "transferId": ""} r = session.post(url_login4, json=sd2) token = r.json()['token'] body['token'] = token body['invoiceId'] = invoiceId body['systemId'] = 'mobile' body['details'][0]['amount'] = amount body['details'][0]['commission'] = last_sender_message['commission'] # print ('#############################################') # print (body) # 5 - вызов createPayment() url_login5 = 'https://post.kz/mail-app/api/v2/payments/create?device=mobile' r = session.post(url_login5, json=body) payment_id = r.json()['paymentData']['id'] # print ('#############################################') # print (r.json()) # 6 - вызов getCards() url_login6 = 'https://post.kz/mail-app/api/intervale/card?device=mobile' sd2 = {"blockedAmount": "", "phone": mobileNumber, "paymentId": "", "returnUrl": "", "transferId": ""} r = session.post(url_login6, json=sd2) card = r.json()[last_sender_message['chosenCardIndex']] sd2 = {} sd2['phone'] = mobileNumber sd2['paymentId'] = payment_id sd2['cardId'] = card['id'] sd2['csc'] = message sd2['token'] = token sd2['returnUrl'] = 'https://post.kz/static/return.html' # 7 - вызов startPayment() url_login7 = 'https://post.kz/mail-app/api/intervale/payment/start/' + token + '?device=mobile' r = session.post(url_login7, json=sd2) # 8 - вызов statusPayment() url_login8 = 'https://post.kz/mail-app/api/intervale/payment/status/' + token + '?device=mobile' sd22 = {} sd22['phone'] = mobileNumber sd22['paymentId'] = payment_id r = session.post(url_login8, json=sd22) # 9 - вызов acceptPayment() url_login9 = 'https://post.kz/mail-app/api/intervale/payment/accept/' + token + '?device=mobile' r = session.post(url_login9, json=sd2) # 10 - вызов statusPayment() url_login10 = 'https://post.kz/mail-app/api/intervale/payment/status/' + token + '?device=mobile' r = session.post(url_login10, json=sd22) data = r.json() if data['state'] == 'redirect': main.reply_send_redirect_url(sender, data['url']) time.sleep(9) timer = 0 while timer < timeout: time.sleep(1) r = session.post(url_login10, json=sd22) data = r.json() if data['state'] == 'result': result_status = data['result']['status'] if result_status == 'fail': main.reply(sender, "Платеж не был завершен успешно. Попробуйте снова") elif result_status == 'success': res = "Поздравляю! Платеж был проведен успешно, номер " + phoneToRefill + " пополнен на сумму " + str( amount) + " тг.\n" res += "Номер квитанции: " + str(payment_id) res += ", она доступна в профиле post.kz в разделе История платежей" main.reply(sender, res) main.reply_main_menu_buttons(sender, last_sender_message) return "ok" timer += 1 last_sender_message = main.mongo_get_by_sender(sender) if last_sender_message['payload'] == 'mobile.startPayment': strminutes = str(timeout // 60) main.reply(sender, "Прошло больше " + strminutes + " минут: платеж отменяется") main.reply_main_menu_buttons(sender, last_sender_message) return "time exceed" except Exception: logging.error(helper.PrintException()) main.reply(sender, "Произошла непредвиденная ошибка, попробуйте позднее") main.reply_main_menu_buttons(sender, last_sender_message) return "fail"
def reply_astanaErc_startPayment(sender, message, last_sender_message): if not helper.check_csc(message): main.reply( sender, "Вы неправильно ввели трёхзначный код CSC/CVV2 на обратной стороне карты, введите заново" ) return "ok" main.reply(sender, "Идет обработка платежа...") main.reply_typing_on(sender) # 1 - авторизация на post.kz try: session = main.get_authorized_session( last_sender_message['encodedLoginPass']) mobileNumber = last_sender_message['mobileNumber'] token = main.get_token_postkz(session, mobileNumber) invoiceData = get_komuslugi_invoice(last_sender_message) invoiceData['systemId'] = 'POSTKZ' invoiceData['token'] = token invoiceData['invoiceId'] = invoiceData['id'] c = 0 for i in invoiceData['details']: invoiceData['details'][c]['amount'] = math.ceil( invoiceData['details'][c]['amount']) c += 1 # 5 - createPayment url_login5 = 'https://post.kz/mail-app/api/v2/payments/create' r = session.post(url_login5, json=invoiceData) payment_id = r.json()['paymentData']['id'] # 6 - вызов getCards() url_login6 = 'https://post.kz/mail-app/api/intervale/card?device=mobile' sd2 = { "blockedAmount": "", "phone": mobileNumber, "paymentId": "", "returnUrl": "", "transferId": "" } r = session.post(url_login6, json=sd2) card = r.json()[last_sender_message['chosenCardIndex']] sd2 = {} sd2['phone'] = mobileNumber sd2['paymentId'] = payment_id sd2['cardId'] = card['id'] sd2['csc'] = message sd2['token'] = token sd2['returnUrl'] = 'https://post.kz/static/return.html' # 7 - вызов startPayment() url_login7 = 'https://post.kz/mail-app/api/intervale/payment/start/' + token r = session.post(url_login7, json=sd2) # 8 - вызов statusPayment() url_login8 = 'https://post.kz/mail-app/api/intervale/payment/status/' + token sd22 = {} sd22['phone'] = mobileNumber sd22['paymentId'] = payment_id r = session.post(url_login8, json=sd22) # 9 - вызов acceptPayment() url_login9 = 'https://post.kz/mail-app/api/intervale/payment/accept/' + token r = session.post(url_login9, json=sd2) # 10 - вызов statusPayment() url_login10 = 'https://post.kz/mail-app/api/intervale/payment/status/' + token r = session.post(url_login10, json=sd22) data = r.json() if data['state'] == 'redirect': main.reply_send_redirect_url(sender, data['url']) time.sleep(5) timer = 0 while timer < main.timeout: time.sleep(1) r = session.post(url_login10, json=sd22) data = r.json() if data['state'] == 'result': result_status = data['result']['status'] if result_status == 'fail': main.reply( sender, "Платеж не был завершен успешно. Попробуйте снова") elif result_status == 'success': res = "Поздравляю! Платеж был проведен успешно, квитанция счёта Астана ЕРЦ " + \ last_sender_message['astanaErc_last_acc'] + " оплачена на сумму " + str(amount) + " тг.\n" res += "Номер квитанции: " + str(payment_id) res += ", она доступна на post.kz в разделе История платежей" main.reply(sender, res) last_sender_message['payload'] = 'astanaErc.finished' main.mongo_update_record(last_sender_message) main.reply_typing_off(sender) main.reply_main_menu_buttons(sender) return "ok" timer += 1 last_sender_message = main.mongo_get_by_sender(sender) if last_sender_message['payload'] == 'astanaErc.startPayment': strminutes = str(main.timeout // 60) main.reply( sender, "Прошло больше " + strminutes + " минут: платеж отменяется") main.reply_typing_off(sender) main.reply_main_menu_buttons(sender) last_sender_message['payload'] = 'mainMenu' main.mongo_update_record(last_sender_message) return "time exceed" except Exception as e: main.reply(sender, "Произошла непредвиденная ошибка, попробуйте позднее") main.reply_typing_off(sender) main.reply_main_menu_buttons(sender) logging.error(helper.PrintException()) return "fail"
def handle_intent(sender, last_sender_message, value): try: if value == 'greeting': message = "Здравствуйте, " + last_sender_message[ 'first_name'] + "!\n" message += "Меня зовут Е-Сау+ле, я голосовая помощница этого бота." main.reply_just_text(sender, message.replace('+', '')) main.send_voice(sender, message) elif value == 'postamat': main.reply(sender, helper.postamat) elif value == 'hybridpost_def': main.reply(sender, helper.hybridpost_def) elif value == 'supermarket': main.reply(sender, helper.what_is_supermarket) elif value == 'trackbynumber_query': main.reply(sender, helper.trackbynumber_query) elif value == 'fastmail_options': main.reply(sender, helper.fastmail_options) elif value == 'postamat_how': main.reply(sender, helper.postamat_how) elif value == 'hybridpost_time': main.reply(sender, helper.hybridpost_time) elif value == 'postamat_info_access': main.reply(sender, helper.postamat_info_access) elif value == 'hybridpost_info': main.reply(sender, helper.hybridpost_info) elif value == 'trackbynumber': main.reply(sender, helper.trackbynumber) elif value == 'redirect': main.reply(sender, helper.redirect) elif value == 'redirect_why': main.reply(sender, helper.redirect_why) elif value == 'package_how_long': main.reply(sender, helper.package_how_long) elif value == 'COMMAND_exchange_rates': main.reply_currencies_kursy(sender) elif value == 'COMMAND_go_home': main.reply_main_menu_buttons(sender, last_sender_message) elif value == 'COMMAND_card2card': card2card.reply_card2card_enter_cardDst(sender, last_sender_message) elif value == 'COMMAND_paymobile': mobile.reply_mobile_enter_number(sender, last_sender_message) elif value == 'COMMAND_payonai': bot_server.call_onai(sender, last_sender_message, 'onai') elif value == 'COMMAND_sendmessage': bot_server.call_sendmessage(sender, last_sender_message, 'send.message') elif value == 'COMMAND_my_cards': bot_server.call_addcard(sender, last_sender_message, 'addcard') elif value == 'COMMAND_nearest': main.reply_nearest(sender) elif value == 'COMMANDS_nearest_postamat' or value == 'find_postamat': bot_server.call_request_nearest_location(sender, last_sender_message, 'nearest.postamats') elif value == 'COMMANDS_nearest_office' or value == 'find_dep': bot_server.call_request_nearest_location(sender, last_sender_message, 'nearest.offices') elif value == 'COMMANDS_nearest_atm': bot_server.call_request_nearest_location(sender, last_sender_message, 'nearest.atms') elif value == 'COMMAND_nearest': main.reply_nearest(sender) elif value == 'COMMAND_disable_bot': bot_server.call_disable_bot(sender, last_sender_message, 'disable.bot') elif value == 'COMMAND_track': tracking.reply_tracking_enter_number(sender, last_sender_message) elif value == 'penalties_pdd' or value == 'COMMAND_penalties': shtrafy.reply_pdd_shtrafy(sender) elif value == 'info_post': tracking.reply_tracking_enter_number(sender, last_sender_message) elif value == 'how_are_you': main.reply(sender, "У меня всё замечательно!") elif value == 'FUN_anekdot': r = feedparser.parse('http://anekdotme.ru/RSS') random_int = randint(0, len(r['entries']) - 1) anekdot = r['entries'][random_int]['summary_detail']['value'] anekdot = anekdot.replace('<br />', '\n').replace('—', '').replace( '<BR>', '').replace('<br>', '') logging.info("Anekdot = " + anekdot) main.reply(sender, anekdot) elif value == 'thanx': main.reply( sender, "Всегда рада Вам служить, " + last_sender_message['first_name'] + "!") else: main.reply(sender, "Я не поняла Вашу команду") except: logging.error(helper.PrintException())
def handle_sticker(sender, last_sender_message): main.reply_main_menu_buttons(sender, last_sender_message)
def handle_text_messages(sender, last_sender_message, message): if message == '👍': main.reply_main_menu_buttons(sender, last_sender_message) return "ok" payload = last_sender_message['payload'] if payload == 'tracking': tracking.reply_tracking(sender, message, last_sender_message) return "ok" elif payload == '4.IIN': shtrafy.reply_pdd_shtrafy_iin(sender, message, last_sender_message) return "ok" elif payload == '4.GosNomer': shtrafy.reply_pdd_shtrafy_gosnomer(sender, message, last_sender_message) return "ok" elif payload == 'astanaErc.enter': komuslugi.reply_astanaErc(sender, message, last_sender_message) return "ok" elif payload == 'astanaErc.startPayment': t = threading.Thread(target=komuslugi.reply_astanaErc_startPayment, args=( sender, message, last_sender_message, )) t.setDaemon(True) t.start() return "ok" elif payload == 'auth': main.reply_auth(sender, message, last_sender_message) return "ok" elif payload == 'balance': mobile.reply_mobile_check_number(sender, message, last_sender_message) return "ok" elif payload == 'card2cash.show': card2cash.reply_card2cash_history_startPayment(sender, message, last_sender_message) return "ok" elif payload == 'card2card': card2card.reply_card2card_check_cardDst(sender, message, last_sender_message) return "ok" elif payload == 'card2card.amount': card2card.reply_card2card_amount(sender, message, last_sender_message) return "ok" elif payload == 'card2card.chooseCard': main.reply_display_cards(sender, last_sender_message) return "ok" elif payload == 'mobile.amount': mobile.reply_mobile_amount(sender, message, last_sender_message) return "ok" elif payload == 'mobile.chooseCard': main.reply_display_cards(sender, last_sender_message) return "ok" elif payload == 'mobile.startPayment': t = threading.Thread(target=mobile.reply_mobile_startPayment, args=( sender, message, last_sender_message, )) t.setDaemon(True) t.start() return "ok" elif payload == 'mobile.finished' or payload == 'onai.finished': return "ok" elif payload == 'onai': onai.reply_onai(sender, message, last_sender_message) return "ok" elif payload == 'onai.amount': onai.reply_onai_amount(sender, message, last_sender_message) return "ok" elif payload == 'onai.startPayment': t = threading.Thread(target=onai.reply_onai_startPayment, args=( sender, message, last_sender_message, )) t.setDaemon(True) t.start() return "ok" elif payload == 'card2card.startPayment': t = threading.Thread(target=card2card.reply_card2card_startPayment, args=( sender, message, last_sender_message, )) t.setDaemon(True) t.start() return "ok" elif payload == 'addcard': addcard.reply_addcard_checkcard(sender, message, last_sender_message) return "ok" elif payload == 'addcard.expiredate': addcard.reply_addcard_checkexpiredate(sender, message, last_sender_message) return "ok" elif payload == 'addcard.cardowner': addcard.reply_addcard_checkcardowner(sender, message, last_sender_message) return "ok" elif payload == 'addcard.confirmation': addcard.card_registration_confirm(sender, message, last_sender_message) return "ok" elif payload == 'addcard.csc': t = threading.Thread(target=addcard.reply_addcard_startAdding, args=( sender, message, last_sender_message, )) t.setDaemon(True) t.start() return "ok" elif payload == 'astanaErc.startPayment': t = threading.Thread(target=komuslugi.reply_astanaErc_startPayment, args=( sender, message, last_sender_message, )) t.setDaemon(True) t.start() return "ok" elif payload == 'send.message': res = "Спасибо, Ваше сообщение принято! Ожидайте ответа от операторов\n" res += "Сейчас бот отключен. Чтобы включить, нажмите кнопку (y)" last_sender_message['isBotActive'] = False main.reply(sender, res) return "ok" main.reply_main_menu_buttons(sender, last_sender_message)
def handle_postback_payload(sender, last_sender_message, payload): if last_sender_message['payload'] == 'card2cash': card2cash.reply_card2cash_history_show(sender, last_sender_message, payload) last_sender_message['payload'] = 'card2cash.show' main.mongo_update_record(last_sender_message) return "ok" if payload == 'GET_STARTED_PAYLOAD': reply_intro(sender) return "ok" elif payload == 'tracking': tracking.reply_tracking_enter_number(sender, last_sender_message) return "ok" elif payload == 'shtrafy': shtrafy.reply_pdd_shtrafy(sender) elif payload == 'komuslugi': komuslugi.reply_komuslugi_cities(sender) elif payload == 'astanaErc': komuslugi.reply_astanaErc_enter(sender, last_sender_message) return "ok" elif payload == 'nearest': main.reply_nearest(sender) elif payload == 'nearest.postamats' or payload == 'nearest.offices' or payload == 'nearest.atms': call_request_nearest_location(sender, last_sender_message, payload) return "ok" elif payload == 'balance': mobile.reply_mobile_enter_number(sender, last_sender_message) return "ok" elif payload == 'card2card': card2card.reply_card2card_enter_cardDst(sender, last_sender_message) return "ok" elif payload == 'card2cash': card2cash.reply_card2cash_history(sender, last_sender_message) return "ok" elif payload == '10.kursy': main.reply_currencies_kursy(sender) elif payload == 'misc': main.reply_misc(sender) elif payload == 'menu.finances': main.reply_menu_finances(sender, last_sender_message) return "ok" elif payload == 'mainMenu': main.reply_main_menu_buttons(sender, last_sender_message) return "ok" elif payload == 'onai': if not call_onai(sender, last_sender_message, payload): return "ok" elif payload == 'auth': try: encodedLoginPass = last_sender_message['encodedLoginPass'] assert encodedLoginPass != None answer = "Вы уже авторизованы под логином " + last_sender_message[ 'login'] + ".\n" answer += "Вы можете переотправить логин и пароль профиля на post.kz через пробел для новой авторизации\n" answer += hint_main_menu main.reply(sender, answer) except: main.reply( sender, "Для авторизации отправьте логин и пароль профиля на post.kz через пробел. " "Если у вас нет аккаунта то зарегистрируйтесь в https://post.kz/register" ) elif payload in digits: last_sender_message['chosenCardIndex'] = int(payload) lastCommand = last_sender_message['lastCommand'] if lastCommand == 'balance': mobile.reply_mobile_csc(sender, payload, last_sender_message) payload = 'mobile.startPayment' elif lastCommand == 'onai': onai.reply_onai_csc(sender, payload, last_sender_message) payload = 'onai.startPayment' elif lastCommand == 'card2card': card2card.reply_card2card_csc(sender, payload, last_sender_message) payload = 'card2card.startPayment' elif lastCommand == 'astanaErc': komuslugi.reply_astanaErc_csc(sender, payload, last_sender_message) payload = 'astanaErc.startPayment' elif payload == 'auth.delete': try: assert last_sender_message['encodedLoginPass'] != None main.reply_auth_delete(sender) except: main.reply(sender, "Авторизации нет") elif payload == 'addcard': if not call_addcard(sender, last_sender_message, payload): return "ok" elif payload == 'disable.bot': call_disable_bot(sender, last_sender_message, payload) return "ok" elif payload == 'send.message': call_sendmessage(sender, last_sender_message, payload) return "ok" else: logging.info("Ne raspoznana komanda") last_sender_message['payload'] = payload main.mongo_update_record(last_sender_message)
def handle_quickreply_payload(sender, data, last_sender_message, payload): text = data['entry'][0]['messaging'][0]['message']['text'] if payload == '4.IIN': shtrafy.reply_pdd_shtrafy_iin_enter(sender, last_sender_message) return "ok" if payload == 'pddIIN.last': shtrafy.reply_pdd_shtrafy_iin(sender, text, last_sender_message) return "ok" if payload == 'pddIIN.delete': shtrafy.reply_pdd_shtrafy_iin_delete(sender, last_sender_message) return "ok" if payload == 'pddIIN.delete.number': shtrafy.reply_pdd_shtrafy_iin_delete_iin(sender, text, last_sender_message) return "ok" elif payload == '4.GosNomer': shtrafy.reply_pdd_shtrafy_gosnomer_enter(sender, last_sender_message) return "ok" elif payload == 'pddGosnomer.last': shtrafy.reply_pdd_shtrafy_gosnomer(sender, text, last_sender_message) return "ok" elif payload == 'pddGosnomer.delete': shtrafy.reply_pdd_shtrafy_gosnomer_delete(sender, last_sender_message) return "ok" elif payload == 'pddGosnomer.delete.number': shtrafy.reply_pdd_shtrafy_gosnomer_delete_gosnomer( sender, text, last_sender_message) return "ok" elif payload == 'astanaErc.last': komuslugi.reply_astanaErc(sender, text, last_sender_message) return "ok" elif payload == 'astanaErc.delete': komuslugi.reply_astanaErc_delete(sender, last_sender_message) return "ok" elif payload == 'astanaErc.delete.acc': komuslugi.reply_astanaErc_delete_acc(sender, text, last_sender_message) return "ok" elif payload == 'astanaErc.pay': komuslugi.reply_astanaErc_chooseCard(sender, last_sender_message) return "ok" elif payload == 'tracking.last': tracking.reply_tracking(sender, text, last_sender_message) payload = 'tracking' elif payload == 'tracking.delete': tracking.reply_tracking_delete(sender, last_sender_message) elif payload == 'tracking.delete.number': tracking.reply_tracking_delete_number(sender, text, last_sender_message) payload = 'tracking' elif payload == 'onai.last': onai.reply_onai(sender, text, last_sender_message) payload = 'onai.amount' elif payload == 'onai.again': last_sender_message['onaisToRefill'].remove( last_sender_message['onaiToRefill']) onai.reply_onai_enter_number(sender, last_sender_message) return "ok" elif payload == 'onai.delete': onai.reply_onai_delete(sender, last_sender_message) return "ok" elif payload == 'onai.delete.phone': onai.reply_onai_delete_phone(sender, text, last_sender_message) return "ok" elif payload == 'mobile.last': mobile.reply_mobile_check_number(sender, text, last_sender_message) return "ok" elif payload == 'mobile.voice_number.again': mobile.reply_mobile_enter_number(sender, last_sender_message) return "ok" elif payload == 'mobile.delete': mobile.reply_mobile_delete(sender, last_sender_message) return "ok" elif payload == 'mobile.delete.phone': mobile.reply_mobile_delete_phone(sender, text, last_sender_message) return "ok" elif payload == 'card2card.last': card2card.reply_card2card_check_cardDst(sender, text, last_sender_message) payload = 'card2card.amount' elif payload == 'card2card.delete': card2card.reply_card2card_delete(sender, last_sender_message) elif payload == 'card2card.again': last_sender_message['cardDsts'].remove( last_sender_message['lastCardDst']) card2card.reply_card2card_enter_cardDst(sender, last_sender_message) return "ok" elif payload == 'card2card.delete.card': card2card.reply_card2card_delete_card(sender, text, last_sender_message) return "ok" elif payload == 'card2card.info': main.reply_just_text(sender, card2card.card2card_info) card2card.reply_card2card_enter_cardDst(sender, last_sender_message) return elif payload == 'auth.delete.yes': last_sender_message['encodedLoginPass'] = None main.reply(sender, "Авторизация успешна удалена") main.reply_main_menu_buttons(sender, last_sender_message) return elif payload == 'auth.delete.no': main.reply_main_menu_buttons(sender, last_sender_message) elif payload == 'disable.bot.yes': res = "Бот отключен. Чтобы включить, нажмите кнопку (y)" last_sender_message['isBotActive'] = False main.reply(sender, res) elif payload == 'disable.bot.no': main.reply(sender, "Бот остался включенным") main.reply_main_menu_buttons(sender, last_sender_message) last_sender_message['payload'] = payload main.mongo_update_record(last_sender_message)
def reply_onai_startPayment(sender, message, last_sender_message): if not helper.check_csc(message): main.reply(sender, "Вы неправильно ввели трёхзначный код CSC/CVV2 на обратной стороне карты, введите заново") return "ok" main.reply(sender, "Идет обработка платежа...") main.reply_typing_on(sender) # 1 - авторизация на post.kz try: session = main.get_authorized_session(last_sender_message['encodedLoginPass']) # 2 - вызов createSubscription() из PaymentAPI url_login2 = 'https://post.kz/mail-app/api/v2/subscriptions' login = last_sender_message['login'] operatorId = 'onai' onaiToRefill = last_sender_message['onaiToRefill'] amount = last_sender_message['amount'] sd2 = {"id": "", "login": login, "operatorId": operatorId, "data": onaiToRefill, "name": "", "invoiceIds": ""} r = session.post(url_login2, json=sd2) data = r.json() subscriptionId = str(data['subscriptionData']['id']) invoiceId = data['subscriptionData']['invoiceIds'][0] # 3 - вызов getInvoices() из PaymentAPI url_login3 = 'https://post.kz/mail-app/api/v2/subscriptions/' + subscriptionId + '/invoices' r = session.get(url_login3) body = r.json()['invoiceData'][0] # 4 - вызов getToken() mobileNumber = last_sender_message['mobileNumber'] token = main.get_token_postkz(session, mobileNumber) body['token'] = token body['invoiceId'] = invoiceId body['systemId'] = 'POSTKZ' body['details'][0]['amount'] = amount body['details'][0]['commission'] = 0 # 5 - вызов createPayment() url_login5 = 'https://post.kz/mail-app/api/v2/payments/create' r = session.post(url_login5, json=body) payment_id = r.json()['paymentData']['id'] # 6 - вызов getCards() url_login6 = 'https://post.kz/mail-app/api/intervale/card?device=mobile' sd2 = {"blockedAmount": "", "phone": mobileNumber, "paymentId": "", "returnUrl": "", "transferId": ""} r = session.post(url_login6, json=sd2) card = r.json()[last_sender_message['chosenCardIndex']] sd2 = {} sd2['phone'] = mobileNumber sd2['paymentId'] = payment_id sd2['cardId'] = card['id'] sd2['csc'] = message sd2['token'] = token sd2['returnUrl'] = 'https://post.kz/static/return.html' # 7 - вызов startPayment() url_login7 = 'https://post.kz/mail-app/api/intervale/payment/start/' + token r = session.post(url_login7, json=sd2) # 8 - вызов statusPayment() url_login8 = 'https://post.kz/mail-app/api/intervale/payment/status/' + token sd22 = {} sd22['phone'] = mobileNumber sd22['paymentId'] = payment_id r = session.post(url_login8, json=sd22) # 9 - вызов acceptPayment() url_login9 = 'https://post.kz/mail-app/api/intervale/payment/accept/' + token r = session.post(url_login9, json=sd2) # 10 - вызов statusPayment() url_login10 = 'https://post.kz/mail-app/api/intervale/payment/status/' + token r = session.post(url_login10, json=sd22) data = r.json() if data['state'] == 'redirect': main.reply_send_redirect_url(sender, data['url']) time.sleep(5) timer = 0 while timer < timeout: time.sleep(1) r = session.post(url_login10, json=sd22) data = r.json() if data['state'] == 'result': result_status = data['result']['status'] if result_status == 'fail': main.reply(sender, "Платеж не был завершен успешно. Попробуйте снова") elif result_status == 'success': res = "Поздравляю! Платеж был проведен успешно, карта Онай " + onaiToRefill + " пополнена на сумму " + str( amount) + " тг.\n" res += "Номер квитанции: " + str(payment_id) res += ", она доступна на post.kz в разделе История платежей" main.reply(sender, res) main.reply_main_menu_buttons(sender, last_sender_message) return "ok" timer += 1 last_sender_message = main.mongo_get_by_sender(sender) if last_sender_message['payload'] == 'onai.startPayment': strminutes = str(timeout // 60) main.reply(sender, "Прошло больше " + strminutes + " минут: платеж отменяется") main.reply_main_menu_buttons(sender, last_sender_message) return "time exceed" except: main.reply(sender, "Произошла непредвиденная ошибка, попробуйте позднее") main.reply_main_menu_buttons(sender, last_sender_message) logging.error(helper.PrintException()) return "fail"
def reply_card2cash_history_startPayment(sender, message, last_sender_message): if not helper.check_csc(message): main.reply( sender, "Вы неправильно ввели трёхзначный код CSC/CVV2 на обратной стороне карты, введите заново" ) return "ok" main.reply(sender, "Идёт обработка перевода, подождите 1-2 минуты...") main.reply_typing_on(sender) try: token = last_sender_message['card2cash_token'] session = requests.Session() headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Channel-Id': x_channel_id, 'X-IV-Authorization': 'Identifier ' + last_sender_message['mobileNumber'] } url_token_show = url + portal_id + '/payment/' + token r = session.get(url_token_show, headers=headers) data = r.json() url_token = url + portal_id + '/token' r = session.post(url_token, headers=headers) new_token = r.json()['token'] data1 = { 'paymentId': "MoneyTransfer_KazPost_Card2Cash", 'returnUrl': 'https://post.kz/static/return.html', 'src.type': 'card_id', 'src.cardholder': 'NAME', 'src.cardId': data['src']['cardId'], 'src.csc': message, 'src.addToProfile': 'true', 'amount': str(data['amount']), 'commission': str(data['commission']), 'total': str(data['amount'] + data['commission']), 'currency': data['currency'], 'params.transfType': data['params']['transfType'], 'params.transfPurpose': data['params']['transfPurpose'], 'params.cliResident': data['params']['cliResident'], 'params.cliTaxcode': data['params']['cliTaxcode'], 'params.cliLastname': data['params']['cliLastname'], 'params.cliName': data['params']['cliName'], 'params.cliAddr': data['params']['cliAddr'], 'params.cliPhone': data['params']['cliPhone'], 'params.passportType': data['params']['passportType'], 'params.passportNum': data['params']['passportNum'], 'params.passportDate': data['params']['passportDate'], 'params.passportOrg': data['params']['passportOrg'], 'params.rcpnLastname': data['params']['rcpnLastname'], 'params.rcpnName': data['params']['rcpnName'], 'params.rcpnAddr': data['params']['rcpnAddr'], 'params.rcpnPhone': data['params']['rcpnPhone'], 'params.codeWord': data['params']['codeWord'], } url_start = url + portal_id + '/payment/' + new_token + '/start' requests.post(url_start, data1, headers=headers) url_status = url + portal_id + '/payment/' + new_token timer = 0 urlSent = False main.reply_typing_on(sender) while timer < timeout: if urlSent: time.sleep(1) r = session.post(url_status, headers=headers).json() if r['state'] == 'redirect' and not urlSent: main.reply_send_redirect_url(sender, r['url']) urlSent = True if r['state'] == 'result': if r['result']['status'] == 'fail': main.reply( sender, "Перевод не был завершен успешно. Попробуйте снова") if r['result']['status'] == 'suspended': main.reply( sender, "Возникла проблема на стороне банка, перевод не был осуществлён. Попробуйте позже" ) if r['result']['status'] == 'success': res = "Поздравляю! Перевод был проведен успешно!" res += "\nВнимание! Сообщите контрольный номер перевода и кодовое слово получателю перевода" res += "\nКонтрольный номер перевода: " + r['result'][ 'transferCode'] res += "\nКонтрольное слово: " + data['params']['codeWord'] main.reply(sender, res) main.reply_main_menu_buttons(sender, last_sender_message) return timer += 1 last_sender_message = main.mongo_get_by_sender(sender) if last_sender_message['payload'] == 'card2cash.show': strminutes = str(timeout // 60) main.reply( sender, "Прошло больше " + strminutes + " минут: перевод отменяется") main.reply_main_menu_buttons(sender, last_sender_message) return "time exceed" except: main.reply(sender, "Произошла непредвиденная ошибка, попробуйте позднее") logging.error(helper.PrintException())