def handle_catalog(call): data = get_unique_seq(call.message.chat.id) if not data: bot.send_photo(call.message.chat.id, open('404.png', 'rb')) bot.send_message(call.message.chat.id, 'Нет доступных курсов..') return for seq in data: if not seq['price']: prices = [LabeledPrice('Комиссия', 10000)] else: prices = [ LabeledPrice(label=seq['name'], amount=int(seq['price']) * 100), LabeledPrice('Комиссия', 10000) ] bot.send_invoice( call.message.chat.id, title=seq['name'], description=seq['description'], provider_token=PROVIDER_TOKEN, currency='rub', photo_url= 'http://hsct.co.uk/wp-content/uploads/2016/04/course2.png', photo_height=448, # !=0/None or picture won't be shown photo_width=1024, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices, start_parameter='test-query', invoice_payload='%d/%d' % (seq['id_'], call.message.chat.id))
def handl(m): prices1 = [ LabeledPrice(label='Тест', amount=10000), LabeledPrice(label='За доставку на дом', amount=35000) ] bot.send_invoice(chat_id=m.chat.id, title='Покупай!',description='Покупка тест',is_flexible=False,\ invoice_payload='payload',provider_token='381764678:TEST:7232',start_parameter='startp',\ currency="RUB",prices=prices1)
def from_order_items_to_labeled_prices(order, language) -> List[LabeledPrice]: order_items = order.order_items.all() currency_value = settings.get_currency_value() prices = [] for oi in order_items: if oi.dish.is_sale: prices.append(LabeledPrice(from_dish_full_name(oi.dish, language) + ' x ' + str(oi.count), int(oi.count * oi.dish.sale_price * currency_value * 100))) else: prices.append(LabeledPrice(from_dish_full_name(oi.dish, language) + ' x ' + str(oi.count), int(oi.count * oi.dish.price * currency_value * 100))) if order.delivery_price: prices.append(LabeledPrice(get_string('delivery_price'), int(order.delivery_price * currency_value * 100))) return prices
def get_number_of_money(message): global number_of_money try: number_of_money = int(message.text) except ValueError: bot.send_message(message.from_user.id, text='Помилка при введені суми') bot.register_next_step_handler(message, callback=get_number_of_money) else: prices = [ LabeledPrice(label='Поповнення рахунку', amount=number_of_money * 100) ] bot.send_message(message.chat.id, "Зараз платежі приймаються лише в тестовому режимі" "\n\nВаш тестовий платіж:", parse_mode='Markdown') bot.send_invoice( message.chat.id, title='Working Time Machine', description=' Поповнення рахунку', provider_token=provider_token, currency='UAH', photo_url= 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQP9bwtPnfeODkt-vJyBYpYDjStfrRMB5UQ4w&usqp=CAU', photo_height=0, # !=0/None or picture won't be shown photo_width=0, photo_size=0, is_flexible=False, # True If you need to set up Shipping Fee prices=prices, start_parameter='time-machine-example', invoice_payload='HAPPY FRIDAYS COUPON')
def send_invoice(user_id): user = User.get(user_id) violations = user.get_fines() title = 'Штрафы' if user.language_code == 'ru' else 'Fines' prices = [] description = '' currency = 'rub' if user.language_code == 'ru' else 'usd' converter = CurrencyConverter( 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip') for violation in violations: label, datetime_native, fine = violation amount = int(converter.convert(fine, 'USD', 'RUB') * 100) if \ user.language_code == 'ru' else fine * 100 prices.append( LabeledPrice(label=f'{datetime_native} {label}', amount=amount)) description += f'{datetime_native} {label} ${fine}\n\n' bot.send_invoice( user_id, title=title, description=description, provider_token=provider_token, currency=currency, photo_url= 'https://safety4sea.com/wp-content/uploads/2016/06/fine-e1522744870402.png', photo_height=512, # !=0/None or picture won't be shown photo_width=512, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices, start_parameter='fines-payment', invoice_payload='FINES PAYMENT')
def payment_card(call: CallbackQuery): if call.message: user = call.from_user if register.exists(user): ctx = register.context(user) text = "Ваш заказ:\n" + \ "".join( f"- {d['name']} {d['price']} грн\n" for d in ctx.dishes) text += f'Общая сумма заказа: {ctx.price} грн' prices = [ LabeledPrice(label=d['name'], amount=int(float(d['price']) * 100)) for d in ctx.dishes ] bot.send_invoice(call.message.chat.id, title='Обеды в офис', description=text, provider_token=tokens.liqPay, currency='uah', prices=prices, start_parameter='office-lunch', invoice_payload='LUNCH') else: bot.send_message(call.message.chat.id, text="Для нового заказа выполните команду /start")
def makeLabeledPrices(): things = [] keys = list(items.keys()) values = list(items.values()) for i in range(0, len(items)): things.append(LabeledPrice(values[i]['name'], values[i]['price'] * 100)) prices = things
def from_order_items_to_labeled_prices(order_items: List[OrderItem], language) -> List[LabeledPrice]: currency_value = settings.get_currency_value() return [ LabeledPrice( from_dish_name(oi.dish, language) + ' x ' + str(oi.count), int(oi.count * oi.dish.price * currency_value * 100)) for oi in order_items ]
def confirm_sub(bot, telegram): # statTime = time.strftime("%y%m") # statTime += '01' try: price_water = [] add_sub( **{ 'telegram': telegram, 'name': users[telegram].get('name'), 'phone': users[telegram].get('phone'), 'price': users[telegram]['price'], 'term': users[telegram]['term'], 'quantity': users[telegram]['how_much_sub'], 'sum': (int(users[telegram]['price']) * int(users[telegram]['how_much_sub'])), 'econom': (int(users[telegram].get('how_much_sub')) * (int(product_price.get('water')) - int(users[telegram]['price']))), 'street': users[telegram].get('street') }) summa = int(users[telegram]['price']) * int( users[telegram]['how_much_sub']) * 100 price_water.append( LabeledPrice(label=users[telegram]['term'], amount=summa)) prices.update({telegram: price_water}) except Exception as e: print('e', e) return back_to_main_menu_del(bot, telegram) try: text = FOR_SEND_SUB_TO_OTHER_BOT.format( telegram, users[telegram].get('name'), users[telegram].get('phone'), users[telegram]['term'], users[telegram]['price'], users[telegram]['how_much_sub'], (int(users[telegram]['price']) * int(users[telegram]['how_much_sub'])), (int(users[telegram].get('how_much_sub')) * (int(product_price.get('water')) - int(users[telegram]['price']))), users[telegram].get('street')) except Exception as e: print(e) return back_to_main_menu_del(bot, telegram) report(text) try: users[telegram].update(report=text) except Exception as e: back_to_main_menu_del(bot, telegram) pay_menu(bot, telegram)
def handle_start(message): print(message.text) if len(message.text) > 6: key = message.text[7:] if key not in sequences.keys(): bot.send_message( message.chat.id, 'Вы прошли по неработающей ссылке.\n%s' % start_text) return seq = Sequence(*[None for i in range(9)], key_id=sequences.get(key)) if not seq.price: prices = [LabeledPrice('Комиссия', 10000)] else: prices = [ LabeledPrice(label=seq.name, amount=int(seq.price) * 100), LabeledPrice('Комиссия', 10000) ] bot.send_invoice( message.chat.id, title=seq.name, description=seq.description, provider_token=PROVIDER_TOKEN, currency='rub', photo_url= 'http://hsct.co.uk/wp-content/uploads/2016/04/course2.png', photo_height=448, # !=0/None or picture won't be shown photo_width=1024, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices, start_parameter='test-query', invoice_payload='%d/%d' % (seq.id_, message.chat.id)) # bot.send_message(message.chat.id, seq.start_message, reply_markup=start_markup(seq.id_)) # seq.start(message.from_user.id) # pool.reload() else: bot.send_message(message.chat.id, menu_text, reply_markup=main_markup())
def donate(message): if tokens.provider_token == '': my_bot.reply_to(message, 'Не подключен токен оплаты!') return my_bot.send_invoice(message.chat.id, title='Поддержка разработки бота', description='Хочется есть, помогите 😞', provider_token=tokens.provider_token, currency='RUB', prices=[LabeledPrice(label='На сникерс', amount=5000)], start_parameter='donate-50', invoice_payload='donate-50') my_bot.send_invoice(message.chat.id, title='Поддержка разработки бота | Plus', description='Очень хочется есть, помогите 😩', provider_token=tokens.provider_token, currency='RUB', prices=[LabeledPrice(label='На обед', amount=25000)], start_parameter='donate-250', invoice_payload='donate-250')
def command_pay(message): prices = [LabeledPrice(label='Working Time Machine', amount=100)] bot.send_invoice( message.chat.id, title='Оплата штрафов', description='Test', provider_token=provider_token, currency='usd', photo_url= 'https://safety4sea.com/wp-content/uploads/2016/06/fine-e1522744870402.png', photo_height=512, # !=0/None or picture won't be shown photo_width=512, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices, start_parameter='fines-payment', invoice_payload='FINES PAYMENT')
def pay(chat_id, user_id, notification_id): if user_id not in order_items: return prices = [] for _, item in order_items[user_id].items(): if item.amount > 0: prices.append( LabeledPrice('{} ({} шт)'.format(item.name, item.amount), item.price * item.amount * 100)) bot.send_message(chat_id, card_disclaimer, parse_mode='Markdown') bot.send_invoice( chat_id, title='Рожковый рай', description='Самые вкусные рожки в галактике', provider_token=provider_token, currency='rub', is_flexible=False, # True If you need to set up Shipping Fee prices=prices, start_parameter='time-machine-example', invoice_payload=notification_id)
def buy_tranzzo(message): amount = message.text # prices = [LabeledPrice(label='Working Time Machine', amount=5750)] # pprint(self.text) # print(self.is_int(self.text)) prices = [LabeledPrice(label='Heroes Life', amount=int(amount) * 1000)] # bot.send_message(message.chat.id, "Нажмите для оплаты /buy") bot.send_invoice( message.chat.id, title='Покупку алмазов в Heroes Life', description='Для оплаты нажмите на кнопку ниже.', provider_token=provider_token, currency='rub', # photo_url='http://erkelzaar.tsudao.com/models/perrotta/TIME_MACHINE.jpg', # photo_height=512, # !=0/None or picture won't be shown ## photo_width=512, # photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices, start_parameter='time-machine-example', invoice_payload='Heroes Life')
""" # e-mail & password for naviaddress map api email = '' password = '' # telegram token token = '' # telegram payment token payment_token = '' # global variables used in bot user_state = None navi_container, navi_naviaddress = '', '' event_name, event_link = '', '' event_money = '' user_name, user_mail = '', '' weights = [] step_description = '' steps = [] image_counter = 0 # additional payment variables settings_global = {"cluster_numbers": None} shipping_options = [ ShippingOption(id='instant', title='1').add_price(LabeledPrice('1', 1000)), ShippingOption(id='pickup', title='2').add_price(LabeledPrice('2', 300)) ]
def confirm(bot, telegram, call_id): pay_menu(bot, telegram) text = '' price_water = [] print('here') text = FOR_SEND_ORDER_TO_OTHER_BOT2.format(telegram, users[telegram].get('name'), users[telegram].get('phone'), users[telegram].get('street')) if users[telegram].get('water'): try: if users[telegram].get('water'): insert_order( **{ 'telegram': telegram, 'name': users[telegram].get('name'), 'phone': users[telegram].get('phone'), 'goods': 'water', 'amount': users[telegram].get('water'), 'sum': (users[telegram].get('water') * product_price.get('water')), 'street': users[telegram].get('street') }) summa = users[telegram].get('water') * product_price.get( 'water') * 100 price_water.append(LabeledPrice(label='water19', amount=summa)) prices.update({ telegram: [ LabeledPrice(label='water19', amount=int(users[telegram].get('water')) * int(product_price.get('water'))) ] }) try: text += FOR_SEND_BOTTLE_TO_OTHER_BOT.format( 'вода', users[telegram].get('water'), (users[telegram].get('water') * int(product_price.get('water')))) except Exception as e: print('error', e) except Exception as e: return back_to_main_menu_del(bot, telegram) if users[telegram].get('pompa'): insert_order( **{ 'telegram': telegram, 'name': users[telegram].get('name'), 'phone': users[telegram].get('phone'), 'goods': 'pompa', 'amount': users[telegram].get('pompa'), 'sum': (users[telegram].get('pompa') * product_price.get('pompa')), 'street': users[telegram].get('street') }) try: text += FOR_SEND_POMPA_TO_OTHER_BOT.format( 'помпа', users[telegram].get('pompa'), (users[telegram].get('pompa') * product_price.get('pompa'))) summa = int(users[telegram].get('pompa')) * int( product_price.get('pompa')) * 100 price_water.append(LabeledPrice(label='pompa', amount=summa)) if prices.get(telegram): prices[telegram].append( LabeledPrice(label='pompa', amount=users[telegram].get('pompa') * product_price.get('pompa'))) else: prices.update({ telegram: [ LabeledPrice(label='pompa', amount=int(users[telegram].get('pompa')) * int(product_price.get('pompa'))) ] }) except Exception as e: print('error pompa', e) if users[telegram].get('pompaEL'): insert_order( **{ 'telegram': telegram, 'name': users[telegram].get('name'), 'phone': users[telegram].get('phone'), 'goods': 'pompaEL', 'amount': users[telegram].get('pompaEL'), 'sum': (users[telegram].get('pompaEL') * product_price.get('pompaEL')), 'street': users[telegram].get('street') }) summa = int(users[telegram].get('pompaEL')) * int( product_price.get('pompaEL')) * 100 price_water.append(LabeledPrice(label='pompaEL', amount=summa)) if prices.get(telegram): prices[telegram].append( LabeledPrice(label='pompaEL', amount=users[telegram].get('pompaEL') * product_price.get('pompaEL'))) else: prices.update({ telegram: [ LabeledPrice(label='pompaEL', amount=int(users[telegram].get('pompaEL')) * int(product_price.get('pompaEL'))) ] }) try: text += FOR_SEND_POMPA_TO_OTHER_BOT.format( 'помпа электрическа', users[telegram].get('pompaEL'), (users[telegram].get('pompaEL') * product_price.get('pompaEL'))) except Exception as e: print('error pompaEL', e) print('here') if users[telegram].get('culer'): insert_order( **{ 'telegram': telegram, 'name': users[telegram].get('name'), 'phone': users[telegram].get('phone'), 'goods': 'culer', 'amount': users[telegram].get('culer'), 'sum': (users[telegram].get('culer') * product_price.get('culer')), 'street': users[telegram].get('street') }) summa = int(users[telegram].get('culer')) * int( product_price.get('culer')) * 100 price_water.append(LabeledPrice(label='culer', amount=summa)) if prices.get(telegram): prices[telegram].append( LabeledPrice(label='culer', amount=users[telegram].get('culer') * product_price.get('culer'))) else: prices.update({ telegram: [ LabeledPrice(label='culer', amount=int(users[telegram].get('culer')) * int(product_price.get('culer'))) ] }) try: text += FOR_SEND_POMPA_TO_OTHER_BOT.format( 'кулер', users[telegram].get('culer'), (users[telegram].get('culer') * product_price.get('culer'))) except Exception as e: print('error pompa', e) print('here') users[telegram].update(report=text) print('here') report(text) try: users.pop(telegram) except Exception as e: print(e)
def handle_Text(mes): findUser = mes.chat.id if str(findUser) in db: print("Found user..") userDB = db[str(mes.chat.id)] print("[" + mes.from_user.first_name + " | " + userDB['stage'] + "]: " + mes.text) if getStage(mes) == 'registerCountry' or userDB['country'] == "": userDB['country'] = mes.text print("User " + mes.from_user.first_name + "'s country is set to " + mes.text) setStage("enterName", mes) elif getStage(mes) == "enterName" or userDB['fullname'] == "": userDB['fullname'] = mes.text print("User's new name: " + str(mes.text)) setStage("enterPhone", mes) elif getStage(mes) == "enterPhone" or userDB['phone'] == "": userDB['phone'] = mes.text print("User's phone: " + str(mes.text)) setStage("enterEmail", mes) elif getStage(mes) == "enterEmail" or userDB['email'] == "": userDB['email'] = mes.text print("User's email: " + str(mes.text)) setStage("isCompany", mes) elif getStage( mes ) == "isCompany" and mes.text == "Skip": ## CHOOSING A COMPANY setStage("registerCompany", mes) userDB['company'] = mes.text print("User " + mes.from_user.first_name + "'s company is set to " + mes.text) elif getStage( mes ) == "isCompany" and mes.text != "Skip": ## ENTERING CITY NAME userDB['city'] = mes.text print("User " + mes.from_user.first_name + "'s city is set to " + mes.text) setStage('registerAddress', mes) elif getStage(mes) == "registerAddress": userDB['address'] = mes.text print("User " + mes.from_user.first_name + "'s address is set to " + mes.text) setStage("finishRegister", mes) elif getStage(mes) == "registerCompany" and mes.text != "skip": userDB['company'] = mes.text setStage("finishRegister", mes) elif getStage(mes) == "registerCompany" and mes.text == "skip": userDB['company'] = "" setStage("isCompany", mes) elif getStage(mes) == "finishRegister" and mes.text == "Yes": if str(mes.chat.id) in usersdb.backups: db[str(mes.chat.id)]['cart'] = usersdb.backups[str( mes.chat.id)]['cart'] saveUser(mes) setStage("MainMenu", mes) elif getStage(mes) == "finishRegister" and mes.text == "No": print("Restart") setStage("firststart", mes) elif getStage(mes) == "settings" and mes.text == "Register again": print("Restart") usersdb.backups[str(mes.chat.id)] = db[str(mes.chat.id)] setStage("firststart", mes) elif getStage(mes) == "settings" and mes.text == dict["home"]: print("Settings cancelled by " + str(userDB)) saveUser(mes) setStage("MainMenu", mes) elif mes.text == "Show more": sort(db[str(mes.chat.id)]['category'], mes, db[str(mes.chat.id)]['step']) elif mes.text == dict["settings"]: setStage("settings", mes) elif mes.text == dict["cart"]: setStage("cart", mes) elif mes.text == dict[ "home"] or mes.text == "Home" or mes.text == "home" or mes.text == "back": setStage("MainMenu", mes) elif mes.text == dict["browse"]: setStage("browse", mes) elif mes.text == dict['contact']: setStage("contact", mes) elif getStage(mes) == "browse" and mes.text in list(itemsdb.cats): sort(itemsdb.bycategory[mes.text], mes, 0) patchCategory(mes) elif getStage(mes) == "payment" and mes.text == "Pay": print("Trying to pay now!") elif mes.text == "Order" and getStage(mes) == "cart": print("This is what is in user's cart:") cart = db[str(mes.chat.id)]['cart'] keys = list(cart.keys()) values = list(cart.values()) total = 0 bot.send_message(mes.chat.id, "This is your order: ") text = "" for i in range(0, len(cart)): print(values[i]['name'] + ", " + str(values[i]['amount']) + " pcs, " + str(int(values[i]['price']) * int(values[i]['amount'])) + "$") text = text + str( values[i]['name'] + ", " + str(values[i]['amount']) + " pcs, " + str(int(values[i]['price']) * int(values[i]['amount'])) + "$" + "\n") total += int(values[i]['price']) * int(values[i]['amount']) bot.send_message(mes.chat.id, text) bot.send_message( mes.chat.id, "Price: " + str(total) + "$. Would you like to pick up the order yourself, or get it by delivery?", reply_markup=newBut("I'll pick up myself", "Delivery", dict['home'])) elif mes.text == "I'll pick up myself" and getStage(mes) == "cart": bot.send_message( mes.chat.id, "Great! Address for pickup is " + usersdb.owner_Info['Store_Name'] + ", " + usersdb.owner_Info['Storage_Address']) setStage("payment", mes) elif mes.text == "Delivery" and getStage(mes) == "cart": setStage("delivery", mes) if userDB['city'] == "": bot.send_message( mes.chat.id, "Is this a correct delivery address: " + userDB['company'] + ", " + userDB['country'] + "?", reply_markup=newBut("Yes", "No", dict['home'])) else: bot.send_message(mes.chat.id, "Is this a correct delivery address: " + userDB['address'] + ", " + userDB['city'] + ", " + userDB['country'] + "?", reply_markup=newBut("Yes", "No")) elif mes.text == "Yes" and getStage(mes) == "delivery": try: makePayment(mes, [ LabeledPrice(label=mes.from_user.first_name + "'s order", amount=int(userDB['cartinfo']['total']) * 100) ]) ## Ask to pay it all :p except Exception as x: print(x) bot.send_message(mes.chat.id, "Some thing is wrong") if str(x).find("CURRENCY_TOTAL_AMOUNT_INVALID"): bot.send_message( mes.chat.id, "Our payment provider or Telegram rules restrict you from paying this much amount of money. Please go to contact to visit our website" ) elif mes.text == "No" and getStage(mes) == "delivery": bot.send_message( mes.chat.id, "I'll redirect you to settings. Complete it and come to \"Cart\" again!" ) setStage("settings", mes) elif mes.text == "Clear cart" and getStage(mes) == "cart": bot.send_message(mes.chat.id, "Would you really like to clear your cart?", reply_markup=newInlineCallback(("Yes", "clear"), ("No", "skip"))) elif mes.text == dict['orders']: if "orders" in userDB and len(userDB['orders']) > 0: setStage("orders", mes) else: bot.send_message( mes.chat.id, "Your order list is empty. Order something first!") setStage("MainMenu", mes) else: bot.send_message( mes.chat.id, "Unknown command. Use /help to see available commands") elif findId(mes) == False: setStage("firststart", mes)
menu_m = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) m1 = types.KeyboardButton("Хайтопы") m2 = types.KeyboardButton("Кроссовки") m3 = types.KeyboardButton("Кроссовки для тренировок") m4 = types.KeyboardButton("Коллабы и эксклюзивы") m5 = types.KeyboardButton("🔶Актуальные модели кроссовок") menu_m.row(m1, m2) menu_m.row(m3, m4) menu_m.row(m5) nazad1 = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True) n11 = types.KeyboardButton("🔙Назад") nazad1.row(n11) prices = [ LabeledPrice(label='Puma Thunder', amount=650000), LabeledPrice('Gift wrapping', 50000) ] price1 = [ LabeledPrice(label='Yeezy Boost 500', amount=1050000), LabeledPrice('Gift wrapping', 50000) ] price2 = [ LabeledPrice(label='NB me547', amount=400000), LabeledPrice('Gift wrapping', 50000) ] price3 = [ LabeledPrice(label='Raf Simons Ozweego', amount=800000), LabeledPrice('Gift wrapping', 50000) ]
def callback_inline(callback): try: if callback: chat_id = callback.from_user.id num = mark_up.call_value(chat_id, 'num') name_lot = mark_up.call_value(chat_id, 'name_lot') if callback.data == '+1': num += 1 mark_up.update_key(chat_id, 'num', num) mark_up.markup_num(num, callback, chat_id) if callback.data == '-1': num -= 1 if num < 1: num = 1 mark_up.update_key(chat_id, 'num', num) mark_up.markup_num(num, callback, chat_id) if callback.data == "корзина": dbworker.set_state(str(chat_id), '1') id_lot = mark_up.call_value(chat_id, 'id_lot') mark_up.gg_basket(callback, id_lot) mark_up.basket(chat_id, callback) if callback.data == 'удалить позицию': id_lot = mark_up.call_value(chat_id, 'id_lot') db_users.delete_lot(id_lot) if callback.inline_message_id == None: bot.edit_message_text( chat_id=chat_id, message_id=callback.message.message_id, text='Позиция удалена') else: bot.edit_message_text( inline_message_id=callback.inline_message_id, text='Позиция удалена') mark_up.check_basket(chat_id) if callback.data == 'очистить': mark_up.update_key(chat_id, 'dobavka', '') mark_up.update_key(chat_id, 'price_dobavka', 0.0) db_users.clear_basket(chat_id) bot.edit_message_text(chat_id=chat_id, message_id=callback.message.message_id, text='Ваша корзина очищена!', reply_markup=mark_up.add_lot()) if callback.data == 'выполнение': number_ship = mark_up.call_value(chat_id, 'number_ship') bot.send_message(-1001302729558, f'Заказ номер: #{number_ship}\n\n') bot.answer_callback_query( callback.id, "Ваш заказ в процессе приготовления!") if callback.data == 'сбросить': mark_up.update_key(chat_id, 'price_dobavka', 0.0) markup = mark_up.dobavki(chat_id) if callback.inline_message_id == None: bot.edit_message_text( chat_id=chat_id, message_id=callback.message.message_id, text= 'Добавки для напитков..\n(Можно выбрать один вариант)', reply_markup=markup) else: bot.edit_message_text( inline_message_id=callback.inline_message_id, text= 'Добавки для напитков..\n(Можно выбрать один вариант)', reply_markup=markup) if callback.data == 'добавки': markup = mark_up.dobavki(chat_id) dbworker.set_state(str(chat_id), 'dobavki') if callback.inline_message_id == None: bot.edit_message_text( chat_id=chat_id, message_id=callback.message.message_id, text= 'Добавки для напитков..\n(Можно выбрать один вариант)', reply_markup=markup) else: bot.edit_message_text( inline_message_id=callback.inline_message_id, text= 'Добавки для напитков..\n(Можно выбрать один вариант)', reply_markup=markup) if callback.data == 'комент': dbworker.set_state(str(chat_id), 'koment') if callback.inline_message_id == None: bot.edit_message_text( chat_id=chat_id, message_id=callback.message.message_id, text='Напишите комментарий к данной позиции:\n\n' f'{name_lot}') else: bot.edit_message_text( inline_message_id=callback.inline_message_id, text='Напишите комментарий к данной позиции:\n\n' f'{name_lot}', reply_markup=mark_up.back()) if callback.data == 'назад_инлайн': dbworker.set_state(str(chat_id), '1') num = mark_up.call_value(chat_id, 'num') markup = mark_up.num_markup2(callback, num) name_lot = mark_up.call_value(chat_id, 'name_lot') dobavka = mark_up.call_value(chat_id, 'dobavka') a = 'Ничего не выбрано' if dobavka == ' ' else dobavka price = mark_up.call_value(chat_id, 'price') pic = mark_up.call_value(chat_id, 'pic') size = mark_up.call_value(chat_id, 'size') price_dobavka = mark_up.call_value(chat_id, 'price_dobavka') price_dobavka = 0.0 if a == 'Ничего не выбрано' else price_dobavka bot.edit_message_text( inline_message_id=callback.inline_message_id, text=f"{name_lot}" f"\n{size}\n{price} ₽\n\n" f'Добавки:\n{a}' f'\n\nЦена {(str((float(price) * num) + (price_dobavka * num)))} ₽' f"[\xa0]({pic})", parse_mode='Markdown', reply_markup=markup) if callback.data == 'оформить': m = db_users.select_user(chat_id) lots = [] for lot in m: jlot = json.loads(lot[0]) tot_price = (jlot['num'] * (jlot['price'])) basket_lot = jlot['name_lot'] + ' ' + str( jlot['num']) + ' шт. ' + str( tot_price) + ' ₽\n ' + jlot['dobavka'] lots.append(basket_lot) string = '\n✅ '.join(lots) price = mark_up.call_value(chat_id, 'total_price') price1 = price * 100 prices = [ LabeledPrice(label=f'Стоимость услуги: ', amount=int(price1)) ] number_ship = f'{str(chat_id)} - {str(mark_up.random_pool())}' mark_up.update_key(chat_id, 'number_ship', number_ship) title = f'Заказ: {number_ship}' if price1 > 6569.0: bot.edit_message_text( chat_id=chat_id, message_id=callback.message.message_id, text=f"Вы перешли к оплате заказа") bot.send_invoice( callback.from_user.id, provider_token= '659414060:AAEWNZpJCVULIOoAdEP7oz8ZGoKJFfmW670', start_parameter='true', title=title, description=f'✅ {string}', invoice_payload='test', currency='RUB', prices=prices, need_phone_number=True, photo_url= 'http://www.tobystevens.co.uk/wp-content/uploads/2012/04/7.-SAMSUNG_COFFEE_CAFE_LOGO_GRAPHIC.jpg', photo_height=512, photo_width=512, photo_size=512, ) else: bot.edit_message_text( chat_id=callback.from_user.id, message_id=callback.message.message_id, text= 'К сожалению, Telegram обслуживает платежи не менее 1$\n' f'Сумма вашего заказа: {price} ₽\n' f'Добавьте в корзину позиции..', reply_markup=mark_up.add_lot()) if "Ближайщее время" == callback.data: markup = mark_up.time2(callback) mark_up.update_key(chat_id, 'time', callback.data) bot.edit_message_reply_markup(callback.from_user.id, callback.message.message_id, reply_markup=markup) if 'мин.' in callback.data: markup = mark_up.time2(callback) mark_up.update_key(chat_id, 'time', callback.data) bot.edit_message_reply_markup(callback.from_user.id, callback.message.message_id, reply_markup=markup) if callback.data == 'добавить': mark_up.update_key(chat_id, 'dobavka', ' ') bot.edit_message_text(chat_id=chat_id, message_id=callback.message.message_id, text='Выберите категорию', reply_markup=mark_up.catalog()) except Exception as e: print(e)
import json from wrappers import wrap_bridge, wrap_lesson, wrap_seq, wrap_feedback, seq_steps, les_steps bot = telebot.TeleBot(TOKEN) sequences = {item[1]: item[0] for item in Sequence.get_links()} sequences2 = {item[0]: item[1] for item in Sequence.get_links()} # working with pool pool = LessonsPool() upd = Updater(TOKEN) queue = upd.job_queue shipping_options = [ ShippingOption(id='instant', title='WorldWide Teleporter').add_price( LabeledPrice('Teleporter', 1000)), ShippingOption(id='pickup', title='Local pickup').add_price(LabeledPrice('Pickup', 300)) ] def process(upd, job): # should return dicts!!! print('checking...', ctime(time())) lessons = pool.pop_lessons() if lessons: for lesson in lessons: seq = Sequence(*[None for i in range(9)], key_id=lesson['_seq_id_']) for user_id in lesson['users']: bot.send_message(user_id,
from telebot.types import LabeledPrice from utils import timestamp, vault import json, TOKENS provider_token = TOKENS._PAYMENT_TOKEN_ # @BotFather -> Bot Settings -> Payments subscriptions = { 1: { "price": [LabeledPrice(label='Individual group', amount=8500)], "description": "\n1 license key to use in 1 group.\n\nPremium Benefits:\n + Zoom Integration\n + Custom Vocabulary Lists\n + 500 dictionary searches" }, 5: { "price": [LabeledPrice(label='Solo teacher', amount=30000)], "description": "\n5 licence keys to use in 5 groups.\n\nPremium Benefits:\n + Zoom Integration\n + Custom Vocabulary Lists\n + 500 dictionary searches", }, 15: { "price": [LabeledPrice(label='Small team', amount=110000)], "description": "\n15 license keys to use in 15 groups.\n\nPremium Benefits:\n + Zoom Integration\n + Custom Vocabulary Lists\n + 500 dictionary searches", } } def payment(bot, message, number_of_groups, edit_message_id): # bot.send_invoice(message.chat.id, title=f'{number_of_groups} key', # description=f"{subscriptions[number_of_groups]['description']}", # provider_token=provider_token, # currency='uah', # photo_height=0, # !=0/None or picture won't be shown # photo_width=0 ,
from Bot import ExistChecker, confirmation_handler from Database import get_user, update_user, PermissionChecker, get_admin_users from JsonGetter import JSON from telebot.types import LabeledPrice, PreCheckoutQuery from re import search is_has_permission = PermissionChecker() is_exist = ExistChecker() config_getter = JSON() _, _, PAYMENTS_PROVIDER_TOKEN, PROMOTION_SUBSCRIPTION_TITLE, PROMOTION_SUBSCRIPTION_DESCRIPTION, PRICE = config_getter() PROMOTION_SUBSCRIPTION_PRICE = LabeledPrice(label='Promotion subscribe price', amount=PRICE) REFFERAL_DICT = dict() def info_handler(bot, message): with open('info_message.txt', 'r', encoding='UTF-8') as file: info = file.read() bot.send_message(message.chat.id, info, parse_mode="html") # ---------------------------------------------------------------------------------------------------------------------- def pdt_response_content_handler(bot, message): def pdt_response_content_next_step_handler(content): def send_to_admins(content_message): for admin in get_admin_users(): bot.forward_message(admin.user_id, content_message.chat.id, content_message.message_id) confirmation_handler(bot, content, lambda: send_to_admins(content), 'Ответ отправлен!')
import os import mysql.connector import telebot from flask import Flask, request from telebot.types import Message, \ LabeledPrice, PreCheckoutQuery, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery PRICE = LabeledPrice(label='Продолжить курс', amount=9900) PAYMENTS_PROVIDER_TOKEN = '381764678:TEST:9009' TOKEN = '843095561:AAGHQNHS4aN0Pvs76DeGZ8Es8yfKL9113bE' bot = telebot.TeleBot(TOKEN) conn = mysql.connector.connect(host='db4free.net', database='test_bot', user='******', password='******') print('MySQL connected') cursor = conn.cursor() weekDays = [[0, 'понедельник'], [1, 'вторник'], [2, 'среда'], [3, 'четверг'], [4, 'пятница'], [5, 'суббота'], [6, 'воскресенье']] server = Flask(__name__) # Общие функции @bot.message_handler(commands=['start']) @bot.edited_message_handler(commands=['start'])
empty_basket = 'Корзина пуста!' clear_button = 'Очистить' pay_button = 'Оплатить' user_basket = 'Ваш заказ' ordering = 'Оформление заказа' successful_payment = 'Спасибо за покупку! Мы доставим ваш товар на сумму `{} {}` как можно быстрее! Оставайтесь на связи.' def set_shipping_option(id, title, *price): shipping_option = ShippingOption(id=id, title=title) shipping_option.add_price(*price) return shipping_option shipping_options = [ set_shipping_option('0', 'Тест', LabeledPrice('Доставка', 1000)), set_shipping_option('1', 'Праздничный день', LabeledPrice('Доставка', 40000)), set_shipping_option('2', 'В ночное время', LabeledPrice('Доставка', 40000)), set_shipping_option('3', 'Батайск', LabeledPrice('Доставка', 45000)), set_shipping_option('4', 'П. Рассвет', LabeledPrice('Доставка', 60000)), set_shipping_option('5', 'П. Солнечный', LabeledPrice('Доставка', 45000)), set_shipping_option('6', 'Аксай', LabeledPrice('Доставка', 40000)), set_shipping_option('7', 'Ростов-на-Дону', LabeledPrice('Доставка', 30000)), set_shipping_option('8', 'Чалтырь', LabeledPrice('Доставка', 45000)), set_shipping_option('9', 'Азов', LabeledPrice('Доставка', 80000)), set_shipping_option('10', 'Таганрог', LabeledPrice('Доставка', 150000)), set_shipping_option('11', 'Старочеркасск', LabeledPrice('Доставка', 50000)),
def text_handler(message): if userCheckStage(message.chat.id, 0): users[message.chat.id]['stage'] = 1 users[message.chat.id]['login'] = message.text bot.send_message(message.chat.id, 'Введите пароль:') elif userCheckStage(message.chat.id, 1): if logOn(users.get(message.chat.id).get('login'), message.text): keyboard = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) button1 = types.KeyboardButton(text="Обновить") button2 = types.KeyboardButton(text="Оплатить") keyboard.add(button1, button2) users[message.chat.id]['stage'] = 2 data = None for i in range(len(database)): print database[i][0] print users[message.chat.id] if database[i][0] == users[message.chat.id]['login']: data = database[i][2] break print unicode(data[0]) mess = 'ФИО\n' + str(data[0]) + '\nДата рождения\n' + str( data[1]) + '\nГород\n' + str(data[2]) + '\nАдрес\n' + str( data[3]) + '\nПотребление/месяц\n' + str( data[4]) + '\nСэкономлено\n' + str( data[5]) + '\nАвтооплата\n' + str(data[6]) bot.send_message(chat_id=message.chat.id, text=mess, reply_markup=keyboard) #bot.send_message(chat_id=message.chat.id, text=currentMsg, reply_markup = keyboard) else: users[message.chat.id]['stage'] = 0 bot.send_message(message.chat.id, 'Неверный логин или пароль') bot.send_message( message.chat.id, 'Здравствуйте! Пожалуйста, введите номер договора:') elif userCheckStage(message.chat.id, 2): if message.text == 'Обновить': keyboard = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) button1 = types.KeyboardButton(text="Обновить") button2 = types.KeyboardButton(text="Оплатить") keyboard.add(button1, button2) users[message.chat.id]['stage'] = 2 data = None for i in range(0, len(database)): if database[i][0] == users[message.chat.id]['login']: data = database[i][2] mess = 'ФИО\n' + str(data[0]) + '\nДата рождения\n' + str( data[1]) + '\nГород\n' + str(data[2]) + '\nАдрес\n' + str( data[3]) + '\nПотребление/месяц\n' + str( data[4]) + '\nСэкономлено\n' + str( data[5]) + '\nАвтооплата\n' + str(data[6]) bot.send_message(chat_id=message.chat.id, text=mess, reply_markup=keyboard) elif message.text == 'Оплатить': keyboard = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) button1 = types.KeyboardButton(text="Обновить") button2 = types.KeyboardButton(text="Оплатить") keyboard.add(button1, button2) users[message.chat.id]['stage'] = 2 data = None for i in range(0, len(database)): if database[i][0] == users[message.chat.id]['login']: data = database[i][2] global PROVIDER_TOKEN print int(data[7][0:-15]) bot.send_invoice( message.chat.id, title='Оплатить задолженность', description=data[7], provider_token=PROVIDER_TOKEN, currency='rub', photo_url= 'https://image.flaticon.com/icons/png/512/189/189093.png', photo_height=100, photo_width=100, photo_size=100, is_flexible=False, prices=[LabeledPrice(data[7], int(data[7][0:-15]))], start_parameter='ITEM', invoice_payload='item')
from telebot.types import LabeledPrice, ShippingOption pickup = ShippingOption(id='first', title='pickup') pickup.add_price(LabeledPrice('count', 100)) pickup = obj.to_json() print(obj) shipping_options = [pickup] print(shipping_options)
import telebot from telebot.types import LabeledPrice from telebot.types import ShippingOption token = '1234567890:AAAABBBBCCCCDDDDeeeeFFFFgggGHHHH' provider_token = '1234567890:TEST:AAAABBBBCCCCDDDD' # @BotFather -> Bot Settings -> Payments bot = telebot.TeleBot(token) # More about Payments: https://core.telegram.org/bots/payments prices = [ LabeledPrice(label='Working Time Machine', amount=5750), LabeledPrice('Gift wrapping', 500) ] shipping_options = [ ShippingOption(id='instant', title='WorldWide Teleporter').add_price( LabeledPrice('Teleporter', 1000)), ShippingOption(id='pickup', title='Local pickup').add_price(LabeledPrice('Pickup', 300)) ] @bot.message_handler(commands=['start']) def command_start(message): bot.send_message( message.chat.id, "Hello, I'm the demo merchant bot." " I can sell you a Time Machine." " Use /buy to order one, /terms for Terms and Conditions")
def confirm_menu(bot, telegram): try: text_for_confirm = DATES_FOR_CONFIRM.format( users[telegram].get('name'), users[telegram].get('phone'), users[telegram].get('street')) except Exception as e: return back_to_main_menu_del(bot, telegram) total = 1 prices_productes = [] if users[telegram].get('water'): text_for_confirm += BOTTLE_FOR_CONFIRM.format( users[telegram].get('water'), product_price.get('water'), (users[telegram].get('water') * int(product_price.get('water')))) total = users[telegram].get('water') * int(product_price.get('water')) prices_productes.append( LabeledPrice(label='water', amount=int(users[telegram].get('water')) * int(product_price.get('water')) * 100)) if users[telegram].get('pompa'): text_for_confirm += POMPA_FOR_CONFIRM.format( users[telegram].get('pompa'), product_price.get('pompa'), (users[telegram].get('pompa') * int(product_price.get('pompa')))) total += users[telegram].get('pompa') * int(product_price.get('pompa')) prices_productes.append( LabeledPrice(label='pompa', amount=int(users[telegram].get('pompa')) * int(product_price.get('pompa')) * 100)) if users[telegram].get('pompaEL'): text_for_confirm += POMPA_FOR_CONFIRM.format( users[telegram].get('pompaEL'), product_price.get('pompaEL'), (users[telegram].get('pompaEL') * int(product_price.get('pompaEL')))) total += users[telegram].get('pompaEL') * int( product_price.get('pompaEL')) prices_productes.append( LabeledPrice(label='pompaEL', amount=int(users[telegram].get('pompaEL')) * int(product_price.get('pompaEL')) * 100)) if users[telegram].get('culer'): text_for_confirm += CULER_FOR_CONFIRM.format( users[telegram].get('culer'), product_price.get('culer'), (users[telegram].get('culer') * int(product_price.get('culer')))) total += users[telegram].get('culer') * int(product_price.get('culer')) prices_productes.append( LabeledPrice(label='culer', amount=int(users[telegram].get('culer')) * int(product_price.get('culer')) * 100)) prices.update({telegram: prices_productes}) text_for_confirm += ITOG_CONFIRM.format(total) # if first: try: del_menu(bot, telegram, select_menu(telegram).get('message_id')) except Exception as e: print(e) send_menu(bot, telegram, text_for_confirm, 8)
import telebot from telebot import types from telebot.types import LabeledPrice, ShippingOption token = 'token' # @BotFather -> /newbot provider_token = 'Payments toekn' # @BotFather -> Bot Settings -> Payments bot = telebot.TeleBot(token) prices = [ LabeledPrice(label='Цена', amount=10000), LabeledPrice('Комиссия', 0) ] @bot.message_handler(commands=['start']) def start(message): menu = types.ReplyKeyboardMarkup(True, False) menu.row('Товары') menu.row('О боте') bot.send_message(message.chat.id, 'Привет , {name} \nВыберите пункт меню :.'.format( name=message.chat.first_name), reply_markup=menu) @bot.message_handler(content_types=['text']) def body(message): if message.text == 'Товары': bot.send_message( message.chat.id, "Сейчас вы получите счет." " Используйте этот номер карты : `4242 4242 4242 4242`",
def go(mes): userDB = db[str(mes.chat.id)] makePayment(mes, [ LabeledPrice(label=mes.from_user.first_name + "'s order", amount=int(userDB['cartinfo']['total'])) ])