Ejemplo n.º 1
0
def command_pay(message):
    log_text(message.chat.id, message.message_id, '--- DONATE --- ')
    if str(message.from_user.id) in BANNED:
        log_text(message.chat.id, message.message_id,
                 '--- BANIDO --- ' + message.text)
        bot.send_message(message.chat.id, msgs.banned)
        return 0
    send_clean_msg(bot, message.chat.id, msgs.donate_warn)
    bot.send_invoice(
        message.chat.id,
        title='RastreioBot',
        description='Para doar R$ 10, clique no botão abaixo.',
        provider_token=STRIPE,
        currency='BRL',
        prices=[types.LabeledPrice(label='Doar R$ 10', amount=1000)],
        start_parameter='doar10',
        invoice_payload='RastreioBot')
    bot.send_invoice(
        message.chat.id,
        title='RastreioBot',
        description='Para doar R$ 15, clique no botão abaixo.',
        provider_token=STRIPE,
        currency='BRL',
        prices=[types.LabeledPrice(label='Doar R$ 15', amount=1500)],
        start_parameter='doar15',
        invoice_payload='RastreioBot')
Ejemplo n.º 2
0
def to_up_ballance(m):
    if m.text == 'Вернуться':
        response_go(m)
    else:
        response_go(m)
        amount = int(m.text + '00')
        prices = [
            types.LabeledPrice(label='Пополнение вашего баланса',
                               amount=amount),
            types.LabeledPrice('Комиссия', 1500)
        ]
        fakeMoney = m.text
        bot.send_message(
            m.chat.id, 'Переведите ' + m.text +
            'руб. На qiwi кошелек: +79308162369. Код: 4221')
Ejemplo n.º 3
0
def otp(message):
    """
        Receives one-time-password
        Sends invoice payment
    """
    otp = message.text
    contract = utility.get(str(message.chat.id) + 'contract_id')
    url_otp_2 = f'https://web.ewa.ua/ewa/api/v9/contract/{contract}/otp?customer={otp}'
    r_otp_2 = requests.get(url_otp_2, headers=headers, cookies=cookies)
    print(r_otp_2)
    connection = sql.connect('DATABASE.sqlite')
    q = connection.cursor()
    q.execute("SELECT * from user WHERE id='%s'" % message.from_user.id)
    results = q.fetchall()
    connection.commit()
    q.close()
    connection.close()
    random_integer = random.randint(10000, 99999)
    payment = utility.get(str(message.chat.id) + 'tariff_payment')
    product_name = f"Travel insurance by - {utility.get(str(message.chat.id) + 'tariff_name')}"
    order = f'order{str(random_integer)}'
    amount = round(payment * 100.)
    bot.send_invoice(message.chat.id,
                     title=product_name,
                     description='Travel insurance policy',
                     invoice_payload=order,
                     provider_token=config.liqpay_token,
                     currency='UAH',
                     prices=[types.LabeledPrice(label='Полис', amount=amount)],
                     start_parameter='true',
                     photo_url='https://aic.com.ua/img/pyt3.jpg')
    utility.update({str(message.chat.id) + 'order': order})
Ejemplo n.º 4
0
def register(m):
    global user_state, navi_container, navi_naviaddress
    keyboard_hider = types.ReplyKeyboardRemove()
    navi_route = json.loads(
        get_naviadress(token, navi_container, navi_naviaddress))
    navi_desc = navi_route.get('result').get('description')
    if navi_desc != '' and navi_desc is not None:
        navi_desc = ast.literal_eval(navi_desc)
        money = navi_desc.get('event_money')

        if money != "" and int(money) != 0:
            bot.send_message(m.chat.id,
                             'Оплата за регистрацию',
                             reply_markup=keyboard_hider)
            bot.send_invoice(
                m.chat.id, 'Билет на мероприятие',
                'Посещение данного мероприятия платно. Пожалуйтса, оплатите билет.',
                '67192', payment_token, 'RUB',
                [types.LabeledPrice(label='Регистрация', amount=int(money))],
                'tme')

        else:
            user_state = 'registering'
            bot.send_message(m.chat.id,
                             "Введите имя:",
                             reply_markup=keyboard_hider)

    else:
        user_state = 'registering'
        bot.send_message(m.chat.id,
                         "Введите имя:",
                         reply_markup=keyboard_hider)
Ejemplo n.º 5
0
def command_pay(message):
    log_text(message.chat.id, message.message_id, '--- PAYMENT --- ')
    send_clean_msg(bot, message.chat.id, msgs.payment)
    bot.send_invoice(
        message.chat.id,
        title='RastreioBot - 6 meses',
        description=
        'Seis meses (183 dias) de rastreio de pacotes internacionais',
        provider_token=STRIPE,
        currency='BRL',
        prices=[types.LabeledPrice(label='Doar R$ 12', amount=1200)],
        start_parameter='doar12',
        invoice_payload='RastreioBot6meses')
    bot.send_invoice(
        message.chat.id,
        title='RastreioBot - 1 ano',
        description='Um ano (366 dias) de rastreio de pacotes internacionais',
        provider_token=STRIPE,
        currency='BRL',
        prices=[types.LabeledPrice(label='Doar R$ 20', amount=2000)],
        start_parameter='doar21',
        invoice_payload='RastreioBot1ano')
Ejemplo n.º 6
0
 def process_buy_command(self, message):
     if settings.BUY_TOKEN.split(':')[1] == 'TEST':
         self.bot.send_message(message.chat.id, 'Детали платежа')
         self.bot.send_invoice(
             message.chat.id,
             title=f'Карта клиента № {self.card_num}',
             description='Здесь надо указать реквизиты тестовой карты',
             provider_token=settings.BUY_TOKEN,
             currency='rub',
             # is_flexible=False,  # True если конечная цена зависит от способа доставки
             prices=[types.LabeledPrice(label='Руб.', amount=int(self.card_cost) * 100)],
             start_parameter='payment_of_client_card',
             invoice_payload='some-invoice-payload-for-our-internal-use'
         )
Ejemplo n.º 7
0
def send_payment_message(cid):
    prices = [
        types.LabeledPrice(label='Доступ к каналу Telegram',
                           amount=config.channel_acces_price)
    ]
    return bot.send_invoice(
        cid,
        title='Доступ к каналу Telegram',
        description='Оплатите месячную подписку на канал в Telegram.',
        provider_token=config.PROVIDER_TOKEN,
        currency='RUB',
        prices=prices,
        start_parameter='channel-access',
        invoice_payload='HAPPY FRIDAYS COUPON')
Ejemplo n.º 8
0
def Donate(message):
    # Telegram payment 
    bot.send_invoice(
        message.chat.id,
        title = 'Поддержать разработчика',
        description = 'Поддержав разработчика, Вы помогаете боту развиваться!',
        invoice_payload = 'something',
        provider_token = '401643678:TEST:bdb72775-f952-465d-9fea-c38185a832af',
        start_parameter = 'support', 
        currency = 'RUB',
        prices = [types.LabeledPrice(label = '100', amount = 100 * 100)] # amount: 100.00 => 10000 => 100 * 100
        )
    # Qiwi & YandexMoney payment 
    keyboard = Pay().paykey(
        sum = 100, 
        id = message.from_user.id, 
        qiwi = config.qiwi, 
        yandex = config.yandex
        )
    bot.send_message(message.chat.id, loc.support[db.Language(message.from_user.id)], reply_markup = keyboard)
Ejemplo n.º 9
0
def send_buy(query):
    order_list = []
    for prod_id, number in db.get_products_from_cart(query.message.chat.id):
        label, amount, about, url = db.get_product_by_id(prod_id)[0]
        for i in range(0, number):
            order_list.append(types.LabeledPrice(label=label, amount=amount))
    if len(order_list) == 0:
        bot.answer_callback_query(
            callback_query_id=query.id, text='У вас порожній кошик')
        return
    if len(order_list) > 10:
        bot.answer_callback_query(
            callback_query_id=query.id, text='У вас не має бути більше 10 товарів')
        return
    bot.send_invoice(chat_id=query.message.chat.id, title="Чек покупок",
                     description='Ваш чек',
                     provider_token=PAYMENT_TOKEN,
                     start_parameter='params',
                     currency='UAH',
                     prices=order_list,
                     invoice_payload='Good')
    bot.delete_message(chat_id=query.message.chat.id,
                       message_id=query.message.message_id)
Ejemplo n.º 10
0
def react(call):
    """ Handles all callback buttons """

    time.sleep(1)
    buttons = types.InlineKeyboardMarkup()
    user_info = db_find_value('tg_id', call.message.chat.id)

    if call.data == "rub":
        tariff_id = user_info['tariff']
        msg = messages.rub_text

        # If user has active tariff, send button allowing to extend his current tariff
        # Temporarily off
        if False and tariff_id in ['1', '2', '3', '22', '23']:
            buttons.add(
                types.InlineKeyboardButton(text="Продлить текущий тариф",
                                           callback_data=f"Р-{tariff_id}"))
            msg += f"\n\nВаш текущий тариф: {tariff_id}"
            bot.send_message(call.message.chat.id,
                             msg,
                             parse_mode='Markdown',
                             reply_markup=buttons)
        else:
            bot.send_message(call.message.chat.id, msg, parse_mode='Markdown')

    elif call.data == "yuan":
        bot.send_message(call.message.chat.id,
                         messages.yuan_text,
                         parse_mode='Markdown')
    elif call.data == "install":
        bot.send_message(call.message.chat.id, messages.first_install)
    elif call.data == "other":
        bot.send_message(call.message.chat.id,
                         messages.support,
                         parse_mode='Markdown')
    elif call.data == "market":
        open_dialogue("tg_id", call.message.chat.id)
        bot.send_message(
            call.message.chat.id,
            'Здравствуйте! Укажите, пожалуйста, продукт и вопросы по нему')
    elif call.data == "urgent":
        support(call.message, urgent=True)
    elif call.data == "sup":
        support(call.message)

    # If user rated quality less than 5 and pushed feedback button, open dialogue for one message only
    elif call.data == "get_better":
        update_clients(["tg_id", call.message.chat.id],
                       ["state", "ONE MESSAGE"],
                       ["review_time", f"{int(time.time())}"])
        bot.send_message(call.message.chat.id, messages.get_better)

    elif call.data == "pay":
        buttons.add(
            types.InlineKeyboardButton(text="В рублях или в гривнах",
                                       callback_data="rub"))
        buttons.add(
            types.InlineKeyboardButton(text="В юанях", callback_data="yuan"))
        buttons.add(
            types.InlineKeyboardButton(
                text="\U00002753 Связаться с поддержкой", callback_data="sup"))
        bot.send_message(call.message.chat.id,
                         messages.pay_type,
                         reply_markup=buttons)

    elif call.data in ["1", "2", "3", "4", "5"]:

        # User has already rated
        if get_info("rate", "tg_id", call.message.chat.id) != "0":
            bot.send_message(call.message.chat.id,
                             "Вы уже поставили оценку, спасибо!")
            return

        rating = call.data

        # Ask user to make review if he gave the highest rate
        if rating == "5":
            buttons.add(
                types.InlineKeyboardButton(text="\U0001F49B Оставить отзыв",
                                           url=config.review_link))
            bot.send_message(
                call.message.chat.id,
                "Если вам понравился наш сервис - оставьте отзыв, "
                "и мы предоставим вам 10 дней бесплатного VPN!\n\n"
                "_Когда оставите отзыв свяжитесь с нами для получения бонуса_",
                reply_markup=buttons,
                parse_mode='Markdown')
        # Ask user to write feedback
        else:
            buttons.add(
                types.InlineKeyboardButton(
                    text="\U0001F4A1 Оставить пожелание",
                    callback_data="get_better"))
            bot.send_message(call.message.chat.id,
                             "Мы можем что-то улучшить в обслуживании?",
                             reply_markup=buttons)

        bot.send_message(
            config.group_id,
            f"Клиент `{call.message.chat.id}` поставил вам {rating}",
            parse_mode='Markdown')
        update_clients(["tg_id", call.message.chat.id], ["rate", rating])

    # User chose tariff he wants to buy, send him buttons to choose tariff duration in days (ascending order)
    # Temporarily off
    elif False and re.fullmatch(r'[РЮ]-[123]+', call.data):
        currency, tariff_id = call.data.split('-')
        tariffs_list = get_tariffs(['tariff', tariff_id],
                                   ['currency', currency])
        for price, tariff_id, days, currency, desc in sorted(
                tariffs_list, key=lambda x: int(x[2])):
            # Telegram does not support prices lower than 60 rub.
            if int(price) < 60:
                continue
            # Choose correct form of 'день' word
            if days[-1] == '1':
                day_word = 'день'
            elif days[-1] in '234':
                day_word = 'дня'
            else:
                day_word = 'дней'
            buttons.add(
                types.InlineKeyboardButton(
                    text=f"{days} {day_word}",
                    callback_data=f"{currency}-{tariff_id}-{days}"))
        bot.send_message(
            call.message.chat.id,
            f"Выберите, на сколько дней вы хотите продлить тариф {tariff_id}",
            reply_markup=buttons)

    # User chose tariff duration in days, send him payment button
    # Temporarily off
    elif False and re.fullmatch(r'[РЮ]-[123]+-[0-9]+', call.data):
        currency, tariff_id, days = call.data.split('-')
        specific_tariff = get_tariffs(['tariff', tariff_id],
                                      ['currency', currency],
                                      ['days', days])[0]
        price = int(specific_tariff[0])
        prices = [
            types.LabeledPrice(label=f'Тариф {tariff_id} на {days} дней',
                               amount=price * 100)
        ]
        bot.send_invoice(call.message.chat.id,
                         title=f"Тариф {tariff_id}",
                         description='Plati',
                         provider_token=config.pay_token,
                         currency='rub',
                         prices=prices,
                         start_parameter='payment',
                         invoice_payload='HAPPY FRIDAYS COUPON')
Ejemplo n.º 11
0
from telebot import types
from Messages import *
from telebot.types import LabeledPrice, ShippingOption
import logging

logging.basicConfig(format=u'%(filename)+13s [ LINE:%(lineno)-4s] %(levelname)-8s [%(asctime)s] %(message)s',
                    level=logging.INFO)


chars = 'abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'

access_token = '1235052627:AAFhn3Toc2uotGtyy4InMAkEou-xcD9rPu0'
bot = telebot.TeleBot(access_token)

PRICES = [
    types.LabeledPrice(label='Кейсы до 150р', amount=4900)
]
PRICES1 = [
    types.LabeledPrice(label='Кейсы до 500р', amount=9900)
]
PRICES2 = [
    types.LabeledPrice(label='Кейсы до 700р', amount=12900)
]
PRICES3 = [
    types.LabeledPrice(label='Кейсы до 1500р', amount=29900)
]
PRICES4 = [
    types.LabeledPrice(label='Кейсы до 3000р', amount=99900)
]
PRICES5 = [
    types.LabeledPrice(label='Случайный нож', amount=299900)
Ejemplo n.º 12
0
 def pay(message):
     if message.text == '⬅️ Отменить заявку':
         start_bot(message)
     elif message.text == '💳Оплата онлайн':
         user = Users.objects.get(name=message.chat.id)
         user.status = '1'
         user.save(update_fields=['status'])
         price = []
         count = 1
         all_sum = 0
         with open('order_number.json', 'r') as f:
             number = json.load(f)['number']
         number_order = json.dumps({"number": number + 1})
         with open('order_number.json', 'w') as f:
             f.write(number_order)
         text = f'*Заказ № {number}*\n'
         text_admin = f'❗️ *Вам пришел заказ № {number}*\n\n'
         if user.delivery == '🏃 Заберу сам':
             text_admin += f'👤Данные покупателя\n{user.nickname}, ' \
                    f'{user.mobile}\n📦Тип доставки:\n{user.delivery}\n\n-----\n🛒Товары:\n'
         else:
             text_admin += f'👤Данные покупателя\n{user.nickname}, ' \
                    f'{user.mobile}\n📦Тип доставки:\n{user.delivery}\n' \
                    f'адрес доставки:{user.address}\n\n-----\n🛒Товары:\n'
         for i in user.basket_set.all():
             position_sum = i.count * i.price
             all_sum += position_sum
             price.append(
                 types.LabeledPrice(
                     label=f'позиция {count}: {i.count}шт. x {i.price}₽',
                     amount=int(position_sum * 100)))
             text += f'*позиция {count}* - {i.name_product}\n{i.count} x {i.price} = {position_sum} ₽\n'
             text_admin += f'*позиция {count}* - {i.name_product}\n{i.count} x {i.price} = {position_sum} ₽\n'
             count += 1
         if user.delivery == '🚗 Привезти':
             if all_sum < 2000:
                 price.append(
                     types.LabeledPrice(label=f'Доставка 300 ₽',
                                        amount=30000))
                 text += '\n+ _Доставка 300 ₽_'
                 text_admin += f'\n-----\n*Доставка:* 200 ₽\n✅*ОПЛАЧЕНО* {all_sum + 300} ₽'
             else:
                 text_admin += f'\n-----\n✅*ОПЛАЧЕНО* {all_sum} ₽'
         else:
             text_admin += f'\n-----\n✅*ОПЛАЧЕНО* {all_sum} ₽'
         Orders.objects.create(number_order=number,
                               user_order=text_admin)
         user.basket_set.all().delete()
         bot.send_message(message.chat.id,
                          text,
                          parse_mode='markdown',
                          reply_markup=start_menu())
         bot.send_invoice(chat_id=message.chat.id,
                          title=f'Заказ № {number}',
                          description=f'Оплата заказа № {number}',
                          provider_token=PAYMENTS_PROVIDER_TOKEN,
                          currency='RUB',
                          is_flexible=False,
                          prices=price,
                          start_parameter='time-machine-example',
                          invoice_payload='{0}'.format(number))
     elif message.text == '💵Оплата при получении':
         user = Users.objects.get(name=message.chat.id)
         user.status = 'q'
         user.save(update_fields=['status'])
         with open('order_number.json', 'r') as f:
             number = json.load(f)['number']
         text = f'*Заказ № {number}*\n\n'
         keyboard = types.ReplyKeyboardMarkup(True, False)
         keyboard.row('✅ Подтвердить и отправить')
         keyboard.row('⬅️ Отменить заявку')
         all_sum = 0
         for i in user.basket_set.all():
             position_sum = i.count * i.price
             text += f'*{i.name_product}*\n{i.count} x {i.price} = {position_sum} ₽\n'
             all_sum += position_sum
         if user.delivery == '🚗 Привезти':
             if all_sum < 2000:
                 text += '+_Доставка: 300 ₽_'
                 all_sum += 300
         text += f'\n\n*Итого:* {all_sum} ₽'
         bot.send_message(message.chat.id,
                          text,
                          parse_mode='markdown',
                          reply_markup=keyboard)
     else:
         bot.send_message(message.chat.id, 'Выберите способ оплаты')
Ejemplo n.º 13
0
Archivo: bot.py Proyecto: Karto4an/shop
name_keyboard_choise_1 = "1st category"
name_keyboard_choise_2 = "2nd category"
name_inlinekeyboard_versionchoise_1 = "Toys"
name_inlinekeyboard_versionchoise_2 = "Sculptures"
name_inlinekeyboard_callback_1 = "invoice_windowshome"
name_inlinekeyboard_callback_2 = "invoice_windowspro"
name_inlinekeyboard_versionchoise_3 = "Arts"
name_inlinekeyboard_versionchoise_4 = "All for art"
name_inlinekeyboard_callback_3 = "invoice_officehome"
name_inlinekeyboard_callback_4 = "invoice_officepro"

price_1_title = "Toy"
price_1_description = "Toy"
price_1_currency = "uah"

price_1 = types.LabeledPrice(label="Toy", amount=10000)

price_2_title = "Sculpture"
price_2_description = "Sculpture"
price_2_currency = "uah"

price_2 = types.LabeledPrice(label="Sculpture", amount=14000)

price_3_title = "Painting"
price_3_description = "Painting"
price_3_currency = "uah"

price_3 = types.LabeledPrice(label="Painting", amount=8000)

price_4_title = "Goods for art"
price_4_description = "Goods for art"
Ejemplo n.º 14
0
def handle_command_adminwindow(message):
    global selected
    global stringList1
    if len(selected) == 1:

        chatid = message.chat.id

        markup = types.InlineKeyboardMarkup(row_width=3)

        markup.add(
            types.InlineKeyboardButton(text="Order",
                                       callback_data="['value', '" + "Order" +
                                       "', '" + "Order" + "']"),
            types.InlineKeyboardButton(text="Opening hours",
                                       callback_data="['value', '" +
                                       "Opening hours" + "', '" + "Hours" +
                                       "']"),
            types.InlineKeyboardButton(text="Menu",
                                       callback_data="['value', '" + "Menu" +
                                       "', '" + "Menu" + "']"))

        temp = {
            chatid: {
                'check': 0,
                'name': '',
                'phone': '',
                'final': '',
                'price': 0,
                'oderid': 0,
                'stringList1': {},
                'cardno': '',
                'email': '',
                'Month': '',
                'Year': '',
                'cvv': ''
            }
        }
        bot.send_message(
            chat_id=message.chat.id,
            text="Hello ! Welcome ! I am your personal virtual assistance",
            reply_markup=markup,
            parse_mode='HTML')
        selected.update(temp)
    else:
        try:
            if selected[message.chat.id]['check'] == 1:
                selected[message.chat.id]['name'] = message.json["text"]
                bot.send_message(message.chat.id,
                                 'Please Enter Your Phone Number')
                selected[message.chat.id]['check'] = 2

            elif selected[message.chat.id]['check'] == 2:
                selected[message.chat.id]['phone'] = str(message.json["text"])
                bot.send_message(message.chat.id, 'Please Enter Your Email')
                selected[message.chat.id]['check'] = 3
            elif selected[message.chat.id]['check'] == 3:
                selected[message.chat.id]['email'] = str(message.json["text"])
                prices = [
                    types.LabeledPrice(
                        label='Pizza Bot',
                        amount=(int)(selected[message.chat.id]['price']) *
                        100),
                ]
                m = bot.send_invoice(
                    chat_id=message.chat.id,
                    title='Pizza',
                    description=selected[message.chat.id]['final'],
                    provider_token=PAYMENTS_PROVIDER_TOKEN,
                    currency='usd',
                    photo_url=
                    'https://media-cdn.tripadvisor.com/media/photo-s/0a/c0/7c/98/best-pizza-in-lahore.jpg',
                    photo_height=None,  # !=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='pizza',
                    invoice_payload='HAPPY')
                print(m)
                m = str(m).split("'pay': ", 1)[1].split('}', 1)[0]
                if m == 'True':
                    print("Payment Successfull")
                else:
                    print('ERror in payment')

                ######## Absar add here ###########
                #bot.send_message(message.chat.id,'Please Enter Your Phone Number')
        except:
            chatid = message.chat.id

            markup = types.InlineKeyboardMarkup(row_width=3)

            markup.add(
                types.InlineKeyboardButton(text="Order",
                                           callback_data="['value', '" +
                                           "Order" + "', '" + "Order" + "']"),
                types.InlineKeyboardButton(text="Opening hours",
                                           callback_data="['value', '" +
                                           "Opening hours" + "', '" + "Hours" +
                                           "']"),
                types.InlineKeyboardButton(text="Menu",
                                           callback_data="['value', '" +
                                           "Menu" + "', '" + "Menu" + "']"))

            temp = {
                chatid: {
                    'check': 0,
                    'name': '',
                    'phone': '',
                    'final': '',
                    'price': 0,
                    'oderid': 0,
                    'stringList1': {},
                    'cardno': '',
                    'email': '',
                    'Month': '',
                    'Year': '',
                    'cvv': ''
                }
            }
            bot.send_message(
                chat_id=message.chat.id,
                text="Hello ! Welcome ! I am your personal virtual assistance",
                reply_markup=markup,
                parse_mode='HTML')
            selected.update(temp)
Ejemplo n.º 15
0
def handle_query(message):
    chat_id = message.message.chat.id
    message_id = message.message.message_id
    data = message.data
    global last_data
    global open_basket
    global menu_id

    # Храним информацию только о 50 последних пользователях
    if len(last_data) > 50:
        last_data = {}
    if len(open_basket) > 50:
        open_basket = {}

    # Проверка что пользователь не нажал две клавиши на одном этапе меню
    if chat_id in last_data.keys() and data == last_data[chat_id]:
        return
    last_data[chat_id] = data
    print(chat_id, ':', data)

    # Список торговых центров
    if data == 'start':
        menu_id[chat_id] = message_id  # Запоминаем номер сообщения с меню
        bot.edit_message_text(chat_id=chat_id,
                              message_id=message_id,
                              text='Список торговых центров',
                              reply_markup=makeKeyboard_TC(DB.TC_list()),
                              parse_mode='HTML')
    # Список фудкортов
    elif data.startswith('{"TC"'):
        menu_id[chat_id] = message_id  # Запоминаем номер сообщения с меню
        TC_name = json.loads(data)['TC']

        bot.edit_message_text(chat_id=chat_id,
                              message_id=message_id,
                              text=TC_name + '\nСписок фудкортов',
                              reply_markup=makeKeyboard_FC(
                                  DB.FC_list(TC_name)),
                              parse_mode='HTML')
    # Список ресторанов
    elif data.startswith('{"FC"'):
        menu_id[chat_id] = message_id  # Запоминаем номер сообщения с меню
        data = json.loads(data)

        TC_name = data['FC'][1]  # TC_name
        FC_name = data['FC'][0]  # FC_name
        if FC_name:
            txt = f'{TC_name}\n{FC_name}\n'
        else:
            txt = f'{TC_name}\n'
        bot.edit_message_text(chat_id=chat_id,
                              message_id=message_id,
                              text=txt + 'Список ресторанов',
                              reply_markup=makeKeyboard_rest(
                                  DB.rest_list(TC_name=TC_name, FC=FC_name)),
                              parse_mode='HTML')

    # Ктегории ресторана
    elif data.startswith('{"rest_id"'):
        menu_id[chat_id] = message_id  # Запоминаем номер сообщения с меню
        data = json.loads(data)
        rest_id = data['rest_id']
        categories = DB.categories_rest(rest_id=rest_id)
        FC = categories["FC"]
        if FC:
            txt = f'{categories["TC_name"]}\n{FC}\n{categories["rest_name"]}\n'
        else:
            txt = f'{categories["TC_name"]}\n{categories["rest_name"]}\n'
        bot.edit_message_text(chat_id=chat_id,
                              message_id=message_id,
                              text=txt + 'Категории',
                              reply_markup=makeKeyboard_categories(categories),
                              parse_mode='HTML')

    # Меню ресторана
    elif data.startswith('{"cat"'):
        menu_id[chat_id] = message_id  # Запоминаем номер сообщения с меню
        data = json.loads(data)
        rest_id = data['cat'][1]
        category = data['cat'][0]
        menu = DB.menu_rest(rest_id=rest_id, category=category)
        rest_name = menu['rest_name']

        photo = data['cat'][2]
        if not photo:
            bot.edit_message_text(chat_id=chat_id,
                                  message_id=message_id,
                                  text=rest_name + '\nМеню\n' + category,
                                  reply_markup=makeKeyboard_menu(menu),
                                  parse_mode='HTML')
        else:
            bot.send_message(chat_id=chat_id,
                             text=rest_name + '\nМеню\n' + category,
                             reply_markup=makeKeyboard_menu(menu),
                             parse_mode='HTML')
            # Удаление старого сообщения
            bot.delete_message(chat_id=chat_id, message_id=message_id)

    # Список товаров (меню рестрана)
    elif data.startswith('{"menu"'):
        menu_id[chat_id] = message_id  # Запоминаем номер сообщения с меню
        data = json.loads(data)
        rest_id = data['menu'][2]
        category = data['menu'][1]
        index = data['menu'][0]

        # Отправка изображния
        menu = DB.menu_rest(rest_id=rest_id, category=category)
        try:
            img = open(menu['menu'][index]['img'], 'rb')
        except:
            print('Image not found:', menu['menu'][index]['img'])
            img = open(error_img_path, 'rb')

        bot.send_photo(chat_id=chat_id,
                       photo=img,
                       reply_markup=makeKeyboard_food(menu, index))

        # Удаление старого сообщения
        bot.delete_message(chat_id=chat_id, message_id=message_id)

        # Если корзина открыта, закрываем
        if chat_id in open_basket.keys() and open_basket[chat_id]:
            bot.delete_message(chat_id=chat_id,
                               message_id=open_basket[chat_id])
            open_basket[chat_id] = False

    # Взаимодействие с товаром
    elif data.startswith('{"food'):
        # '{"food": [rest_id, category, index, action]}'
        data = json.loads(data)['food']
        rest_id = data[0]
        category = data[1]
        index = data[2]
        action = data[3]
        menu = DB.menu_rest(rest_id=rest_id, category=category)

        if '-' in action:
            quantity = int(data[3][1:])
            if quantity == 1:
                return
            quantity -= 1
            bot.edit_message_reply_markup(chat_id=chat_id,
                                          message_id=message_id,
                                          reply_markup=makeKeyboard_food(
                                              menu, index, quantity=quantity))
        elif '+' in action:
            quantity = int(data[3][1:])
            quantity += 1
            bot.edit_message_reply_markup(chat_id=chat_id,
                                          message_id=message_id,
                                          reply_markup=makeKeyboard_food(
                                              menu, index, quantity=quantity))
        elif 'sruct' in action:

            bot.answer_callback_query(callback_query_id=message.id,
                                      show_alert=True,
                                      text='Состав:\n' +
                                      menu['menu'][index]['composition'])
        elif 'add' in action:
            rest_name = menu['rest_name']

            # Проверка если начали добавлять товары другого ресторана
            basket = read_basket(chat_id)
            update_text = ''
            if basket and int(rest_id) != int(basket[0]['rest_id']):
                del_basket(chat_id)
                update_text = 'Корзина обновлена '

            food_name = menu['menu'][index]['name']
            prise = menu['menu'][index]['price']
            quantity = int(data[3][3:])

            add_basket(chat_id, food_name, quantity, prise, rest_id=rest_id)

            bot.answer_callback_query(
                callback_query_id=message.id,
                show_alert=False,
                text=
                f'{update_text}В корзину добавлено {food_name} {quantity} шт.')

            bot.send_message(chat_id=chat_id,
                             text=rest_name + '\nМеню',
                             reply_markup=makeKeyboard_menu(menu),
                             parse_mode='HTML')

            menu_id[
                chat_id] = message_id + 1  # Запоминаем номер сообщения с меню

            # Удаление старого сообщения
            bot.delete_message(chat_id=chat_id, message_id=message_id)

            # Если корзина открыта, закрываем
            if chat_id in open_basket.keys() and open_basket[chat_id]:
                bot.delete_message(chat_id=chat_id,
                                   message_id=open_basket[chat_id])
                open_basket[chat_id] = False

    # Взаимодействие с корзиной
    elif data.startswith('{"basket"'):
        data = json.loads(data)
        action = data['basket']
        if action == 'close':
            bot.delete_message(chat_id=chat_id, message_id=message_id)
            open_basket[chat_id] = False
        elif 'clear' in action:
            del_basket(chat_id)
            bot.answer_callback_query(callback_query_id=message.id,
                                      show_alert=False,
                                      text='Корзина очищена')
            bot.delete_message(chat_id=chat_id, message_id=message_id)
            open_basket[chat_id] = False

        elif 'change' in action:
            basket = read_basket(str(chat_id))
            bot.edit_message_text(chat_id=chat_id,
                                  message_id=message_id,
                                  text='<b>Корзина</b> (изменение)',
                                  reply_markup=makeKeyboard_changeBasket(
                                      basket=basket, chat_id=chat_id),
                                  parse_mode='HTML')
    # Изменение корзины
    elif data.startswith('{"change"'):
        # {"change": ["Шашлык куриный", "+2"]}
        data = json.loads(data)['change']

        # Кнопка сохранить
        if data == 'save':
            save_basket(chat_id)
            items = read_basket(str(chat_id))

            if not items:
                bot.edit_message_text(
                    chat_id=chat_id,
                    message_id=message_id,
                    text='<b>Корзина пуста</b>',
                    reply_markup=makeKeyboard_basket(clear=True),
                    parse_mode='HTML')
                return

            basket_text, amount, basket_info = makeBasket(items)
            rest_id = items[0]['rest_id']
            restaurant = DB.categories_rest(rest_id)
            rest_name = restaurant['rest_name']

            bot.edit_message_text(
                chat_id=chat_id,
                message_id=message_id,
                text=
                f'<b>Корзина</b>\n{rest_name}\n\n<i>{basket_text}</i>\nИтого: <i>{amount} руб.</i>',
                reply_markup=makeKeyboard_basket(),
                parse_mode='HTML')
            return

        # Кнопки - и +
        food_name = data[0]
        action = data[1]
        if '-' in action:
            quantity = int(data[1][1:])
            if quantity == 0:
                return
            quantity = -1
            add_basket(chat_id=chat_id, food_name=food_name, quantity=quantity)
            basket = read_basket(chat_id)
            bot.edit_message_reply_markup(
                chat_id=chat_id,
                message_id=message_id,
                reply_markup=makeKeyboard_changeBasket(basket,
                                                       chat_id=chat_id))
        elif '+' in action:
            quantity = 1
            add_basket(chat_id=chat_id, food_name=food_name, quantity=quantity)
            basket = read_basket(chat_id)
            bot.edit_message_reply_markup(
                chat_id=chat_id,
                message_id=message_id,
                reply_markup=makeKeyboard_changeBasket(basket,
                                                       chat_id=chat_id))
    # Формирование заказа
    elif data == 'pay':
        bot.delete_message(chat_id=chat_id, message_id=message_id)

        markup = types.InlineKeyboardMarkup()
        markup.add(
            types.InlineKeyboardButton(text='Оплатить', pay=True),
            types.InlineKeyboardButton(text='Удалить',
                                       callback_data='del_order_or_receipt'))

        items = read_basket(str(chat_id))
        basket_text, amount, basket_info = makeBasket(items)
        rest_id = items[0]['rest_id']
        restaurant = DB.categories_rest(rest_id)
        rest_name = restaurant['rest_name']
        print(rest_name)

        prices = []
        for i in basket_info:
            food_name = i['food_name']
            quantity = i['quantity']
            price = i['price']
            prices.append(
                types.LabeledPrice(label=food_name + ' ' + str(quantity) +
                                   ' шт.',
                                   amount=price * quantity * 100))
        print(items)
        bot.send_invoice(chat_id=chat_id,
                         title=rest_name,
                         description=basket_text,
                         invoice_payload={"bla": "bla"},
                         provider_token=PROVIDER_TOKEN,
                         start_parameter="mybot",
                         currency="RUB",
                         prices=prices,
                         reply_markup=markup)

        open_basket[chat_id] = False

    # Удаление заказа или чека
    elif data == 'del_order_or_receipt':
        bot.delete_message(chat_id=chat_id, message_id=message_id)
Ejemplo n.º 16
0
from config import DEVTOKEN as report_token
from config import TESTTOKEN as debug_token
from prawcore.exceptions import Forbidden
from telebot import types
import praw
import random
import telebot
import json

#https://surik00.gitbooks.io/aiogram-lessons/content/chapter4.html

token = debug_token
bot = telebot.TeleBot(token)
logger = telebot.TeleBot(report_token)

PRICE = types.LabeledPrice(label='Support us', amount=10000)


@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
    if call.message:
        if call.data == 'nsfw_y':
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text="Displaying NSFW")
            core.NSFW(str(call.message.chat.id), True)
        if call.data == 'nsfw_n':
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  text="NSFW is not displaying")
            core.NSFW(str(call.message.chat.id), False)
Ejemplo n.º 17
0
token = ""
liqpay_token = ""
bot = telebot.TeleBot(token)

#for example
#also can use db
items = {
	"coffee": {
		"description": "Robust coffee",
	},
	"tea": {
		"description": "Robust tea",
	}
}
prices = {
	"coffee": [types.LabeledPrice(label="coffee", amount=1000)],
	"tea": [types.LabeledPrice(label="tea", amount=2000)],
}


#start
#and help
@bot.message_handler(commands=["start", "help"])
def start_command(message):
	bot.send_message(message.chat.id, "Hi!\nI am demo shop bot!\nYou can see menu using '/menu'")


#main menu
#show items and other
@bot.message_handler(commands=["menu"])
def menu_command(message):