Beispiel #1
0
def handle_menu(update: Update, context: CallbackContext):
    query = update.callback_query
    query.answer()
    query.message.delete()
    if query.data == 'Корзина':
        handle_cart(update, context)
        return "HANDLE_DESCRIPTION"

    access_token = get_access_token(redis_conn)
    product_info = get_element_by_id(access_token, query.data)
    image_id = product_info['relationships']['main_image']['data']['id']
    text_mess = format_description(product_info)
    image_link = get_image_link(access_token, image_id)['data']['link']['href']

    keyboard = [[InlineKeyboardButton('В меню', callback_data='В меню')],
                [
                    InlineKeyboardButton('Положить в корзину',
                                         callback_data=query.data)
                ]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    context.bot.send_photo(chat_id=update.effective_user.id,
                           photo=image_link,
                           caption=text_mess,
                           reply_markup=reply_markup)['message_id']
    return "HANDLE_DESCRIPTION"
Beispiel #2
0
def handle_description(sender_id, payload):
    """Отправляет по хэндлам"""
    if not payload:
        title, payload_id = None, None
    else:
        title = payload['title']
        payload_id = payload['payload']
    access_token = get_access_token(redis_conn)

    if title == 'Корзина':
        handle_cart(sender_id, payload_id)
        return "HANDLE_DESCRIPTION"

    elif title in ['Оплатить', 'Доставка', 'Самовывоз']:
        send_message(sender_id, "Эта функция пока не доступна!")
        return "HANDLE_WAITING"

    elif title == 'Убрать из корзины':
        delete_from_cart(access_token, payload_id, sender_id)
        handle_cart(sender_id, payload_id)
        return "HANDLE_DESCRIPTION"

    elif title in ['Положить в корзину', 'Добавить еще одну']:
        send_message(sender_id, 'Пицца добавлена!')
        add_to_cart(access_token, 1, payload_id, sender_id)
        return 'HANDLE_DESCRIPTION'

    elif title:
        if 'В меню' in title:  # Facebook почему-то делает запросы лишнии из-за этого тут возникают ошибки
            handle_start(sender_id, payload_id)
            return 'HANDLE_DESCRIPTION'

    return 'HANDLE_DESCRIPTION'
Beispiel #3
0
def handle_cart(update: Update, context: CallbackContext):
    """Показывает корзину"""
    access_token = get_access_token(redis_conn)
    chat_id = update.effective_user.id
    cart = get_cart(access_token, f"tg-{chat_id}")

    keyboard = []
    keyboard.append([InlineKeyboardButton('В меню', callback_data='В меню')])

    if not cart['data']:
        text_message = 'Ваша корзина пуста :C'
        reply_markup = InlineKeyboardMarkup(keyboard)
        context.bot.send_message(text=text_message,
                                 chat_id=chat_id,
                                 reply_markup=reply_markup)
        return "HANDLE_DESCRIPTION"

    text_message, pizza_names, pizza_ids = format_cart(cart, context)
    for name_pizza, id_pizza in zip(pizza_names, pizza_ids):
        keyboard.append([
            InlineKeyboardButton(f'Убрать из корзины {name_pizza}',
                                 callback_data=f'Убрать|{id_pizza}')
        ])

    keyboard.append(
        [InlineKeyboardButton('Оплатить', callback_data='Оплатить')])
    reply_markup = InlineKeyboardMarkup(keyboard)
    context.bot.send_message(text=text_message,
                             chat_id=chat_id,
                             reply_markup=reply_markup)
    return "HANDLE_DESCRIPTION"
Beispiel #4
0
def handle_description(update: Update, context: CallbackContext):
    """Отправляет по хэндлам"""
    query = update.callback_query
    query.answer()
    access_token = get_access_token(redis_conn)
    chat_id = update.effective_user.id

    if query.data == 'В меню':
        start(update, context)
        query.message.delete()
        return 'HANDLE_MENU'

    elif query.data == 'Корзина':
        handle_cart(update, context)
        query.message.delete()
        return "HANDLE_DESCRIPTION"

    elif query.data == 'Оплатить':
        query.message.delete()
        context.bot.send_message(text="Отправьте мне вашу локацию или адрес",
                                 chat_id=chat_id)
        return "HANDLE_WAITING"

    elif 'Убрать' in query.data:
        item_id = query.data.split("|")[1]
        delete_from_cart(access_token, item_id, f"tg-{chat_id}")
        handle_cart(update, context)
        query.message.delete()
        return "HANDLE_DESCRIPTION"

    item_id = query.data
    add_to_cart(access_token, 1, item_id, f"tg-{chat_id}")
    context.bot.send_message(text='added', chat_id=chat_id)
    return 'HANDLE_DESCRIPTION'
Beispiel #5
0
def handle_description(update: Update, context: CallbackContext):
    query = update.callback_query
    query.answer()
    access_token = get_access_token(redis_conn)
    chat_id = update.effective_user.id
    if query.data == 'В меню':
        start(update, context)
        query.message.delete()
        return 'HANDLE_MENU'
    elif query.data == 'Корзина':
        handle_cart(update, context)
        query.message.delete()
        return "HANDLE_DESCRIPTION"
    elif query.data == 'Оплатить':
        query.message.delete()
        context.bot.send_message(
            text='Пожалуйста укажите ваш email пример "*****@*****.**"',
            chat_id=chat_id)
        return "WAITING_EMAIL"
    elif 'Убрать' in query.data:
        item_id = query.data.split("|")[1]
        delete_from_cart(access_token, item_id, chat_id)
        handle_cart(update, context)
        query.message.delete()
        return "HANDLE_DESCRIPTION"
    quantity, item_id = query.data.split('|')
    add_to_cart(access_token, int(quantity), item_id, chat_id)
    context.bot.send_message(
        text='added', chat_id=chat_id)
    return 'HANDLE_DESCRIPTION'
Beispiel #6
0
def main():
    load_dotenv()
    redis_conn = redis.Redis(host=os.getenv('REDIS_HOST'),
                             password=os.getenv('REDIS_PASSWORD'),
                             port=os.getenv('REDIS_PORT'),
                             db=0,
                             decode_responses=True)
    upload_catalogue(redis_conn)
    with open("addresses.json", "r", encoding='utf-8') as my_file:
        addresses = json.load(my_file)
    access_token = get_access_token(redis_conn)
    flow_slug = "pizzeria"
    for entry in addresses:
        coordinates = entry['coordinates']
        #  Обязательно не забудьте создать Flow адресов, и поля для него!
        data = {
            "data": {
                "type": "entry",
                "address": entry['address']['full'],
                "alias": entry['alias'],
                "latitude": coordinates['lat'],
                "longitude": coordinates['lon'],
            }
        }
        create_an_entry(access_token, data, flow_slug)
Beispiel #7
0
def create_menu():
    access_token = get_access_token(redis_conn)
    menu = {}
    categories = get_all_categories(access_token)['data']

    for category in categories:
        keyboard_elements = []
        products = get_products_by_category_id(access_token,
                                               category['id'])['data']

        for product in products:
            image_id = product['relationships']['main_image']['data']['id']
            access_token = get_access_token(redis_conn)
            image_link = get_image_link(access_token,
                                        image_id)['data']['link']['href']

            keyboard_elements.append({
                'title':
                f"{product['name']} {product['meta']['display_price']['with_tax']['formatted']}",
                'subtitle':
                product['description'],
                'image_url':
                image_link,
                'buttons': [{
                    'type': 'postback',
                    'title': 'Положить в корзину',
                    'payload': product['id'],
                }]
            })

        keyboard_elements.append({
            'title':
            'Не нашли нужную пиццу?',
            'subtitle':
            'Остальные пиццы можно посмотреть в одной из категории',
            'image_url':
            'https://primepizza.ru/uploads/position/large_0c07c6fd5c4dcadddaf4a2f1a2c218760b20c396.jpg',
            'buttons': [{
                'type': 'postback',
                'title': f"В меню {menu_category['name']} пиццы",
                'payload': menu_category['id'],
            } for menu_category in categories
                        if menu_category['id'] != category['id']]
        })

        menu[category['id']] = keyboard_elements
    return menu
Beispiel #8
0
def send_the_order_to_the_courier(update, context, entry, user_chat_id, lat,
                                  lon):

    access_token = get_access_token(redis_conn)
    cart = get_cart(access_token, f"tg-{user_chat_id}")
    text_message = format_cart(cart, context)[0]
    courier_id = entry['courier_id_telegram']
    context.bot.send_message(text=text_message, chat_id=courier_id)
    context.bot.send_location(latitude=lat, longitude=lon, chat_id=courier_id)
Beispiel #9
0
def start(update: Update, context: CallbackContext):
    access_token = get_access_token(redis_conn)
    keyboard_product = [
        [InlineKeyboardButton(product['name'], callback_data=product['id'])] for product in get_products(access_token)]
    keyboard_product.append(
        [InlineKeyboardButton('Корзина', callback_data='Корзина')])
    reply_markup = InlineKeyboardMarkup(keyboard_product)

    context.bot.send_message(
        text='Пожалуйста выберите: ', chat_id=update.effective_user.id,
        reply_markup=reply_markup)
    return 'HANDLE_MENU'
Beispiel #10
0
def handle_cart(sender_id, payload):
    """Показывает корзину"""
    access_token = get_access_token(redis_conn)
    cart = get_cart(access_token, sender_id)

    if not cart['data']:
        send_keyboard(
            sender_id, {
                'title':
                "Ваша корзина пуста :C",
                'buttons': [
                    {
                        'type': 'postback',
                        'title': 'В меню',
                        'payload': "68ff879e-9b22-4cab-ab32-23cac76a40d9",
                    },
                ]
            })
        return "HANDLE_DESCRIPTION"

    keyboard_cart, total_to_pay = format_cart(cart)
    keyboard_elements = [{
        'title':
        f"Ваш заказ на сумму {total_to_pay}",
        'image_url':
        'https://internet-marketings.ru/wp-content/uploads/2018/08/idealnaya-korzina-internet-magazina-1068x713.jpg',
        'buttons': [
            {
                'type': 'postback',
                'title': 'Доставка',
                'payload': 'Кнопка не работает',
            },
            {
                'type': 'postback',
                'title': 'Самовывоз',
                'payload': 'Кнопка не работает',
            },
            {
                'type': 'postback',
                'title': 'В меню',
                'payload': "68ff879e-9b22-4cab-ab32-23cac76a40d9",
            },
        ]
    }]

    keyboard_elements += keyboard_cart
    send_keyboard(sender_id, keyboard_elements)
    return "HANDLE_DESCRIPTION"
Beispiel #11
0
def get_near_entry(current_pos, redis_conn):
    """Возвращает ближайщую пиццерию и расстояние до неё в км"""
    distances = []
    access_token = get_access_token(redis_conn)
    distances = []
    entries = get_all_entries(access_token)['data']

    for entry in entries:
        distances.append({
            "entry":
            entry,
            "distance":
            distance.distance((entry['latitude'], entry['longitude']),
                              current_pos).km
        })
    min_entry = min(distances, key=lambda distance: distance['distance'])
    return min_entry['entry'], min_entry['distance']
Beispiel #12
0
def waiting_email(update: Update, context: CallbackContext):
    users_reply = update.message.text
    is_valid = validate_email(users_reply)
    if is_valid:
        access_token = get_access_token(redis_conn)
        try:
            create_customer(
                access_token, str(update.effective_user.id), users_reply)
        except HTTPError:
            update.message.reply_text('Ошибка такой Email уже указывали!')
            return "WAITING_EMAIL"
        update.message.reply_text(
            f"Вы прислали мне эту почту - {users_reply}. Мы скоро свяжемся.")
        start(update, context)
        return "HANDLE_DESCRIPTION"
    update.message.reply_text(f"Ошибка! неверный email - '{users_reply}'")
    return "WAITING_EMAIL"
Beispiel #13
0
def upload_catalogue(redis_conn):
    with open("menu.json", "r", encoding='utf-8') as my_file:
        menu_pizza = json.load(my_file)
    Path(os.getcwd(), 'images').mkdir(parents=True, exist_ok=True)
    for pizza in menu_pizza:
        name = pizza['name']
        description = pizza['description']
        url_img = pizza['product_image']['url']
        price = pizza['price']
        id_pizza = str(pizza['id'])

        access_token = get_access_token(redis_conn)
        download_photo(id_pizza, url_img)

        id_project = create_product(access_token, name, description, price,
                                    id_pizza)['data']['id']

        rel_img_path = download_photo(id_pizza, url_img)
        id_image = upload_file(access_token, rel_img_path)['data']['id']

        create_relationship(access_token, id_project, id_image)

    path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'images')
    shutil.rmtree(path)
Beispiel #14
0
def create_customer_adreess(redis_conn, lat, lon):
    access_token = get_access_token(redis_conn)

    data = {"data": {"type": "entry", "latitude": lat, "longitude": lon}}
    create_an_entry(access_token, data, "customer_address")