def get_yandex_balance(): yandex_money_token = get_config_var('YandexMoneyToken') if not yandex_money_token: return False wallet = Wallet(yandex_money_token) account_info = wallet.account_info() return account_info['balance']
def account_info(message, con): cur = con.cursor() cur.execute('SELECT token FROM `users` WHERE cid=' + str(message.from_user.id)) con.commit() sql_result = cur.fetchall() if sql_result: token = sql_result[0][0] else: # no user in DB return 'Для продолжения перейдите по <a href="http://95.163.114.6/?cid=' + str(message.from_user.id) + '&b=1">ссылке</a>' wallet = Wallet(token) return wallet.account_info()['balance_details']['available']
def account_info(message, con): cur = con.cursor() cur.execute('SELECT token FROM `users` WHERE cid=' + str(message.from_user.id)) con.commit() sql_result = cur.fetchall() if sql_result: token = sql_result[0][0] else: # no user in DB return 'Для продолжения перейдите по <a href="http://95.163.114.6/?cid=' + str( message.from_user.id) + '&b=1">ссылке</a>' wallet = Wallet(token) return wallet.account_info()['balance_details']['available']
def get_yandex_wallet_history(): wallet, c = Wallets.objects.get_or_create(name='Yandex Money') yandex_uw = UserWallet.objects.filter(wallet=wallet) if len(yandex_uw) > 0: for uw in yandex_uw: access_token = uw.access_token if access_token is not None: yandex_wallet_object = Wallet(access_token) account_info = yandex_wallet_object.account_info() uw.balance = account_info['balance'] uw.total_btc = get_btc_value('rur', account_info['balance']) uw.total_usd = get_usd_value('rur', account_info['balance']) uw.save() get_yandex_records(wallet=yandex_wallet_object, uw=uw) print('ok') else: print("Кошельки отсутствуют") return True
def wallet(request): if request.method == 'POST': wallet = Wallets.objects.get(pk=request.POST.get('wallet')) if wallet.name == 'Yandex Money': if not settings.YANDEX_MONEY_CLIENT_ID or not settings.YANDEX_MONEY_REDIRECT_URI or not \ settings.YANDEX_MONEY_CLIENT_SECRET: return HttpResponse('You must define yandex money settings', status=404) scope = ['account-info', 'operation-history', 'operation-details'] auth_url = Wallet.build_obtain_token_url( client_id=settings.YANDEX_MONEY_CLIENT_ID, redirect_uri=settings.YANDEX_MONEY_REDIRECT_URI, scope=scope) + '&response_type=code' return redirect(auth_url) else: uw = UserWallet() uw.user = request.user uw.address = request.POST.get('address') uw.wallet = wallet uw.save() elif request.method == 'GET': if not settings.YANDEX_MONEY_CLIENT_ID or not settings.YANDEX_MONEY_REDIRECT_URI or not \ settings.YANDEX_MONEY_CLIENT_SECRET: return HttpResponse('You must define yandex money settings', status=404) access_token = Wallet.get_access_token( client_id=settings.YANDEX_MONEY_CLIENT_ID, redirect_uri=settings.YANDEX_MONEY_REDIRECT_URI, code=request.GET.get('code'), client_secret=settings.YANDEX_MONEY_CLIENT_SECRET) access_token = access_token['access_token'] wallet = Wallet(access_token) account_info = wallet.account_info() uw = UserWallet() uw.wallet = Wallets.objects.get(name='Yandex Money') uw.access_token = access_token uw.user = request.user uw.address = account_info['account'] uw.balance = account_info['balance'] uw.save() return redirect(index)
def do_GET(self): #DB connection con = sqlite3.connect('/home/user/bot/users.sqlite') cur = con.cursor() p = urlparse(self.path) q = parse_qs(p.query) self.send_response(302, 'Found') if 'cid' in q: scope = ['account-info', 'operation-history', 'payment-p2p'] auth_url = Wallet.build_obtain_token_url(config.client_id, config.redirect_uri, scope) self.send_header('Location', auth_url) if 'b' in q: self.send_header("Set-Cookie", "cid=" + q['cid'][0] + '&b=1') else: self.send_header("Set-Cookie", "cid=" + q['cid'][0] + '&to=' + q['to'][0] + '&amount=' + q['amount'][0]) elif 'code' in q: access_token = Wallet.get_access_token(config.client_id, q['code'][0], config.redirect_uri, client_secret=None) cookie = parse_qs(self.headers.get('Cookie')) cid = cookie['cid'][0] cur.execute('INSERT INTO users (cid, token) VALUES ("' + str(cid) +'", "' + access_token['access_token'] + '")') con.commit() wallet = Wallet(access_token['access_token']) if 'b' in cookie: queue.put({'cid': cid, 'b': wallet.account_info()['balance_details']['available']}) else: to = cookie['to'][0] amount = cookie['amount'][0] request_options = {"pattern_id": "p2p", "to": to, "amount_due": amount, "comment": "переведено через бота", "message": "переведено через бота", "label": "testPayment"} request_result = wallet.request_payment(request_options) # check status process_payment = wallet.process_payment({"request_id": request_result['request_id'],}) # check result if process_payment['status'] == "success": queue.put({'cid': cid, 'result':'+'}) else: queue.put({'cid': cid, 'result':'-'}) self.send_header('Location', 'http://telegram.me/GodMoneyBot') self.end_headers() con.close()
def get_ym_account(card_id): log = logging.getLogger('payment') card = PaymentCard.query.get(card_id) if not card: message = 'Payment: Not found card card_id=%s' % card_id log.error(message) return False wallet = Wallet(card.token) try: info = wallet.account_info() except Exception as e: log.error(e) return False else: if 'account' not in info: return False card.pan = info['account'] card.save() return True
class WalletTestSuite(unittest.TestCase): def setUp(self): super(WalletTestSuite, self).setUp() self.api = Wallet(ACCESS_TOKEN) def assert_auth_header_present(self): pass def testAccountInfo(self): response = self.api.account_info() self.assert_auth_header_present() def testGetAuxToken(self): token = "some_aux_token" response = self.api.get_aux_token(["account-info", "operation-history"]) self.assertIn('aux_token', response) def testOperationHistory(self): options = {"records": 3} response = self.api.operation_history(options) def testOperationDetails(self): pass def testRequestPayment(self): options = { "pattern_id": "p2p", "to": "410011161616877", "amount_due": "0.02", "comment": "test payment comment from yandex-money-python", "message": "test payment message from yandex-money-python", "label": "testPayment", "test_payment": True, "test_result": "success" } response = self.api.request_payment(options) self.assertEqual(response['status'], 'success') def testResponsePayment(self): options = { "request_id": "test-p2p", "test_payment": True, "test_result": "success" } response = self.api.process_payment(options) self.assertEqual(response['status'], 'success') def testIncomingTransferAccept(self): #self.addResponse("incoming-transfer-accept", {"status": "success"}) operation_id = "some id" protection_code = "some code" # TODO: test when it's None response = self.api.incoming_transfer_accept( operation_id=operation_id, protection_code=protection_code ) self.assertEqual(response['status'], "refused") def testIncomingTransferReject(self): #self.addResponse("incoming-transfer-reject", {"status": "success"}) operation_id = "some operatoin id" response = self.api.incoming_transfer_reject( operation_id=operation_id, ) def testObtainTokenUrl(self): client_id = "client-id" url = Wallet.build_obtain_token_url( "client-id", "http://localhost/redirect", ["account-info", "operation_history"] ) # TODO: check url def testGetAccessToken(self): options = { "code": "code", "client_id": "client_id", "grant_type": "authorization_code", "redirect_uri": "redirect_uri", "client_secret": "client_secret" } response = Wallet.get_access_token( code=options["code"], client_id=options["client_id"], redirect_uri=options["redirect_uri"], client_secret=options["client_secret"] ) self.assertEqual(response['error'], 'unauthorized_client')
class WalletTestSuite(unittest.TestCase): def setUp(self): super(WalletTestSuite, self).setUp() self.api = Wallet(ACCESS_TOKEN) def assert_auth_header_present(self): pass def testAccountInfo(self): self.api.account_info() self.assert_auth_header_present() def testGetAuxToken(self): response = self.api.get_aux_token( ["account-info", "operation-history"]) self.assertIn('aux_token', response) def testOperationHistory(self): options = {"records": 3} self.api.operation_history(options) def testOperationDetails(self): self.api.operation_details("some-invalid-id") def testRequestPayment(self): options = { "pattern_id": "p2p", "to": "410011161616877", "amount_due": "0.02", "comment": "test payment comment from yandex-money-python", "message": "test payment message from yandex-money-python", "label": "testPayment", "test_payment": True, "test_result": "success" } response = self.api.request_payment(options) self.assertEqual(response['status'], 'success') def testResponsePayment(self): options = { "request_id": "test-p2p", "test_payment": True, "test_result": "success" } response = self.api.process_payment(options) self.assertEqual(response['status'], 'success') def testIncomingTransferAccept(self): operation_id = "some id" protection_code = "some code" # TODO: test when it's None response = self.api.incoming_transfer_accept( operation_id=operation_id, protection_code=protection_code) self.assertEqual(response['status'], "refused") def testIncomingTransferReject(self): operation_id = "some operatoin id" self.api.incoming_transfer_reject(operation_id=operation_id, ) def testObtainTokenUrl(self): Wallet.build_obtain_token_url("client-id", "http://localhost/redirect", ["account-info", "operation_history"]) # TODO: check url def testGetAccessToken(self): options = { "code": "code", "client_id": "client_id", "grant_type": "authorization_code", "redirect_uri": "redirect_uri", "client_secret": "client_secret" } response = Wallet.get_access_token( code=options["code"], client_id=options["client_id"], redirect_uri=options["redirect_uri"], client_secret=options["client_secret"]) self.assertEqual(response['error'], 'unauthorized_client')
def handle_text(message): #DB connection con = sqlite3.connect('/home/user/bot/users.sqlite') txt = message.text print('Получено сообщение: \'', txt, '\' от пользователя ', message.from_user.first_name, '(', message.from_user.id, ')') # if menu stack is empty: kbd = main_kbd if txt == '.': self.q = [] send_message(message.from_user.id, 'Выберите действие', main_kbd) return if not self.q: if txt == '\U0001F4B8 Перевод денег': ans = 'Введите номер кошелька или номер телефона или e-mail получателя' kbd = telebot.types.ReplyKeyboardHide(selective=False) send_message(message.from_user.id, ans, kbd) self.q.append('to_number') elif txt == '\U00002139 Информация': ans = 'О чем Вы хотите узнать?' send_message(message.from_user.id, ans, info_kbd) elif txt == '\U0001F4CB Услуги': ans = 'Пожалуйста, выберите услугу' kbd = ser_kbd send_message(message.from_user.id, ans, kbd) elif txt == '\U0001F4E2 Почему Яндекс.Деньги?': ans = 'Пройдите наш мини-опрос и узнайте, чем может быть полезен сервис Яндекс.Деньги именно Вам\n\nЧасто ли у Вас возникает чувство, что Вы забыли заплатить за интернет или телефон?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q1') elif txt == '\U0001F694 Проверка штрафов ГИБДД': ans = 'Введите номер водительского удостоверения' kbd = telebot.types.ReplyKeyboardHide(selective=False) self.q.append('check_penalty') send_message(message.from_user.id, ans, kbd) elif txt == '\U0001F6CD Акции партнеров': title_path = '/html/body/div[2]/div[2]/div/div[<i>]/div[<j>]/div/div[1]' img_path = '/html/body/div[2]/div[2]/div/div[<i>]/div[<j>]/a/div/img' url_path = '/html/body/div[2]/div[2]/div/div[<i>]/div[<j>]/a' promo_titles = [] promo_img = [] promo_url = [] r = requests.get('https://money.yandex.ru/promo') for j in range(1,2+1): for i in range(1,3+1): ht = lxml.html.fromstring(r.text) l = ht.xpath(title_path.replace('<i>', str(i)).replace('<j>', str(j))) p = ht.xpath(img_path.replace('<i>', str(i)).replace('<j>', str(j))) url = ht.xpath(url_path.replace('<i>', str(i)).replace('<j>', str(j))) promo_url.append(url[0].values()[4]) if promo_url[-1].startswith('http'): ans = l[0].text.replace('\xa0', ' ') + '\n' + url[0].values()[4] else: ans = l[0].text.replace('\xa0', ' ') + '\nhttp://money.yandex.ru' + url[0].values()[4] send_message(message.from_user.id, ans, kbd) elif txt == '\U0001F916 Информация о боте': ans = """Я умею: <b>Переводить деньги</b> на кошельки Укажите кошелек,телефон или email. Можете отправить контакт из адресной книжки и мы переведем деньги на кошелек по этому номеру. <b>Узнавать штрафы ГИБДД</b> Нужен только номер водительского удотоверения Сообщать об <b>акциях и предложениях</b> в Яндекс.Деньгах Покажу весь список со ссылками Узнавать ваш <b>баланс</b> и рассказывать про <b>курс валют</b> Только актуальные данные! А еще Вы можете пройти <b>опрос</b> и узнать о выгодах от использования лично для Вас. \n Полезные команды: чтобы перейти в главное меню введите точку '.' /help информация о боте /start начало работы """ kbd = main_kbd send_message(message.from_user.id, ans, kbd) elif txt == '\U0001F4B1 Курсы валют': ans = '\U0001F4C5 Данные актуальны на 13.03.2016 ' + str(datetime.datetime.now().time())[:8] + '\n\U0001F4B5 Доллар США\n70,3067 RUB\n\U0001F4B6 Евро\n77.9700 RUB' cur = con.cursor() cur.execute('SELECT token FROM `users` WHERE cid=' + str(message.from_user.id)) con.commit() sql_result = cur.fetchall() if sql_result: token = sql_result[0][0] wallet = Wallet(token) b = wallet.account_info()['balance_details']['available'] ans += '\nНа имеющиеся на вашем счете ' + str(b) + ' руб. Вы можете купить:\n· ' + str(round(b/70.3067, 2)) + ' долларов США\n· ' + str(round(b/77.97, 2)) + ' евро' send_message(message.from_user.id, ans, info_kbd) elif txt == 'Меню': self.q = [] send_message(message.from_user.id, 'Выберите действие', main_kbd) elif txt == '\U0001F4B0 Информация о балансе': ai = str(account_info(message, con)) print('ai = ', ai) print('ai.startswith(\'http\')', ai.startswith('http')) if ai.startswith('Для'): ans = ai else: ans = 'Баланс: ' + ai + ' руб.' kbd = info_kbd send_message(message.from_user.id, ans, kbd) else: ans = 'Я не понял, попробуйте что-нибудь другое' send_message(message.from_user.id, ans, kbd) else: if self.q: cmenu = self.q.pop() if cmenu == 'check_penalty': ans = check_penalty(message) send_message(message.from_user.id, ans, kbd) elif cmenu == 'to_number': self.to_number = message.text ans = 'Введите сумму к получению в рублях' kbd = amount_kbd send_message(message.from_user.id, ans, kbd) self.q.append('amount') elif cmenu == 'q1': if message.text == 'да': ans = 'Вы оплачиваете ЖКУ сами лично?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q2') else: ans = 'У Вас есть свой веб-сайт?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q3') elif cmenu == 'q3': if message.text == 'да': ans = 'Скорее всего, Вы выглядите как-то так...' kbd = main_kbd send_message(message.from_user.id, ans, kbd) self.send_photo(message.from_user.id, open('/home/user/bot/img/bm.jpg','rb')) ans = '\nВы можете принимать платежи на вашем сайте через <a href="https://kassa.yandex.ru/">Яндекс.Кассу</a>' send_message(message.from_user.id, ans, kbd) else: ans = 'Вы оплачиваете ЖКУ сами лично?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q2') elif cmenu == 'q2': if message.text == 'да': ans = 'У Вас есть карта "Тройка"?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q4') else: ans = 'У Вас мало времени на досуг?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q5') elif cmenu == 'q5': if message.text == 'да': ans = 'Скорее всего, Вы выглядите как-то так...' kbd = main_kbd send_message(message.from_user.id, ans, kbd) self.send_photo(message.from_user.id, open('/home/user/bot/img/work.jpg','rb')) ans = '\nМы понимаем, что у Вас не хватает времени на себя. Именно поэтому, чтобы помочь вам выкроить немного свободного времени, предлагаем удобно оплачивать штрафы ГИБДД, билеты в театр и прочие заказы в несколько кликов' send_message(message.from_user.id, ans, kbd) else: ans = 'Вы когда-либо покупали технику в инетрнет-магазине?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q8') elif cmenu == 'q4': if message.text == 'да': ans = 'Вы когда-либо покупали одежду в интернет-магазине?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q7') else: ans = 'У Вас есть личное авто?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q6') elif cmenu == 'q6': if message.text == 'да': ans = 'У Вас мало времени на досуг?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q5') else: ans = 'Вы когда-либо покупали одежду в интернет-магазине?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q7') elif cmenu == 'q7' or cmenu == 'q5': if message.text == 'нет': ans = 'Вы когда-либо покупали технику в интернет-магазине?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q8') elif cmenu == 'q8': if message.text == 'да': ans = 'Скорее всего, Вы выглядите как-то так...' kbd = main_kbd send_message(message.from_user.id, ans, kbd) self.send_photo(message.from_user.id, open('/home/user/bot/img/student.jpg','rb')) ans = '\nВы молоды и энергичны. Не стоит понапрасну терять время - оплачивайте покупки без отрыва от вашей насыщенной жизни прямо сейчас' send_message(message.from_user.id, ans, kbd) else: ans = 'Скорее всего, Вы выглядите как-то так...' kbd = main_kbd send_message(message.from_user.id, ans, kbd) self.send_photo(message.from_user.id, open('/home/user/bot/img/hw.jpg','rb')) ans = '\nВы явно заботитесь о домашнем очаге. Чтобы принести в дом еще больше уюта, платите легко и узнавайте скидки на <ahref="https://money.yandex.ru/promo/">сайте</a>' send_message(message.from_user.id, ans, kbd) elif cmenu == 'q7': if message.text == 'нет': ans = 'Скорее всего, Вы выглядите как-то так...' kbd = main_kbd send_message(message.from_user.id, ans, kbd) self.send_photo(message.from_user.id, open('/home/user/bot/img/hw.jpg','rb')) ans = '\nВы явно заботитесь о домашнем очаге. Чтобы принести в дом еще больше уюта, платите легко и узнавайте скидки на <a href="https://money.yandex.ru/promo/">сайте</a>' send_message(message.from_user.id, ans, kbd) else: ans = 'Скорее всего, Вы выглядите как-то так...' kbd = main_kbd send_message(message.from_user.id, ans, kbd) self.send_photo(message.from_user.id, open('/home/user/bot/img/student.jpg','rb')) ans = '\nВы молоды и энергичны. Не стоит понапрасну терять время - оплачивайте покупки без отрыва от вашей насыщенной жизни прямо сейчас' send_message(message.from_user.id, ans, kbd) elif cmenu == 'amount': self.amount = round(decimal.Decimal(message.text.replace(',','.')), 2) amount_ = self.amount amount_ = round(decimal.Decimal(message.text.replace(',','.')), 2) total_amount = str(amount_ * decimal.Decimal('1.005')) print(total_amount) if total_amount[total_amount.index('.') + 2] == '5' or total_amount[total_amount.index('.') + 2] == '0': if int(total_amount[total_amount.index('.') + 3]) > 4: amount_ = float(total_amount[:(total_amount.index('.') + 3)]) + 0.01 print(1) else: amount_ = float(total_amount[:(total_amount.index('.') + 3)]) print(0) else: amount_ = round(decimal.Decimal(total_amount), 2) print(2) ans = 'Сумма к оплате с учетом комиссии:' + str(amount_) + '\nПереводим?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('send') elif cmenu == 'send': if message.text.lower() == 'да': # print('to_number = ', to_number) ans = pay(message, self.to_number, self.amount, con) kbd = main_kbd send_message(message.from_user.id, ans, kbd) else: ans = 'Очень жаль, что Вы не хотите =(' kbd = main_kbd send_message(message.from_user.id, ans, kbd)
def do_GET(self): #DB connection con = sqlite3.connect('/home/user/bot/users.sqlite') cur = con.cursor() p = urlparse(self.path) q = parse_qs(p.query) self.send_response(302, 'Found') if 'cid' in q: scope = [ 'account-info', 'operation-history', 'payment-p2p' ] auth_url = Wallet.build_obtain_token_url( config.client_id, config.redirect_uri, scope) self.send_header('Location', auth_url) if 'b' in q: self.send_header("Set-Cookie", "cid=" + q['cid'][0] + '&b=1') else: self.send_header( "Set-Cookie", "cid=" + q['cid'][0] + '&to=' + q['to'][0] + '&amount=' + q['amount'][0]) elif 'code' in q: access_token = Wallet.get_access_token(config.client_id, q['code'][0], config.redirect_uri, client_secret=None) cookie = parse_qs(self.headers.get('Cookie')) cid = cookie['cid'][0] cur.execute('INSERT INTO users (cid, token) VALUES ("' + str(cid) + '", "' + access_token['access_token'] + '")') con.commit() wallet = Wallet(access_token['access_token']) if 'b' in cookie: queue.put({ 'cid': cid, 'b': wallet.account_info()['balance_details'] ['available'] }) else: to = cookie['to'][0] amount = cookie['amount'][0] request_options = { "pattern_id": "p2p", "to": to, "amount_due": amount, "comment": "переведено через бота", "message": "переведено через бота", "label": "testPayment" } request_result = wallet.request_payment( request_options) # check status process_payment = wallet.process_payment({ "request_id": request_result['request_id'], }) # check result if process_payment['status'] == "success": queue.put({'cid': cid, 'result': '+'}) else: queue.put({'cid': cid, 'result': '-'}) self.send_header('Location', 'http://telegram.me/GodMoneyBot') self.end_headers() con.close()
def handle_text(message): #DB connection con = sqlite3.connect('/home/user/bot/users.sqlite') txt = message.text print('Получено сообщение: \'', txt, '\' от пользователя ', message.from_user.first_name, '(', message.from_user.id, ')') # if menu stack is empty: kbd = main_kbd if txt == '.': self.q = [] send_message(message.from_user.id, 'Выберите действие', main_kbd) return if not self.q: if txt == '\U0001F4B8 Перевод денег': ans = 'Введите номер кошелька или номер телефона или e-mail получателя' kbd = telebot.types.ReplyKeyboardHide(selective=False) send_message(message.from_user.id, ans, kbd) self.q.append('to_number') elif txt == '\U00002139 Информация': ans = 'О чем Вы хотите узнать?' send_message(message.from_user.id, ans, info_kbd) elif txt == '\U0001F4CB Услуги': ans = 'Пожалуйста, выберите услугу' kbd = ser_kbd send_message(message.from_user.id, ans, kbd) elif txt == '\U0001F4E2 Почему Яндекс.Деньги?': ans = 'Пройдите наш мини-опрос и узнайте, чем может быть полезен сервис Яндекс.Деньги именно Вам\n\nЧасто ли у Вас возникает чувство, что Вы забыли заплатить за интернет или телефон?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q1') elif txt == '\U0001F694 Проверка штрафов ГИБДД': ans = 'Введите номер водительского удостоверения' kbd = telebot.types.ReplyKeyboardHide(selective=False) self.q.append('check_penalty') send_message(message.from_user.id, ans, kbd) elif txt == '\U0001F6CD Акции партнеров': title_path = '/html/body/div[2]/div[2]/div/div[<i>]/div[<j>]/div/div[1]' img_path = '/html/body/div[2]/div[2]/div/div[<i>]/div[<j>]/a/div/img' url_path = '/html/body/div[2]/div[2]/div/div[<i>]/div[<j>]/a' promo_titles = [] promo_img = [] promo_url = [] r = requests.get('https://money.yandex.ru/promo') for j in range(1, 2 + 1): for i in range(1, 3 + 1): ht = lxml.html.fromstring(r.text) l = ht.xpath( title_path.replace('<i>', str(i)).replace( '<j>', str(j))) p = ht.xpath( img_path.replace('<i>', str(i)).replace( '<j>', str(j))) url = ht.xpath( url_path.replace('<i>', str(i)).replace( '<j>', str(j))) promo_url.append(url[0].values()[4]) if promo_url[-1].startswith('http'): ans = l[0].text.replace( '\xa0', ' ') + '\n' + url[0].values()[4] else: ans = l[0].text.replace( '\xa0', ' ') + '\nhttp://money.yandex.ru' + url[ 0].values()[4] send_message(message.from_user.id, ans, kbd) elif txt == '\U0001F916 Информация о боте': ans = """Я умею: <b>Переводить деньги</b> на кошельки Укажите кошелек,телефон или email. Можете отправить контакт из адресной книжки и мы переведем деньги на кошелек по этому номеру. <b>Узнавать штрафы ГИБДД</b> Нужен только номер водительского удотоверения Сообщать об <b>акциях и предложениях</b> в Яндекс.Деньгах Покажу весь список со ссылками Узнавать ваш <b>баланс</b> и рассказывать про <b>курс валют</b> Только актуальные данные! А еще Вы можете пройти <b>опрос</b> и узнать о выгодах от использования лично для Вас. \n Полезные команды: чтобы перейти в главное меню введите точку '.' /help информация о боте /start начало работы """ kbd = main_kbd send_message(message.from_user.id, ans, kbd) elif txt == '\U0001F4B1 Курсы валют': ans = '\U0001F4C5 Данные актуальны на 13.03.2016 ' + str( datetime.datetime.now().time() )[:8] + '\n\U0001F4B5 Доллар США\n70,3067 RUB\n\U0001F4B6 Евро\n77.9700 RUB' cur = con.cursor() cur.execute('SELECT token FROM `users` WHERE cid=' + str(message.from_user.id)) con.commit() sql_result = cur.fetchall() if sql_result: token = sql_result[0][0] wallet = Wallet(token) b = wallet.account_info( )['balance_details']['available'] ans += '\nНа имеющиеся на вашем счете ' + str( b) + ' руб. Вы можете купить:\n· ' + str( round(b / 70.3067, 2)) + ' долларов США\n· ' + str( round(b / 77.97, 2)) + ' евро' send_message(message.from_user.id, ans, info_kbd) elif txt == 'Меню': self.q = [] send_message(message.from_user.id, 'Выберите действие', main_kbd) elif txt == '\U0001F4B0 Информация о балансе': ai = str(account_info(message, con)) print('ai = ', ai) print('ai.startswith(\'http\')', ai.startswith('http')) if ai.startswith('Для'): ans = ai else: ans = 'Баланс: ' + ai + ' руб.' kbd = info_kbd send_message(message.from_user.id, ans, kbd) else: ans = 'Я не понял, попробуйте что-нибудь другое' send_message(message.from_user.id, ans, kbd) else: if self.q: cmenu = self.q.pop() if cmenu == 'check_penalty': ans = check_penalty(message) send_message(message.from_user.id, ans, kbd) elif cmenu == 'to_number': self.to_number = message.text ans = 'Введите сумму к получению в рублях' kbd = amount_kbd send_message(message.from_user.id, ans, kbd) self.q.append('amount') elif cmenu == 'q1': if message.text == 'да': ans = 'Вы оплачиваете ЖКУ сами лично?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q2') else: ans = 'У Вас есть свой веб-сайт?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q3') elif cmenu == 'q3': if message.text == 'да': ans = 'Скорее всего, Вы выглядите как-то так...' kbd = main_kbd send_message(message.from_user.id, ans, kbd) self.send_photo( message.from_user.id, open('/home/user/bot/img/bm.jpg', 'rb')) ans = '\nВы можете принимать платежи на вашем сайте через <a href="https://kassa.yandex.ru/">Яндекс.Кассу</a>' send_message(message.from_user.id, ans, kbd) else: ans = 'Вы оплачиваете ЖКУ сами лично?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q2') elif cmenu == 'q2': if message.text == 'да': ans = 'У Вас есть карта "Тройка"?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q4') else: ans = 'У Вас мало времени на досуг?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q5') elif cmenu == 'q5': if message.text == 'да': ans = 'Скорее всего, Вы выглядите как-то так...' kbd = main_kbd send_message(message.from_user.id, ans, kbd) self.send_photo( message.from_user.id, open('/home/user/bot/img/work.jpg', 'rb')) ans = '\nМы понимаем, что у Вас не хватает времени на себя. Именно поэтому, чтобы помочь вам выкроить немного свободного времени, предлагаем удобно оплачивать штрафы ГИБДД, билеты в театр и прочие заказы в несколько кликов' send_message(message.from_user.id, ans, kbd) else: ans = 'Вы когда-либо покупали технику в инетрнет-магазине?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q8') elif cmenu == 'q4': if message.text == 'да': ans = 'Вы когда-либо покупали одежду в интернет-магазине?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q7') else: ans = 'У Вас есть личное авто?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q6') elif cmenu == 'q6': if message.text == 'да': ans = 'У Вас мало времени на досуг?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q5') else: ans = 'Вы когда-либо покупали одежду в интернет-магазине?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q7') elif cmenu == 'q7' or cmenu == 'q5': if message.text == 'нет': ans = 'Вы когда-либо покупали технику в интернет-магазине?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('q8') elif cmenu == 'q8': if message.text == 'да': ans = 'Скорее всего, Вы выглядите как-то так...' kbd = main_kbd send_message(message.from_user.id, ans, kbd) self.send_photo( message.from_user.id, open('/home/user/bot/img/student.jpg', 'rb')) ans = '\nВы молоды и энергичны. Не стоит понапрасну терять время - оплачивайте покупки без отрыва от вашей насыщенной жизни прямо сейчас' send_message(message.from_user.id, ans, kbd) else: ans = 'Скорее всего, Вы выглядите как-то так...' kbd = main_kbd send_message(message.from_user.id, ans, kbd) self.send_photo( message.from_user.id, open('/home/user/bot/img/hw.jpg', 'rb')) ans = '\nВы явно заботитесь о домашнем очаге. Чтобы принести в дом еще больше уюта, платите легко и узнавайте скидки на <ahref="https://money.yandex.ru/promo/">сайте</a>' send_message(message.from_user.id, ans, kbd) elif cmenu == 'q7': if message.text == 'нет': ans = 'Скорее всего, Вы выглядите как-то так...' kbd = main_kbd send_message(message.from_user.id, ans, kbd) self.send_photo( message.from_user.id, open('/home/user/bot/img/hw.jpg', 'rb')) ans = '\nВы явно заботитесь о домашнем очаге. Чтобы принести в дом еще больше уюта, платите легко и узнавайте скидки на <a href="https://money.yandex.ru/promo/">сайте</a>' send_message(message.from_user.id, ans, kbd) else: ans = 'Скорее всего, Вы выглядите как-то так...' kbd = main_kbd send_message(message.from_user.id, ans, kbd) self.send_photo( message.from_user.id, open('/home/user/bot/img/student.jpg', 'rb')) ans = '\nВы молоды и энергичны. Не стоит понапрасну терять время - оплачивайте покупки без отрыва от вашей насыщенной жизни прямо сейчас' send_message(message.from_user.id, ans, kbd) elif cmenu == 'amount': self.amount = round( decimal.Decimal(message.text.replace(',', '.')), 2) amount_ = self.amount amount_ = round( decimal.Decimal(message.text.replace(',', '.')), 2) total_amount = str(amount_ * decimal.Decimal('1.005')) print(total_amount) if total_amount[total_amount.index('.') + 2] == '5' or total_amount[ total_amount.index('.') + 2] == '0': if int(total_amount[total_amount.index('.') + 3]) > 4: amount_ = float(total_amount[:( total_amount.index('.') + 3)]) + 0.01 print(1) else: amount_ = float( total_amount[:(total_amount.index('.') + 3)]) print(0) else: amount_ = round(decimal.Decimal(total_amount), 2) print(2) ans = 'Сумма к оплате с учетом комиссии:' + str( amount_) + '\nПереводим?' kbd = yn_kbd send_message(message.from_user.id, ans, kbd) self.q.append('send') elif cmenu == 'send': if message.text.lower() == 'да': # print('to_number = ', to_number) ans = pay(message, self.to_number, self.amount, con) kbd = main_kbd send_message(message.from_user.id, ans, kbd) else: ans = 'Очень жаль, что Вы не хотите =(' kbd = main_kbd send_message(message.from_user.id, ans, kbd)
with open('good.jpg', 'wb') as file: file.write(a)''' scope = ['account-info', 'operation-history'] # etc.. client_id = 'A76ACB24B8300F9585A065ECEBF272C746AC909DE178E8D696D17B6E1D0BA0C6' redirect_uri = 'http://localhost/redirect' url = Wallet.build_obtain_token_url(client_id, "http://localhost/redirect", ["account-info", "operation_history"]) print(url) access_token = Wallet.get_access_token(client_id, code, redirect_uri, client_secret=None) api = Wallet(access_token) account_info = api.account_info() balance = account_info['balance'] # and so on request_options = { "pattern_id": "p2p", "to": "410011161616877", "amount_due": "0.02", "comment": "test payment comment from yandex-money-python", "message": "test payment message from yandex-money-python", "label": "testPayment", "test_payment": True, "test_result": "success" } request_result = api.request(request_options) # check status process_payment = api.process({
class WalletTestSuite(ResponseMockTestCase): def setUp(self): super(WalletTestSuite, self).setUp() self.api = Wallet("TEST TOKEN") def assert_auth_header_present(self): self.assertEqual("Bearer TEST TOKEN", responses.calls[0].request.headers['Authorization'], ) def testAccountInfo(self): self.addResponse("account-info", {"status": "success"} ) response = self.api.account_info() self.assertEqual(response['status'], "success") self.assert_auth_header_present() def testGetAuxToken(self): token = "some_aux_token" self.addResponse("token-aux", {"aux_token": token}) response = self.api.get_aux_token(["account-info", "operation-history"]) self.assertEqual(response['aux_token'], token) self.assertEqual(responses.calls[0].request.body, "scope=account-info+operation-history") def testOperationHistory(self): options = {"foo": "bar", "foo2": "bar2"} self.addResponse("operation-history", []) response = self.api.operation_history(options) self.assertEqual(response, []) self.assertEqual(responses.calls[0].request.body, urlencode(options) ) def testRequestPayment(self): self.addResponse("request-payment", {"status": "success"}) options = { "foo": "bar", "foo2": "bar2", } response = self.api.request_payment(options) self.assertEqual(response, {"status": "success"}) self.assertEqual(responses.calls[0].request.body, urlencode(options) ) def testResponsePayment(self): self.addResponse("process-payment", {"status": "success"}) options = { "foo": "bar", "foo2": "bar2", } response = self.api.process_payment(options) self.assertEqual(response, {"status": "success"}) self.assertEqual(responses.calls[0].request.body, urlencode(options) ) def testIncomingTransferAccept(self): self.addResponse("incoming-transfer-accept", {"status": "success"}) options = { "foo": "bar", "foo2": "bar2", } operation_id = "some id" protection_code = "some code" # TODO: test when it's None response = self.api.incoming_transfer_accept( operation_id=operation_id, protection_code=protection_code ) self.assertEqual(response, {"status": "success"}) self.assertEqual( responses.calls[0].request.body, urlencode({ "operation_id": operation_id, "protection_code": protection_code }) ) def testIncomingTransferReject(self): self.addResponse("incoming-transfer-reject", {"status": "success"}) operation_id = "some id" response = self.api.incoming_transfer_reject( operation_id=operation_id, ) self.assertEqual(response, {"status": "success"}) self.assertEqual( responses.calls[0].request.body, urlencode({ "operation_id": operation_id, }) ) def testObtainTokenUrl(self): client_id = "client-id" url = Wallet.build_obtain_token_url( "client-id", "http://localhost/redirect", ["account-info", "operation_history"] ) # TODO: check url def testGetAccessToken(self): self.addResponse(Wallet.SP_MONEY_URL + "/oauth/token", {"status": "success"}, is_api_url=False ) options = { "code": "code", "client_id": "client_id", "grant_type": "authorization_code", "redirect_uri": "redirect_uri", "client_secret": "client_secret" } response = Wallet.get_access_token( code=options["code"], client_id=options["client_id"], redirect_uri=options["redirect_uri"], client_secret=options["client_secret"] ) self.assertEqual(response, {"status": "success"}) self.assertEqual( responses.calls[0].request.body, urlencode(options) ) def testRevokeToken(self): self.addResponse("revoke", {"status": "success"}) Wallet.revoke_token("TEST TOKEN") self.assert_auth_header_present()