def get_balance(chatid): if not chatid in caches["balance"]: caches["balance"][chatid] = [db.get_balance(chatid),time.time()] else: if caches["balance"][chatid][1] < time.time() - 60 * 1: caches["balance"][chatid] = [db.get_balance(chatid),time.time()] return caches["balance"][chatid][0]
def check_bet(call, id, amount): if db.get_balance(id) >= amount: return amount else: bot.edit_message_text(chat_id=id, message_id=call.message.message_id, text="Недостаточно монет. Ваш баланс: " + str(db.get_balance(id))) return 0
def account_f(**kwargs): if 'id' in kwargs: check_new_month() db.set_state(kwargs['id'], account) reg_date = bot_time.get_reg_date(db.get_registred_time(kwargs['id'])) balance = db.get_balance(kwargs['id']) parent_id = db.get_parent_by_id(kwargs['id']) if db.is_have_free_access(kwargs['id']): exp_date = 'бесплатная' else: exp_date = bot_time.get_exp_date( db.get_expiration_time(kwargs['id'])) if exp_date is not None: exp_date = 'истекает ' + exp_date else: exp_date = 'не оплачена' if parent_id is not None and parent_id != 398821553: parent_name = db.get_name_by_id(parent_id) parent_phone = db.get_phone_by_id(parent_id) msg = msgs.account.format(parent_name, parent_phone, parent_id, exp_date, balance) else: msg = msgs.account_no_par.format(exp_date, balance) bot.send_message(kwargs['id'], msg, reply_markup=get_menu_markup()) referal_f(id=kwargs['id'])
def get_number(call): bot.delete_message(call.message.chat.id, call.message.message_id) global number number = lib.Number(services[choice], call.data) price = lib.get_price(services[choice], call.data) if price == "Нет в наличии": bot.send_message(call.message.chat.id, "Просим прощения, но в наличие нету номеров с заданными параметрами, попробуйте позже, или поменяйте страну, подкатегорию") elif str(number) and float(price[::-1][2:][::-1]) <= db.get_balance(call.message.chat.id): s = 'Сервис: {}\nНомер: {}\nОжидайте прихода смс\n\nЕсли в течении 4 минут смс не прийдёт, аренда будет отменена, после деньги, потраченные на аренду данного номера, будут зачислены к вам на счёт'.format(choice, str(number)) bot.send_message(call.message.chat.id, s, reply_markup=end_sms()) s = number.get_sms() print(s) if s == 'Аренда номера была отменена': cash = db.get_last_payment(call.message.chat.id) number.edit_status(8) bot.delete_message(call.message.chat.id, call.message.message_id + 1) else: bot.delete_message(call.message.chat.id, call.message.message_id + 1) db.buy(choice, str(number), call.message.chat.id, float(price[::-1][2:][::-1])) bot.send_message(call.message.chat.id, "Ваш код: ```" + str(s) + '```\nПожалуйста, выберете одно из предложенных действий', reply_markup=number_sms(), parse_mode="Markdown") else: try: number.edit_status(8) except: pass bot.send_message(call.message.chat.id, "На балансе недостаточно средств", reply_markup=menu())
def button(bot, update): """Callback funtion for the inline keyboard buttons that handles what happens when user chooses an option in the store.""" if update.callback_query.data.split(" ")[-1] in fiirumi.emojis: fiirumi.vote_message(bot, update) return if not is_registered(bot, update): return query = update.callback_query if query.data == "Poistu": query.edit_message_text(text="Osto keskeytetty") return user = update.effective_user.id time = datetime.datetime.today().isoformat() price = db.get_price(query.data) name = db.get_user(user)[0][2] #print(price) db.add_transaction(user, name, query.data, time, price) db.update_balance(user, -price) saldo = db.get_balance(user) #print(saldo) query.edit_message_text(text="Ostit tuotteen: {}.\n\nSaldo: {:.2f}€".format(query.data, saldo / 100))
def poista(update, context): """Does the actual removing when user wants to remove their last action.""" if update.message.text == "Kyllä": user = update.effective_user.id edellinen = db.get_last_transaction(update.effective_user.id) print("Removing transaction: ", edellinen[0]) summa = -edellinen[4] if edellinen[3] == "PANO" else edellinen[4] if edellinen[3] != "PANO" and edellinen[3] != "NOSTO": try: db.update_stock(edellinen[3], 0) except TypeError: pass db.update_balance(user, summa) db.delete_transaction(edellinen[0]) saldo = db.get_balance(user) context.bot.send_message( update.message.chat.id, "Tapahtuma poistettu. Tilisi saldo on {:.2f}€.".format(saldo / 100), reply_markup=ReplyKeyboardRemove()) else: context.bot.send_message(update.message.chat.id, "Tapahtumaa ei poistettu", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END
def nosta(update, context): """Withdraw money from account.""" maara = 0 try: maara = int(float(update.message.text.replace(",", ".")) * 100) if maara < 0: raise ValueError except ValueError: context.bot.send_message(update.message.chat.id, "Antamasi luku ei kelpaa. Nosto keskeytetty.", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END user = update.effective_user.id time = datetime.datetime.today().isoformat() name = db.get_user(user)[0][2] db.update_balance(update.effective_user.id, -maara) db.add_transaction(user, name, "NOSTO", time, maara) saldo = db.get_balance(update.effective_user.id) context.bot.send_message( update.message.chat.id, "Rahan nostaminen saldosta onnistui. Saldosi on nyt {:.2f}€".format( saldo / 100), reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END
def ohjaa(update, context): """"Conversation handler for when the user wants to top up or withdraw from their account.""" global saldo_sanat print(update.effective_message.text) if update.effective_message.text == saldo_sanat[0]: saldo = db.get_balance(update.effective_user.id) context.bot.send_message(update.effective_chat.id, "Saldosi on {:.2f}€.".format(saldo / 100), reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END elif update.effective_message.text == saldo_sanat[1]: update.message.reply_text( "Paljonko saldoa haluaisit lisätä? Anna positiivinen desimaaliluku.", reply_markup=ReplyKeyboardRemove()) return LISAA elif update.effective_message.text == saldo_sanat[2]: update.message.reply_text( "Paljonko rahaa haluaisit nostaa saldosta? Anna positiivinen desimaaliluku.", reply_markup=ReplyKeyboardRemove()) return NOSTA else: return ConversationHandler.END
def command_balance(user, session, bot, update): """ /balance Show's the users balance """ balance = db.get_balance(session, user) logger.info("{} has balance {}".format(user, balance)) update.message.reply_markdown(messages.balance(balance))
def comm_handler(message): select = "" if (message.text == "Первая игра"): bot.send_message(message.chat.id, description.game_one, reply_markup=keyboards.game_one_keyboard()) elif (message.text == "Вторая игра"): bot.send_message(message.chat.id, description.game_two, reply_markup=keyboards.game_two_bet_keyboard()) elif (message.text == "Третья игра"): bot.send_message(message.chat.id, description.game_three, reply_markup=keyboards.game_three_keyboard()) elif (message.text == "\U0001F4C3" + " " + 'Правила'): bot.send_message(message.chat.id, rules.rule.first_page, reply_markup=keyboards.rules_keyboard_first()) elif (message.text == "\U00002753" + " " + 'Инфо'): bot.send_message(message.chat.id, "Информация", reply_markup=keyboards.info_keyboard()) # pay.send_money(5, 79535780551) # print(db.get_values_game3_db(message.chat.id)) elif (message.text == "\U0001F4C4" + " " + 'Дополнительная информация'): bot.send_message(message.chat.id, info.inform) elif (message.text == "\U0001F464" + " " + 'Партнерская программа'): bot.send_message(message.chat.id, "Скоро!") elif (message.text == "\U0001F4B0" + " " + 'Кошелек'): select == message.text bot.send_message(message.chat.id, "Выберите: ", reply_markup=keyboards.purse_keyboard()) elif (message.text == "\U0001F4B2" + " " + 'Проверить баланс'): bot.send_message( message.chat.id, "\U0001F4B2" + " " + "Ваш баланс: " + str(db.get_balance(message.chat.id))) elif (message.text == "\U0001F4B5" + " " + 'Пополнить баланс'): trans_id = db.new_trans_id(message) bot.send_message(message.chat.id, "Ваш комментарий к переводу: " + str(trans_id), reply_markup=keyboards.payment_keyboard()) elif (message.text == "\U0001F4B8" + " " + 'Вывести монеты'): bot.send_message(message.chat.id, "Введите количество монет для вывода: ", reply_markup=keyboards.cancel_keyboard()) db.update_status_db(message, 1) elif (message.text == "\U000021A9" + " " + 'Назад'): bot.send_message(message.chat.id, "\U0001F4D1" + " " + "Главное меню", reply_markup=keyboards.start_keyboard()) else: bot.send_message(message.chat.id, "Пожалуйста, используйте клавиатуру")
def like_ddd(client, message): global caches userid = message["from_user"]["id"] add_message_to_cache(message) tg_analytic.statistics_chat(message.chat.id, get_title_chat(message)) value_to_send = int(message.text.split(" ")[1]) if message.reply_to_message.from_user.id != message["from_user"][ "id"] and not message["reply_to_message"]["from_user"][ "is_bot"] and value_to_send > 0: mnemonic = db.get_mnemo(userid) wallet = Wallet(seed=mnemonic) balance = db.get_balance(userid) value_to_send = correct_value_balance(value_to_send, balance) owner = get_owner_chat(app, message) to_address = db.create_user(message.reply_to_message.from_user.id) if value_to_send > 0.01: if owner != None: owner_dat = db.create_user(owner.user.id) # Check if like sending to owner of group or from him if wallet.address == owner_dat[2] or owner_dat[ 2] == to_address[2]: owner = None else: wallet.send(to=owner_dat[2], value=0.1 * float(value_to_send), coin="LIKE", payload='', include_commission=True) if owner == None: transaction = wallet.send(to=to_address[2], value=float(value_to_send), coin="LIKE", payload='', include_commission=True) else: transaction = wallet.send(to=to_address[2], value=0.9 * float(value_to_send), coin="LIKE", payload='', include_commission=True) if transaction != None: # If result success send message to chat if not 'error' in transaction["result"]: a = message["reply_to_message"].reply_text( "Your message was liked by " + get_name(message) + "'s message! [Spend your coins](https://t.me/MinterLikeBot)", parse_mode="Markdown", disable_web_page_preview=True) tg_analytic.statistics(message.chat.id, "emoji like", True, value_to_send) threading.Thread(target=delete_message, args=(a.chat.id, a.message_id)).start()
def withdrawal_hanlder_amount(message): if not message.text.isdigit(): bot.send_message(message.chat.id, "Пожалуйста, вводите только цифры") else: if message.text == "0": bot.send_message(message.chat.id, "Вы не можете вывести 0 монет") else: if int(message.text) <= db.get_balance(message.chat.id): db.update_amount_trans(message) bot.send_message(message.chat.id, "Введите номер кошелька") db.update_status_db(message, 2) else: bot.send_message(message.chat.id, "Недостаточно монет на балансе")
def saldo(update, context): """Conversations handler for when the user wishes to alter their saldo.""" if not is_registered(context.bot, update): return global saldo_sanat keyboard = [[saldo_sanat[1]], [saldo_sanat[2]]] reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True) saldo = db.get_balance(update.effective_user.id) / 100 update.message.reply_text( 'Saldosi on {:.2f}€.\n\nMitä haluaisit tehdä?\n\nKirjoita missä vaiheessa tahansa /lopeta keskeyttäksesi toiminnon.' .format(saldo), reply_markup=reply_markup) return OHJAA
def get_creds_f(**kwargs): if 'id' in kwargs and 'text' in kwargs: amount = float(db.get_amount(kwargs['id'])) balance = float(db.get_balance(kwargs['id'])) if amount > balance: bot.send_message(kwargs['id'], msgs.nomoney) menu_f(id=kwargs['id']) else: db.set_balance(kwargs['id'], balance - amount) bot.send_message( manager_id, msgs.exchange.format(amount, db.get_name_by_id(kwargs['id']), kwargs['text'])) bot.send_message(kwargs['id'], msgs.managered) menu_f(id=kwargs['id'])
def is_order_valid(session, form): order = OrderParameters(session, form) if not db.authenticate(order.username, order.password): return 'BAD USERNAME OR PASSWORD' order.usd_balance, order.eth_balance = db.get_balance(order.username) #user wants to purchase eth if order.option == 'buy' and order.usd_amount > order.usd_balance: return 'NOT ENOUGH USD' #user wants to sell eth elif order.option == 'sell' and order.eth_amount > order.eth_balance: return 'NOT ENOUGH ETH' return order
def like_d(client, message): # For asynchronity because Minter SDK doesnt support asyncio add_message_to_cache(message) tg_analytic.statistics_chat(message.chat.id, get_title_chat(message)) if message.reply_to_message and not "edit_date" is message and message.reply_to_message.from_user.id != message["from_user"]["id"] and not message["reply_to_message"]["from_user"]["is_bot"]: # Get owner chat for sending commision owner_chat = get_owner_chat(app, message) # Get count like for detect how many need send count_emoji = correct_count_emoji(is_emoji(message.text)) value_to_send = correct_value_to_send( 10 ** (count_emoji - 1)) # Correct if count emoji < 1 # Get user from whom will send LIKE user = db.create_user(message["from_user"]["id"]) user_balance = db.get_balance( message["from_user"]["id"]) # Get balance user value_to_send = correct_value_balance( float(value_to_send), float(user_balance)) wallet = Wallet(seed=db.get_mnemo( message["from_user"]["id"])) # Wallet of user to_address = db.create_user( message["reply_to_message"]["from_user"]["id"]) if owner_chat != None: # Check if owner exists owner_dat = db.create_user(owner_chat.user.id) # Check if like sending to owner of group or from him if wallet.address == owner_dat[2] or owner_dat[2] == to_address[2]: owner_chat = None if value_to_send > 0.01: if owner_chat != None: # If owner exists send to him some LIKE wallet.send(to=owner_dat[2], value=0.1 * value_to_send, coin="LIKE", payload='', include_commission=True) transaction = wallet.send(to=to_address[ 2], value=0.9 * value_to_send, coin="LIKE", payload='', include_commission=True) else: transaction = wallet.send(to=to_address[ 2], value=value_to_send, coin="LIKE", payload='', include_commission=True) if transaction != None: # If result success send message to chat if not 'error' in transaction["result"]: tg_analytic.statistics( message.chat.id, "emoji like", True, value_to_send) a = message["reply_to_message"].reply_text("Your message was liked by " + get_name( message) + "! [Spend your coins](https://t.me/MinterLikeBot)", parse_mode="Markdown", disable_web_page_preview=True) threading.Thread(target=delete_message, args=( a.chat.id, a.message_id)).start() # Delete message
def get_text_messages(message): s = message.text if s == "🔥 Номера": bot.send_message(message.chat.id, "Пожалуйста, выберете для каких целей вы хотите арендовать номер", reply_markup=num()) elif s == "🆘 Правила": bot.send_message(message.chat.id, "1. Главное:\n1.1 Мы продаем номера, без инструкций к их использованию. Вся ответственность после покупки номеров только на вас.\n1.2 Если комментарий при оплате был указан неверно, администрация имеет полное право не делать замену\n1.3 Администрация оставляет за собой право вносить любые изменения и дополнения в Правила, без предупреждения!\n1.4 Администрация вправе обнулить ваш лицевой счет.\n\nФОРМА ОБРАЩЕНИЯ\n1) Переписка с ботом + скрины переписки + скрин оплаты\n2) Предоставляйте видеозапись проверки номера с момента покупки в магазине и проверки на офф.сайте сервиса, который купили. Видео должно быть одно и цельное. ( ОБЯЗАТЕЛЬНО ) Отклонения от формы будут игнорироваться!!!", reply_markup=menu()) elif s == "💰 Баланс": b = db.get_balance(message.chat.id) s = int(b) if int(b) == float(b) else float(b) bot.send_message(message.chat.id, "Ваш баланс: " + str(s) + 'р.', reply_markup=balance()) bot.register_next_step_handler(message, money) elif s == '💩 Помощь': bot.send_message(message.chat.id, 'Обратитесь к @freddy_support ', reply_markup=menu()) elif s == "↪ В главное меню ↩": bot.send_message(message.chat.id, "Вы в главном меню", reply_markup=menu()) elif s == "💼 Мой профиль": lst = db.get_info(message.chat.id) bot.send_message(message.chat.id, 'id: {}\nКоличество заказов: {}шт. \nСумма всех ваших покупок: {}р.'.format(message.chat.id, len(lst), sum(lst))) else: bot.send_message(message.chat.id, 'Воспользуйтесь клавиатурой', reply_markup=menu())
def dashboard() -> 'html': d_date = DatesForCalendarCreation(app.config['MONTH_YEAR']['y'], app.config['MONTH_YEAR']['m']) dash = dict() fday, lday = (d_date.f_day(), d_date.l_day()) dash['month_incomes'] = get_month_values(fday, lday, 1) dash['month_costs'] = get_month_values(fday, lday, 2) dash['month_totals'] = { 'incomes': show_sums(fday, lday, 1), 'costs': show_sums(fday, lday, 2) } dash['top_purchase'] = get_top(fday, lday) dash['cur_balance'] = get_balance() dash['sber_balance'] = 100 return render_template('dashboard.html', the_title='Dashboard', the_dash=dash, for_nav=detect_general_parameters( app.config['MONTH_YEAR']['m'], app.config['MONTH_YEAR']['y']))
def lisaa(bot, update): """Add money to account.""" maara = 0 try: maara = int(float(update.message.text.replace(",", ".")) * 100) if maara < 0: raise ValueError except ValueError: bot.send_message(update.message.chat.id, "Antamasi luku ei kelpaa. Lisääminen keskeytetty.", reply_markup = ReplyKeyboardRemove()) return ConversationHandler.END user = update.effective_user.id time = datetime.datetime.today().isoformat() name = db.get_user(user)[0][2] db.update_balance(update.effective_user.id, maara) db.add_transaction(user, name, "PANO", time, maara) saldo = db.get_balance(update.effective_user.id) bot.send_message(update.message.chat.id, "Saldon lisääminen onnistui. Saldosi on nyt {:.2f}€".format(saldo / 100), reply_markup = ReplyKeyboardRemove()) return ConversationHandler.END
def callback_inline(call): id = call.from_user.id set1 = 0 set2 = 0 set3 = 0 ###game one### if call.data == "set50": set1 = check_bet(call, id, 50) elif call.data == "set100": set1 = check_bet(call, id, 100) elif call.data == "set150": set1 = check_bet(call, id, 150) elif call.data == "set500": set1 = check_bet(call, id, 500) if (set1 != 0): db.sub_balance(id, set1) db.stat_game(id, 1) res = games.game_one() db.add_balance(id, res) bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="It's the first game!!! Good luck !!! Have fun!!! You win: " + str(res), reply_markup=keyboards.game_one_restart_button()) ###game two### if call.data == "g2_50": set2 = check_bet(call, id, 50) elif call.data == "g2_100": set2 = check_bet(call, id, 100) elif call.data == "g2_150": set2 = check_bet(call, id, 150) elif call.data == "g2_500": set2 = check_bet(call, id, 500) if (set2 != 0): db.sub_balance(id, set2) db.update_last_bet_game2_db(id, set2) bot.edit_message_text(chat_id=id, message_id=call.message.message_id, text="Орел или Решка?", reply_markup=keyboards.game_two_keyboard()) if call.data == "0" or call.data == "1": db.stat_game(id, 2) set2 = db.get_last_bet_game2_db(id) res = games.game_two() if (res == 1): db.add_balance(id, set2 * 2) bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text= "It's the second game!!! Good luck !!! Have fun!!! You win: " + str(set2 * 2), reply_markup=keyboards.game_two_restart_button()) else: db.add_balance(id, 0) bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text= "It's the second game!!! Good luck !!! Have fun!!! You win: " + str(0), reply_markup=keyboards.game_two_restart_button()) db.reset_last_bet_game2_db(id) ###game three### if call.data == "g3_50": set3 = check_bet(call, id, 50) elif call.data == "g3_100": set3 = check_bet(call, id, 100) elif call.data == "g3_150": set3 = check_bet(call, id, 150) elif call.data == "g3_500": set3 = check_bet(call, id, 500) if (set3 != 0): db.sub_balance(id, set3) db.update_last_bet_game3_db(id, set3) db.stat_game(id, 3) bot.edit_message_text(chat_id=id, message_id=call.message.message_id, text="Откройте три коробки и найдите три звезды", reply_markup=games.game_three(id)) if call.data == "box1": if db.get_counter_game3_db(id) == 2: games.update_game_three(id, 0) game3_message(call, id) else: bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="Откройте три коробки и найдите три звезды", reply_markup=games.update_game_three(id, 0)) if call.data == "box2": if db.get_counter_game3_db(id) == 2: games.update_game_three(id, 1) game3_message(call, id) else: bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="Откройте три коробки и найдите три звезды", reply_markup=games.update_game_three(id, 1)) if call.data == "box3": if db.get_counter_game3_db(id) == 2: games.update_game_three(id, 2) game3_message(call, id) else: bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="Откройте три коробки и найдите три звезды", reply_markup=games.update_game_three(id, 2)) if call.data == "box4": if db.get_counter_game3_db(id) == 2: games.update_game_three(id, 3) game3_message(call, id) else: bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="Откройте три коробки и найдите три звезды", reply_markup=games.update_game_three(id, 3)) if call.data == "box5": if db.get_counter_game3_db(id) == 2: games.update_game_three(id, 4) game3_message(call, id) else: bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="Откройте три коробки и найдите три звезды", reply_markup=games.update_game_three(id, 4)) if call.data == "box6": if db.get_counter_game3_db(id) == 2: games.update_game_three(id, 5) game3_message(call, id) else: bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="Откройте три коробки и найдите три звезды", reply_markup=games.update_game_three(id, 5)) if call.data == "box7": if db.get_counter_game3_db(id) == 2: games.update_game_three(id, 6) game3_message(call, id) else: bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="Откройте три коробки и найдите три звезды", reply_markup=games.update_game_three(id, 6)) if call.data == "box8": if db.get_counter_game3_db(id) == 2: games.update_game_three(id, 7) game3_message(call, id) else: bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="Откройте три коробки и найдите три звезды", reply_markup=games.update_game_three(id, 7)) if call.data == "box9": if db.get_counter_game3_db(id) == 2: games.update_game_three(id, 8) game3_message(call, id) else: bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="Откройте три коробки и найдите три звезды", reply_markup=games.update_game_three(id, 8)) if (call.data == "restart_one"): bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="It's the first game!!! Good luck !!! Have fun!!!", reply_markup=keyboards.game_one_keyboard()) if (call.data == "restart_two"): bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="It's the second game!!! Good luck !!! Have fun!!!", reply_markup=keyboards.game_two_bet_keyboard()) if (call.data == "restart_three"): bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text="It's the third game!!! Good luck !!! Have fun!!!", reply_markup=keyboards.game_three_keyboard()) if (call.data == "check_payment"): #comment = "Пополнение или возврат по QVC (QVP)" comment = db.get_lt_id(id) amount = pay.qiwi_amount(str(comment)) if (amount <= 0 or amount == None): bot.edit_message_text( chat_id=id, message_id=call.message.message_id, text= "Пожалуйста, проверьте правильность перевода и нажмите снова!", reply_markup=keyboards.payment_keyboard()) else: db.add_balance(id, amount) db.erase_trans_id(id) balance = db.get_balance(id) bot.edit_message_text(chat_id=id, message_id=call.message.message_id, text="Пополнение совершено. Ваш баланс: " + str(balance)) if (call.data == "cancel_payment"): db.update_last_trans(id, 0, 0) bot.edit_message_text(chat_id=id, message_id=call.message.message_id, text="Вы отменили запрос") bot.send_message(id, "\U0001F4D1" + " " + "Главное меню", reply_markup=keyboards.start_keyboard()) if (call.data == "accept_payment"): amount = db.get_amount_last_trans(id) bot.edit_message_text(chat_id=id, message_id=call.message.message_id, text="Вы подтвердили запрос") # pay.test_send(amount, db.get_number_last_trans(id)) pay.send_money(amount, db.get_number_last_trans(id)) db.sub_balance(id, amount) db.update_last_trans(id, 0, 0) bot.send_message(id, "\U0001F4D1" + " " + "Главное меню", reply_markup=keyboards.start_keyboard()) if (call.data == "page_next"): bot.edit_message_text(chat_id=id, message_id=call.message.message_id, text=rules.rule.second_page, reply_markup=keyboards.rules_keyboard_second()) if (call.data == "page_last"): bot.edit_message_text(chat_id=id, message_id=call.message.message_id, text=rules.rule.third_page, reply_markup=keyboards.rules_keyboard_third()) if (call.data == "page_back"): bot.edit_message_text(chat_id=id, message_id=call.message.message_id, text=rules.rule.first_page, reply_markup=keyboards.rules_keyboard_first()) if (call.data == "page_back_two"): bot.edit_message_text(chat_id=id, message_id=call.message.message_id, text=rules.rule.second_page, reply_markup=keyboards.rules_keyboard_second())
def pay(user, session, bot, update, payment_request): try: decode_payreq = decode_invoice(payment_request) if not decode_payreq: update.message.reply_text("This doesn't look like an invoice") return except Exception, e: update.message.reply_markdown(messages.exception(e)) raise e logger.debug(decode_payreq) satoshis = decode_payreq.num_satoshis destination = decode_payreq.destination if satoshis > db.get_balance(session, user): update.message.reply_text("Insufficient funds") return logger.info("{} initiating payment of {}".format(user, payment_request)) update.message.reply_text("Sending payment...") # XXX: This is a synchonous command, will block until GRPC_TIMEOUT try: ret = stub.SendPaymentSync( ln.SendRequest(payment_request=payment_request), timeout=GRPC_TIMEOUT) except Exception, e: update.message.reply_markdown(messages.exception(e)) raise e
def balance(): if request.method == 'GET': usd_balance, eth_balance = db.get_balance(session['username']) with open('links.html', 'r') as l: return 'USD: {} ETH: {}{}'.format(usd_balance, eth_balance, l.read())
def check_balance(self, message): return db.get_balance(self)
def detect_general_parameters(m, y) -> dict: """Returns standard parameters of app""" return {'date': str(m) + '.' + str(y), 'balance': get_balance(m, y), 'sber_balance': get_sber_balance(m, y)}
def show() -> 'json': """For AJAX-requests""" trans_type = request.args.get('trtype') gr_id = request.args.get('group') d_params = { 'd': request.args.get('trn_day'), 'm': request.args.get('trn_month'), 'y': request.args.get('trn_year') } last_m_pars = request.args.get('show_months') show_acc = request.args.get('show_accounts') # check get-request-arguments db_res = 'Parameters are not identified' if trans_type is not None: db_res = db_session.execute( '''SELECT group_goods_id, name FROM group_goods WHERE transacion_type_id = :w1''', { 'w1': trans_type }).fetchall() elif gr_id is not None: db_res = db_session.execute( '''SELECT purchase_id, name FROM purchase WHERE group_goods_id = :w1''', { 'w1': gr_id }).fetchall() elif last_m_pars is not None: if not json.loads(last_m_pars): return app_date = datetime.date(app.config['MONTH_YEAR']['y'], app.config['MONTH_YEAR']['m'], 1) last_m_pur = get_last_months_purchase(datepar=app_date) db_res = { k: [itm[k] if itm[k] is not None else 0 for itm in last_m_pur] for rw in last_m_pur for k in rw.keys() } try: db_res['month'] = [get_rus_month(m) for m in db_res['month']] except KeyError: db_res.setdefault('month', '') elif None not in d_params.values(): try: d_params['m'] = get_month(d_params['m']) db_res = get_transactions_per_day(d_params) if len(db_res) == 0: db_res = [['Данные не найдены']] except MonthFindError: pass elif show_acc is not None: if json.loads(show_acc): db_res = get_accounts() elif request.args.get('upd_sber_data') is not None: if json.loads(request.args.get('upd_sber_data')): m, y = [ app.config['MONTH_YEAR']['m'], app.config['MONTH_YEAR']['y'] ] db_res = { 'bal': get_balance(m, y), 'sber_bal': get_sber_balance(m, y), 'sber_tbl': [{ ky: val if ky != 'date' else str(val.day) + ' ' + get_rus_month(val.month) + ' ' + str(val.year) for ky, val in line.items() } for line in get_sber_transactions(m, y)] } elif request.args.get('show_users') is not None: if json.loads(request.args.get('show_users')): db_res = get_owner() elif request.args.get('month_year') is not None: if json.loads(request.args.get('month_year')): db_res = { 'month': app.config['MONTH_YEAR']['m'], 'year': app.config['MONTH_YEAR']['y'] } elif request.args.get('show_planning') is not None and request.args.get( 'planning_group') is not None: if json.loads(request.args.get('show_planning')): d = datetime.date(app.config['MONTH_YEAR']['y'], app.config['MONTH_YEAR']['m'], 1) planning_groups = { pl_gr_row['pl_gr_id']: pl_gr_row['name'] for pl_gr_row in get_planning_groups() } par_plan_gr = request.args.get('planning_group') if par_plan_gr not in planning_groups: db_res = {'message': 'Не указана группа планирования'} else: db_res = { 'title': planning_groups[par_plan_gr], 'data': [{k: v for k, v in plan_par_row.items()} for plan_par_row in get_planning_parameters( par_plan_gr, cur_date=d, with_pur_id=True)] } if len(db_res['data']) != 0: db_res_keys = list(db_res['data'][0].keys()) db_res['keys'] = get_field_props(db_res_keys) # we need list-type for returning the json-answer if type(db_res) == list: db_res_for_json = [list(line) for line in db_res] else: db_res_for_json = db_res # json-answer return json.dumps(db_res_for_json, sort_keys=True, ensure_ascii=False)