/
george2066
/
TelegramBotParkPiterSoft
Обзор
Документация
Войти
/
george2066
/
TelegramBotParkPiterSoft
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
controller/controller.py
279 строк
13 KB
george2066
fir description tariff and capture
31 июл 2025, 15:56
31 июл 2025, 15:56
931d0f8
Код
Авторство
О чём код?
import secret from aiogram import F from aiogram import Bot, Dispatcher from aiogram.enums import ParseMode from aiogram.types import Message, InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery, FSInputFile, LabeledPrice from aiogram.types.pre_checkout_query import PreCheckoutQuery from aiogram.filters import CommandStart from aiogram.client.default import DefaultBotProperties from aiogram.fsm.context import FSMContext from aiogram.fsm.state import State, StatesGroup from aiogram.fsm.storage.memory import MemoryStorage from service.services import TelegramBotParkPiter telegram_bot = TelegramBotParkPiter() bot = Bot(token=secret.TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) dp = Dispatcher(storage=MemoryStorage()) back = [InlineKeyboardButton(text='Назад', callback_data='hello_message')] request_ticket_or_QR = 'Пожалуйста, введите код вашего талона или сфотографируйте QR-код.' class States(StatesGroup): waiting_tariff = State() waiting_arrears = State() payed = State() @dp.message(CommandStart()) async def hello_message(message: Message): inline_keyboard = [ [ InlineKeyboardButton(text="Показать ТАРИФ", callback_data="get_tariff"), InlineKeyboardButton(text="Показать ЗАДОЛЖЕННОСТЬ", callback_data="get_arrears") ], [InlineKeyboardButton(text="Показать СПИСОК КАМЕР", callback_data="get_list_captures")] ] inline_keyboard_markup = InlineKeyboardMarkup(inline_keyboard=inline_keyboard) await message.answer(f"{'Добро пожаловать! ' if message.text == '/start' else ''}Выберете опцию:", reply_markup=inline_keyboard_markup) ############################################################################### '💲💲💲💲💲💲💲💲💲💲💲💲💲waiting_tariff💲💲💲💲💲💲💲💲💲💲💲💲💲💲💲' ############################################################################### @dp.callback_query(lambda callback: callback.data == 'get_tariff') async def get_tariff(callback_query: CallbackQuery, state: FSMContext): await state.set_state(States.waiting_tariff) await callback_query.message.reply(text=request_ticket_or_QR, reply_markup=get_back()) await bot.delete_message(callback_query.from_user.id, callback_query.message.message_id) @dp.message(F.text, States.waiting_tariff) async def get_tariff_ticket_id(message: Message, state: FSMContext): ticket_id = message.text try: non_description = lambda name: f"К сожалению. описание к тарифу \"{name}\" отсутствует.\n\nСсылка: {telegram_bot.get_link(ticket_id)}" description = get_description_tariff(ticket_id) await message.answer(text=description) except Exception as e: telegram_bot.writer_logg('get_tariff_ticket_id', ticket_id, message.from_user.full_name, e) await message.answer(f"{telegram_bot.json_error}") finally: await state.clear() await hello_message(message) @dp.message(F.photo, States.waiting_tariff) async def get_tariff_photo(message: Message, state: FSMContext): photo_data = await state.update_data(photo=message.photo[-1]) photo_data = photo_data['photo'] file_id = photo_data.file_id file = await bot.get_file(file_id) file_path = file.file_path image_data = await bot.download_file(file_path) link = telegram_bot.get_link_QR(image_data) ticket_id = telegram_bot.get_ticket_id(link) try: non_description = lambda name: f"К сожалению. описание к тарифу \"{name}\" отсутствует.\n\nСсылка: {telegram_bot.get_link(ticket_id)}" description = get_description_tariff(ticket_id) await message.answer(text=description) except Exception as e: telegram_bot.writer_logg('get_tariff_photo', ticket_id, message.from_user.full_name, e) await message.answer(f"{telegram_bot.json_error}") finally: await state.clear() await hello_message(message) ################################################################################ '💵💵💵💵💵💵💵💵💵💵💵💵💵waiting_arrears💵💵💵💵💵💵💵💵💵💵💵💵💵💵💵' ################################################################################ @dp.callback_query(lambda callback: callback.data == 'get_arrears') async def get_arrears(callback_query: CallbackQuery, state: FSMContext): await state.set_state(States.waiting_arrears) await callback_query.message.reply(text=request_ticket_or_QR, reply_markup=get_back()) await bot.delete_message(callback_query.from_user.id, callback_query.message.message_id) @dp.message(F.text, States.waiting_arrears) async def get_arrears_ticket_id(message: Message, state: FSMContext): ticket_id = message.text try: await get_keyboard(message, ticket_id, state) except Exception as e: telegram_bot.writer_logg('get_arrears_ticket_id', ticket_id, message.from_user.full_name, e) await message.answer(f"{telegram_bot.json_error}") await hello_message(message) finally: await state.clear() @dp.message(F.photo, States.waiting_arrears) async def get_arrears_photo(message: Message, state: FSMContext): ticket_id = await get_ticket_id_QR(message, state) await get_keyboard(message, ticket_id, state) ################################################################################ '💵💵💵💵💵💵💵💵💵💵💵💵💵payed💵💵💵💵💵💵💵💵💵💵💵💵💵💵💵' ################################################################################ @dp.callback_query(lambda callback: callback.data == 'payed' and States.waiting_arrears) async def pay(callback: CallbackQuery, state: FSMContext): await state.set_state(States.payed) ticket_id = '' try: query = callback.message.text message_id = callback.message.message_id ticket_id = [el for el in query.split('\n') if 'Талон: ' in el][0].split()[1] await state.update_data(ticket_id=ticket_id) await state.update_data(message_delete=message_id) json = telegram_bot.get_JSON_PAY(ticket_id) price = json['amount'] await bot.send_invoice( chat_id=callback.from_user.id, title='Оплатите парковку', description=f'С вас {price} рублей', payload='payed_ok', provider_token=secret.TOKEN_PAY, currency='RUB', start_parameter='card_bot', prices=[LabeledPrice( label=f'Оплата {price}', amount=int(price * 100) )] ) except Exception as e: telegram_bot.writer_logg('pay', ticket_id, callback.message.from_user.full_name, e) await callback.answer(text=f"Сумма должна быть не меньше 80 рублей, чтобы оплатить через Telegram-бота.") @dp.pre_checkout_query() async def process_pre_checkout_query(pre_checkout_query: PreCheckoutQuery): await bot.answer_pre_checkout_query(pre_checkout_query.id, ok=True) @dp.message(F.content_type.in_(['successful_payment']) and States.payed) async def successful_pay(message: Message, state: FSMContext): data = await state.get_data() if message.successful_payment.invoice_payload == 'payed_ok': ticket_id = data['ticket_id'] telegram_bot.payment(ticket_id) await message.answer(text='Вы оплатили парковку.') await hello_message(message) await bot.delete_message(message.from_user.id, message.message_id) await bot.delete_message(message.from_user.id, data['message_delete']) ############################################################################### '📹📹📹📹📹📹📹📹📹📹📹📹📹📹CAPTURES📹📹📹📹📹📹📹📹📹📹📹📹📹📹📹📹📹' ############################################################################### @dp.callback_query(lambda callback: callback.data == 'get_list_captures') async def get_list_captures(callback_query: CallbackQuery): try: inline_keyboard = [ [InlineKeyboardButton(text=f'{data["name"]}', callback_data=f'capture_{data["camera"]}')] for data in telegram_bot.get_list_captures() ] inline_keyboard.append(back) inline_keyboard_markup = InlineKeyboardMarkup(inline_keyboard=inline_keyboard) await bot.delete_message(callback_query.from_user.id, callback_query.message.message_id) await callback_query.message.answer(text='Выберите камеру:', reply_markup=inline_keyboard_markup) except Exception as e: telegram_bot.writer_logg('get_photo', '', callback_query.message.from_user.full_name, e) await callback_query.message.answer(text=telegram_bot.not_captures) await hello_message(callback_query.message) @dp.callback_query(lambda callback: callback.data and callback.data.startswith('capture_')) async def get_photo(callback_query: CallbackQuery): try: number = int(callback_query.data.split('_')[1]) file_path =telegram_bot.get_path_photo(number) photo = FSInputFile(path=file_path) await callback_query.message.answer_photo(photo=photo) except Exception as e: telegram_bot.writer_logg('get_photo', '', callback_query.message.from_user.full_name, e) await callback_query.message.answer(text=telegram_bot.not_captures) finally: await hello_message(callback_query.message) ############################################################################### ############################################################################### ############################################################################### '''@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@''' '''@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@''' '''@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@''' ############################################################################### '🆘🆘🆘🆘🆘🆘🆘🆘🆘🆘🆘🆘🆘🆘HELPERS🆘🆘🆘🆘🆘🆘🆘🆘🆘🆘🆘🆘🆘🆘🆘🆘🆘' ############################################################################### def get_back(): keyboard = [back] inline_keyboard_markup = InlineKeyboardMarkup(inline_keyboard=keyboard) return inline_keyboard_markup @dp.callback_query(lambda c: c.data == 'hello_message') async def back_handler(callback_query: CallbackQuery): await callback_query.answer() await hello_message(callback_query.message) await bot.delete_message(callback_query.from_user.id, callback_query.message.message_id) async def get_keyboard(message: Message, ticket_id: str, state: FSMContext): try: await state.update_data({'ticket_id': ticket_id}) json_PAY = telegram_bot.get_JSON_PAY(ticket_id) json_CLIENT = telegram_bot.get_JSON_CLIENT(ticket_id) about_client = ( f'Талон: {json_CLIENT["ticket_id"]}\n' f'Не оплачено: {"0 руб." if json_PAY == "CardNotFound" else json_PAY["amount"]} руб.\n' f'Тариф: {json_CLIENT["tariff_name"]}\n' f'Оплачено: {json_CLIENT["amount_paid"]} руб.\n' f'Время въезда: {json_CLIENT["enter_time"].replace("T", " ")}\n' f'Время выезда: {json_CLIENT["leave_at"].replace("T", " ")}\n' f'\n' f'Ссылка: {telegram_bot.get_link(ticket_id)}' ) if json_CLIENT['active'] == True or (json_PAY != 'CardNotFound' and json_PAY["amount"] > 0): keyboard = [ [InlineKeyboardButton(text="Оплатить", callback_data='payed')], back ] reply_markup = InlineKeyboardMarkup(inline_keyboard=keyboard) await message.answer(text=about_client, reply_markup=reply_markup) else: await message.answer(text=about_client) await hello_message(message) except Exception as e: await message.answer(text=telegram_bot.json_error) await hello_message(message) async def get_ticket_id_QR(message, state): photo_data = await state.update_data(photo=message.photo[-1]) photo_data = photo_data['photo'] file_id = photo_data.file_id file = await bot.get_file(file_id) file_path = file.file_path image_data = await bot.download_file(file_path) link = telegram_bot.get_link_QR(image_data) ticket_id = telegram_bot.get_ticket_id(link) return ticket_id def get_description_tariff(ticket_id): json_data = telegram_bot.get_tariff(ticket_id) description = (f'Тариф: {json_data["name"]}\n' f'\n' f'Описание:\n\n' f'{json_data["description"] if json_data["description"] else "(описание отсутствует)"}\n\n' f'Ссылка: {telegram_bot.get_link(ticket_id)}') return description async def main() -> None: await dp.start_polling(bot)