Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
22 kB
2
Indexable
Never
import asyncpg
from aiogram import Router, types, Bot, F
from aiogram.filters.state import State, StatesGroup
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery
from aiogram.utils.keyboard import InlineKeyboardBuilder
from pycoingecko import CoinGeckoAPI

from config import channel_id, admin_id, sup_id, addr


# from lite import create_wallet, check_balance


class WalletState(StatesGroup):
    address = State()
    secret = State()


class OrderInfo(StatesGroup):
    location = State()
    product_name = State()
    weight = State()
    cost = State()
    addr_cust = State()
    courier = State()
    customer = State()


class Aprove(StatesGroup):
    photo = State()


class Review(StatesGroup):
    message = State()


r = Router()


def get_litecoin_to_usdt_rate():
    cg = CoinGeckoAPI()
    data = cg.get_price(ids='litecoin', vs_currencies='usd')
    return data['litecoin']['usd']


def convert_usdt_to_litecoin(usdt_amount, rate):
    return usdt_amount / rate


@r.callback_query(lambda c: c.data == 'buy')
async def buy_inline(call: CallbackQuery):
    builder = InlineKeyboardBuilder()
    builder.row(
        types.InlineKeyboardButton(
            text="дус",
            callback_data="dus"))
    builder.row(
        types.InlineKeyboardButton(
            text="шпак",
            callback_data="shpak"
        )
    )
    await call.message.edit_text("в наявности:", reply_markup=builder.row().as_markup())


async def choose_weight_and_cost_shpak(call: CallbackQuery, location: str):
    builder = InlineKeyboardBuilder()
    builder.row(
        types.InlineKeyboardButton(
            text="вес 5г = 15$",
            callback_data=f"15|shpak|{location}"))
    builder.row(
        types.InlineKeyboardButton(
            text="вес 10г = 25$",
            callback_data=f"25|shpak|{location}"
        )
    )
    await call.message.edit_text(f"локация: {location}\nвыбери вес:", reply_markup=builder.row().as_markup())


@r.callback_query(lambda c: c.data == 'shpak')
async def buy_dus(call: CallbackQuery):
    builder = InlineKeyboardBuilder()
    builder.row(
        types.InlineKeyboardButton(
            text="Октябрьский",
            callback_data=f"okta|shpak"))
    builder.row(
        types.InlineKeyboardButton(
            text="Первомайский",
            callback_data="pervo|shpak"))
    builder.row(
        types.InlineKeyboardButton(
            text="Ленинский",
            callback_data="lenin|shpak"))
    builder.row(
        types.InlineKeyboardButton(
            text="Свердловский",
            callback_data="sverdl|shpak"))
    await call.message.edit_text("выбери район:", reply_markup=builder.row().as_markup())


# Обработчики для каждого района
@r.callback_query(lambda c: c.data.endswith('|shpak'))
async def choose_location(call: CallbackQuery):
    data_parts = call.data.split("|")
    if len(data_parts) == 3:
        cost, nartype, location = data_parts
    else:
        location, nartype = data_parts

    location_map = {
        "okta": "Октябрьский",
        "pervo": "Первомайский",
        "lenin": "Ленинский",
        "sverdl": "Свердловский"
    }
    await choose_weight_and_cost_shpak(call, location_map[location])


# ------------------------------------------------------------------------------------------ #
async def process_order_shpak(call: CallbackQuery, cost: str, weight: str, location: str, state: FSMContext):
    builder = InlineKeyboardBuilder()
    builder.row(
        types.InlineKeyboardButton(
            text="принять",
            callback_data=f"get|{cost}"
        )
    )
    builder.row(
        types.InlineKeyboardButton(
            text="отменить",
            callback_data=f"no"
        )
    )

    await call.message.edit_text(f"товар: шпак\n"
                                 f"вес: {weight}\n"
                                 f"стоимость: {cost}$\n"
                                 f"локация: {location}\n\n"
                                 f"подтверди покупку",
                                 reply_markup=builder.row().as_markup())

    await state.update_data({
        'location': location,
        'product_name': 'шпак',
        'weight': weight,
        'cost': cost
    })


@r.callback_query(lambda c: c.data.endswith('shpak|Октябрьский'))
async def handle_order_okta(call: CallbackQuery, state: FSMContext):
    cost, _, location = call.data.split("|")
    weight = "5г" if cost == "15" else "10г"
    await process_order_shpak(call, cost, weight, location, state)


@r.callback_query(lambda c: c.data.endswith('shpak|Первомайский'))
async def handle_order_pervo(call: CallbackQuery, state: FSMContext):
    cost, _, location = call.data.split("|")
    weight = "5г" if cost == "15" else "10г"
    await process_order_shpak(call, cost, weight, location, state)


@r.callback_query(lambda c: c.data.endswith('shpak|Свердловский'))
async def handle_order_sverdl(call: CallbackQuery, state: FSMContext):
    cost, _, location = call.data.split("|")
    weight = "5г" if cost == "15" else "10г"
    await process_order_shpak(call, cost, weight, location, state)


@r.callback_query(lambda c: c.data.endswith('shpak|Ленинский'))
async def handle_order_lenin(call: CallbackQuery, state: FSMContext):
    cost, _, location = call.data.split("|")
    weight = "5г" if cost == "15" else "10г"
    await process_order_shpak(call, cost, weight, location, state)


# ------------------------------------------------------------------------------------------ #
async def choose_weight_and_cost_dus(call: CallbackQuery, location: str):
    builder = InlineKeyboardBuilder()
    builder.row(
        types.InlineKeyboardButton(
            text="вес 5г = 15$",
            callback_data=f"15|dus|{location}"))
    builder.row(
        types.InlineKeyboardButton(
            text="вес 10г = 25$",
            callback_data=f"25|dus|{location}"
        )
    )
    await call.message.edit_text(f"локация: {location}\nвыбери вес:", reply_markup=builder.row().as_markup())


@r.callback_query(lambda c: c.data == 'dus')
async def buy_dus(call: CallbackQuery):
    builder = InlineKeyboardBuilder()
    builder.row(
        types.InlineKeyboardButton(
            text="Октябрьский",
            callback_data=f"okta|dus"))
    builder.row(
        types.InlineKeyboardButton(
            text="Первомайский",
            callback_data="pervo|dus"))
    builder.row(
        types.InlineKeyboardButton(
            text="Ленинский",
            callback_data="lenin|dus"))
    builder.row(
        types.InlineKeyboardButton(
            text="Свердловский",
            callback_data="sverdl|dus"))
    await call.message.edit_text("выбери район:", reply_markup=builder.row().as_markup())


# Обработчики для каждого района
@r.callback_query(lambda c: c.data.endswith('|dus'))
async def choose_location(call: CallbackQuery):
    data_parts = call.data.split("|")
    if len(data_parts) == 3:
        cost, nartype, location = data_parts
    else:
        location, nartype = data_parts

    location_map = {
        "okta": "Октябрьский",
        "pervo": "Первомайский",
        "lenin": "Ленинский",
        "sverdl": "Свердловский"
    }
    await choose_weight_and_cost_dus(call, location_map[location])


# ------------------------------------------------------------------------------------------ #


async def process_order(call: CallbackQuery, cost: str, weight: str, location: str, state: FSMContext):
    builder = InlineKeyboardBuilder()
    builder.row(
        types.InlineKeyboardButton(
            text="принять",
            callback_data=f"get|{cost}"
        )
    )
    builder.row(
        types.InlineKeyboardButton(
            text="отменить",
            callback_data=f"no"
        )
    )

    await call.message.edit_text(f"товар: дус\n"
                                 f"вес: {weight}\n"
                                 f"стоимость: {cost}$\n"
                                 f"локация: {location}\n\n"
                                 f"подтверди покупку",
                                 reply_markup=builder.row().as_markup())

    await state.update_data({
        'location': location,
        'product_name': 'дус',
        'weight': weight,
        'cost': cost
    })


# Обработчики
@r.callback_query(lambda c: c.data.endswith('dus|Октябрьский'))
async def handle_order_okta(call: CallbackQuery, state: FSMContext):
    cost, _, location = call.data.split("|")
    weight = "5г" if cost == "15" else "10г"
    await process_order(call, cost, weight, location, state)


@r.callback_query(lambda c: c.data.endswith('dus|Первомайский'))
async def handle_order_pervo(call: CallbackQuery, state: FSMContext):
    cost, _, location = call.data.split("|")
    weight = "5г" if cost == "15" else "10г"
    await process_order(call, cost, weight, location, state)


@r.callback_query(lambda c: c.data.endswith('dus|Свердловский'))
async def handle_order_sverdl(call: CallbackQuery, state: FSMContext):
    cost, _, location = call.data.split("|")
    weight = "5г" if cost == "15" else "10г"
    await process_order(call, cost, weight, location, state)


@r.callback_query(lambda c: c.data.endswith('dus|Ленинский'))
async def handle_order_lenin(call: CallbackQuery, state: FSMContext):
    cost, _, location = call.data.split("|")
    weight = "5г" if cost == "15" else "10г"
    await process_order(call, cost, weight, location, state)


@r.callback_query(lambda c: c.data == "no")
async def no(call: CallbackQuery, state: FSMContext):
    await call.message.edit_text("отмена")
    try:
        await state.clear()
    except:
        pass


# ------------------------------------------------------------------------------------------ #


@r.callback_query(lambda c: c.data.startswith('get'))
async def get_inline(call: CallbackQuery, state: FSMContext):
    amount = call.data.split("|")[1]

    rate = get_litecoin_to_usdt_rate()
    ltc_amount = convert_usdt_to_litecoin(int(amount), rate)
    # await state.set_state(WalletState.secret.state)
    # await state.update_data(secret=secret)
    builder = InlineKeyboardBuilder()
    builder.row(
        types.InlineKeyboardButton(
            text="отправил",
            callback_data=f"sended|{str(ltc_amount)}"))
    await call.message.edit_text(text=f"Адрес: <code>{addr}</code>\n\n"
                                      f"отправь туда ровно <code>{ltc_amount}</code> с учетом комиссии!"
                                      f"(важно подождать, пока все блоки обработаются, и потом нажимать кнопку)",
                                      reply_markup=builder.row().as_markup())


@r.callback_query(lambda c: c.data.startswith('sended'))
async def sended(call: CallbackQuery, bot: Bot, state: FSMContext):
    _, amount = call.data.split("|")
    await state.set_state(OrderInfo.cost.state)
    await state.update_data(amount=amount)
    await call.message.answer("Пожалуйста, отправь свой адрес.")
    await state.set_state(OrderInfo.addr_cust)
    # data = await state.get_data()
    # current_state = await state.get_data()
    # print(current_state)
    # customer_id = call.from_user.id
    # addr_cust = data.get("addr_cust")
    # builder = InlineKeyboardBuilder()
    # builder.row(
    #     types.InlineKeyboardButton(
    #         text=f"подтверждаю",
    #         callback_data=f"podtv|{customer_id}"
    #     ),
    #     types.InlineKeyboardButton(
    #         text="не подтверждаю",
    #         callback_data=f"ne_podtv|{customer_id}"
    #     )
    # )
    # await bot.send_message(sup_id,
    #                        f"адрес {addr_cust} отправил {amount}. подтверди, что деньги пришли",
    #                        reply_markup=builder.row().as_markup())
    # # await state.clear()


@r.callback_query(lambda c: c.data.startswith('podtv'))
async def podtv_order(call: CallbackQuery, bot: Bot, state: FSMContext):
    _, customer_id = call.data.split("|")
    await call.message.edit_text("принял. уведомляю заказчика и передаю дальше инфу...")
    await bot.send_message(customer_id, "деньги пришли. передаю данные курьерам...")
    conn = await asyncpg.connect(host="localhost",
                                 port=5432,
                                 user="postgres",
                                 password="qweasd123",
                                 database="shop")
    builder2 = InlineKeyboardBuilder()
    builder2.row(
        types.InlineKeyboardButton(
            text="принять",
            callback_data=f"accept|{customer_id}"  # передаем ID заказчика
        )
    )
    # global location
    # global product_name
    # global weight
    # global cost
    data = await state.get_data()
    location = data.get("location")
    product_name = data.get("product_name")
    weight = data.get("weight")
    cost = data.get("cost")
    await bot.send_message(channel_id, text=f"новый заказ!!\n\n"
                                            f"локация: {location}\n"
                                            f"вид: {product_name}\n"
                                            f"количество: {weight}\n"
                                            f"стоимость: {cost}$", reply_markup=builder2.row().as_markup())
    # await bot.send_message(admin_id, text=f"новый заказ!!\n\n"
    #                                       f"локация: {location}\n"
    #                                       f"вид: {product_name}\n"
    #                                       f"количество: {weight}\n"
    #                                       f"стоимость: {cost}$")
    await bot.send_message(sup_id, text=f"новый заказ!!\n\n"
                                        f"локация: {location}\n"
                                        f"вид: {product_name}\n"
                                        f"количество: {weight}\n"
                                        f"стоимость: {cost}$")
    # await state.clear()


@r.callback_query(lambda c: c.data.startswith('ne_podtv'))
async def ne_podtv_order(call: CallbackQuery, bot: Bot, state: FSMContext):
    _, customer_id = call.data.split("|")
    await call.message.edit_text("отклонил ордер")
    await bot.send_message(customer_id, "деньги не пришли. ордер отклонен")


@r.message(OrderInfo.addr_cust)
async def get_address(message: types.Message, state: FSMContext, bot: Bot):
    data = await state.get_data()
    current_state = await state.get_data()
    print(current_state)
    customer_id = message.from_user.id
    addr_cust = message.text
    amount = data.get("amount")
    builder = InlineKeyboardBuilder()
    builder.row(
        types.InlineKeyboardButton(
            text=f"подтверждаю",
            callback_data=f"podtv|{customer_id}"
        ),
        types.InlineKeyboardButton(
            text="не подтверждаю",
            callback_data=f"ne_podtv|{customer_id}"
        )
    )
    await bot.send_message(sup_id,
                           f"адрес {addr_cust} отправил {amount}. подтверди, что деньги пришли",
                           reply_markup=builder.row().as_markup())
    # await state.clear()


@r.callback_query(lambda c: c.data.startswith('accept'))
async def accept(call: CallbackQuery, bot: Bot, state: FSMContext):
    global courier_id
    global customer_id
    customer_id = call.data.split('|')[1]  # извлекаем ID заказчика
    courier_id = call.from_user.id  # ID курьера
    await call.message.edit_text("заказ принят")
    print(f"Customer ID in sended: {customer_id}")
    print(f"courier ID in sended: {courier_id}")
    builder = InlineKeyboardBuilder()
    builder.row(
        types.InlineKeyboardButton(
            text="выполнено",
            callback_data="made"
        )
    )
    data = await state.get_data()
    location = data.get("location")
    product_name = data.get("product_name")
    weight = data.get("weight")
    cost = data.get("cost")
    await bot.send_message(courier_id, text=f"ты принял заказ. информация:\n\n"
                                         f"локация: {location}\n"
                                         f"вид: {product_name}\n"
                                         f"количество: {weight}\n"
                                         f"стоимость: {cost}$", reply_markup=builder.row().as_markup())
    cour = await bot.get_chat(courier_id)
    cust = await bot.get_chat(customer_id)
    # await bot.send_message(admin_id, text=f"заказ был принят человеком @{cour.username if cour.username else 'None'}"
    #                                     f"(<code>{cour.id}</code>)\n"
    #                                     f"для @{cust.username if cust.username else 'None'}(<code>{cust.id}</code>)\n\n"
    #                                     f"информация:\n"
    #                                     f"локация: {location}\n"
    #                                     f"вид: {product_name}\n"
    #                                     f"количество: {weight}\n"
    #                                     f"стоимость: {cost}$")

    await bot.send_message(sup_id, text=f"заказ был принят человеком @{cour.username if cour.username else 'None'}"
                                        f"(<code>{cour.id}</code>)\n"
                                        f"для @{cust.username if cust.username else 'None'}(<code>{cust.id}</code>)\n\n"
                                        f"информация:\n"
                                        f"локация: {location}\n"
                                        f"вид: {product_name}\n"
                                        f"количество: {weight}\n"
                                        f"стоимость: {cost}$")


@r.callback_query(lambda c: c.data == "made")
async def made(call: CallbackQuery, state: FSMContext):
    await call.message.edit_text("отправь фотографию, на которой так же будут координаты клада")
    await state.set_state(Aprove.photo)


@r.message(Aprove.photo, F.photo)
async def photo(m: types.Message, state: FSMContext, bot: Bot):
    await state.update_data(photo=m.photo[-1].file_id)
    await m.answer("спасибо за работу. все данные отправляю заказчику...")
    data = await state.get_data()
    file_id = data.get("photo")
    builder = InlineKeyboardBuilder()
    builder.row(
        types.InlineKeyboardButton(
            text="оставить отзыв",
            callback_data="review"
        )
    )
    builder.row(
        types.InlineKeyboardButton(
            text="связь с саппортом",
            url="username.t.me"
        )
    )
    await bot.send_photo(chat_id=int(customer_id), photo=str(file_id), caption="ваш заказ выполнен",
                         reply_markup=builder.row().as_markup())
    cour = await bot.get_chat(courier_id)
    cust = await bot.get_chat(customer_id)
    await bot.send_photo(sup_id, photo=str(file_id))
    data = await state.get_data()
    location = data.get("location")
    product_name = data.get("product_name")
    weight = data.get("weight")
    cost = data.get("cost")
    await bot.send_message(sup_id,text=f"@{cour.username if cour.username else 'None'}(<code>{cour.id}</code>) "
                                       f"выполнил заказ для @{cust.username if cust.username else 'None'}"
                                       f"(<code>{cust.id}</code>)\n"
                                       f"локация: {location}\n"
                                       f"вид: {product_name}\n"
                                       f"количество: {weight}\n"
                                       f"стоимость: {cost}$")

    # await bot.send_photo(admin_id, photo=str(file_id))
    # await bot.send_message(admin_id, text=f"@{cour.username if cour.username else 'None'}(<code>{cour.id}</code>) "
    #                                     f"выполнил заказ для @{cust.username if cust.username else 'None'}"
    #                                     f"(<code>{cust.id}</code>)\n"
    #                                     f"локация: {location}\n"
    #                                     f"вид: {product_name}\n"
    #                                     f"количество: {weight}\n"
    #                                     f"стоимость: {cost}$")
    await state.clear()


@r.callback_query(lambda c: c.data == "review")
async def review(call: CallbackQuery, state: FSMContext):
    builder = InlineKeyboardBuilder()
    builder.row(
        types.InlineKeyboardButton(
            text="отмена",
            callback_data="no"
        )
    )
    await call.message.answer("напиши отзыв", reply_markup=builder.row().as_markup())
    await state.set_state(Review.message)


@r.message(Review.message)
async def review_message(m: types.Message, bot: Bot, state: FSMContext):
    await state.update_data(message=m.text)
    await m.answer("пасиб")
    await bot.send_message(admin_id, text=f"новый отзыв!\n"
                                          f"{m.text}")
    await bot.send_message(sup_id, text=f"новый отзыв!\n"
                                        f"{m.text}")
    await state.clear()