Renamed dtek-bot's dockercompose for easy access

Updated parser logic for updated site version
This commit is contained in:
2025-11-13 14:22:59 +01:00
parent 9ad731dae8
commit 4bbe94c91b
2 changed files with 68 additions and 55 deletions
+68 -55
View File
@@ -1,3 +1,10 @@
# Раздел "ТВАРИ, ЧИТАТЕ ВНИМАТЕЛЬНО!"
# Когда обновят сайт -- расскоментровать 641-646 и закоментировать 647.
# Поменять комменты 671 и 672 местами.
import requests import requests
import json import json
import asyncio import asyncio
@@ -82,7 +89,7 @@ def get_day_statistics(day_blocks: List[Dict]) -> Dict[str, int]:
# ============================================================================ # ============================================================================
def parse_html(html: str) -> List[Dict]: def parse_html(html: str) -> List[Dict]:
"""Парсит HTML с графиком отключений""" """Парсит HTML с графиком отключений (нова логіка)"""
soup = BeautifulSoup(html, "html.parser") soup = BeautifulSoup(html, "html.parser")
cells = soup.select(".disconnection-detailed-table-cell.cell") cells = soup.select(".disconnection-detailed-table-cell.cell")
@@ -95,61 +102,63 @@ def parse_html(html: str) -> List[Dict]:
continue continue
cell_classes = cell.get('class', []) cell_classes = cell.get('class', [])
# Перевіряємо чи вся година вимкнена
full_hour_off = 'has_disconnection' in cell_classes and 'full_hour' in cell_classes full_hour_off = 'has_disconnection' in cell_classes and 'full_hour' in cell_classes
no_disconnection = 'no_disconnection' in cell_classes
hour_block = cell.select_one(".hour_block") hour_block = cell.select_one(".hour_block")
if not hour_block: if not hour_block:
continue continue
left = hour_block.select_one(".half.left") # Визначаємо статус та підтвердження для всієї години
right = hour_block.select_one(".half.right") confirmed = None
if 'confirm_1' in cell_classes:
def parse_half(half, force_off: bool = False) -> Dict: confirmed = True
if not half: elif 'confirm_0' in cell_classes:
return {"status": "unknown", "queue": None, "confirmed": None} confirmed = False
status = "off" if force_off else "unknown" # Шукаємо часткові відключення через div.fill
if not force_off: fill_divs = hour_block.select(".fill")
classes = half.get("class", [])
if "has_disconnection" in classes: first_half_data = {"status": "on", "queue": None, "confirmed": None}
status = "off" second_half_data = {"status": "on", "queue": None, "confirmed": None}
elif "no_disconnection" in classes:
status = "on" if full_hour_off:
# Вся година вимкнена
queue = None first_half_data = {"status": "off", "queue": None, "confirmed": confirmed}
confirmed = None second_half_data = {"status": "off", "queue": None, "confirmed": confirmed}
disconnection_div = half.select_one(".disconnection") elif no_disconnection and not fill_divs:
# Вся година ввімкнена
if disconnection_div and disconnection_div.has_attr("title"): first_half_data = {"status": "on", "queue": None, "confirmed": None}
title = disconnection_div["title"] second_half_data = {"status": "on", "queue": None, "confirmed": None}
if "Номер черги" in title: else:
try: # Перевіряємо часткові відключення
queue = title.split(":")[-1].strip() for fill_div in fill_divs:
except: title = fill_div.get('title', '')
pass style = fill_div.get('style', '')
fill_classes = fill_div.get('class', [])
disconnection_classes = disconnection_div.get("class", []) # Визначаємо підтвердження
if "disconnection_confirm_1" in disconnection_classes: fill_confirmed = None
confirmed = True if 'confirmed' in fill_classes:
elif "disconnection_confirm_0" in disconnection_classes: fill_confirmed = True
confirmed = False elif 'possible' in fill_classes:
fill_confirmed = False
if force_off and confirmed is None:
if 'confirm_1' in cell_classes: # Парсимо стиль для визначення часу
confirmed = True # --start:0;--size:50 означає 0-30 хвилин (перша половина)
elif 'confirm_0' in cell_classes: # --start:50;--size:50 означає 30-60 хвилин (друга половина)
confirmed = False if '--start:0' in style or title.endswith(':00—' + f'{current_hour:02d}:30'):
first_half_data = {"status": "off", "queue": None, "confirmed": fill_confirmed}
return {"status": status, "queue": queue, "confirmed": confirmed} elif '--start:50' in style or (f'{current_hour:02d}:30' in title and title.endswith(':00')):
second_half_data = {"status": "off", "queue": None, "confirmed": fill_confirmed}
left_data = parse_half(left, force_off=full_hour_off)
right_data = parse_half(right, force_off=full_hour_off)
schedule.append({ schedule.append({
"hour": current_hour, "hour": current_hour,
"day": current_day, "day": current_day,
"first_half": left_data, "first_half": first_half_data,
"second_half": right_data, "second_half": second_half_data,
}) })
current_hour += 1 current_hour += 1
@@ -159,7 +168,6 @@ def parse_html(html: str) -> List[Dict]:
return schedule return schedule
def get_voe_html(city_id: int, street_id: int, house_id: int) -> str: def get_voe_html(city_id: int, street_id: int, house_id: int) -> str:
"""Получает HTML с сайта VOE""" """Получает HTML с сайта VOE"""
url = "https://www.voe.com.ua/disconnection/detailed?ajax_form=1&_wrapper_format=drupal_ajax" url = "https://www.voe.com.ua/disconnection/detailed?ajax_form=1&_wrapper_format=drupal_ajax"
@@ -637,17 +645,21 @@ async def cmd_tomorrow(message: Message):
return return
try: try:
await message.answer("⏳ Завантаження графіку завтра...") # """Закоментировал до лучших времен"""
html = get_voe_html(VOE_CITY_ID, VOE_STREET_ID, VOE_HOUSE_ID) # await message.answer("⏳ Завантаження графіку завтра...")
schedule = parse_html(html) # html = get_voe_html(VOE_CITY_ID, VOE_STREET_ID, VOE_HOUSE_ID)
text = format_single_day_schedule(schedule, 1) # schedule = parse_html(html)
await message.answer(text, parse_mode="HTML", reply_markup=get_main_keyboard()) # text = format_single_day_schedule(schedule, 1)
# await message.answer(text, parse_mode="HTML", reply_markup=get_main_keyboard())
await message.answer("❌ Функція тимчасово недоступна. Чекаємо на оновлення сайту", parse_mode="HTML", reply_markup=get_main_keyboard())
except Exception as e: except Exception as e:
await message.answer( await message.answer(
f"❌ <b>Помилка:</b> {str(e)}", f"❌ <b>Помилка:</b> {str(e)}",
parse_mode="HTML", parse_mode="HTML",
reply_markup=get_main_keyboard() reply_markup=get_main_keyboard()
) )
# Когда обновят сайт -- расскоментровать 641-646 и закоментировать 647.
# Поменять комменты 671 и 672 местами.
@dp.message(Command("check")) @dp.message(Command("check"))
@@ -663,7 +675,8 @@ async def cmd_check(message: Message):
new_schedule = parse_html(html) new_schedule = parse_html(html)
prefix = "✅ <b>Знайдено зміни!</b>\n\n" if schedules_differ(last_schedule, new_schedule) else "✓ <b>Графік без змін</b>\n\n" prefix = "✅ <b>Знайдено зміни!</b>\n\n" if schedules_differ(last_schedule, new_schedule) else "✓ <b>Графік без змін</b>\n\n"
result = prefix + format_schedule_message(new_schedule, days_to_show=2) # result = prefix + format_schedule_message(new_schedule, days_to_show=2)
result = prefix + format_schedule_message(new_schedule, days_to_show=1)
await message.answer(result, parse_mode="HTML", reply_markup=get_main_keyboard()) await message.answer(result, parse_mode="HTML", reply_markup=get_main_keyboard())
except Exception as e: except Exception as e:
@@ -690,9 +703,9 @@ async def handle_text(message: Message):
elif text == "📅 Сьогодні": elif text == "📅 Сьогодні":
await cmd_today(message) await cmd_today(message)
# Кнопка "Завтра" # # Кнопка "Завтра"
elif text == "📅 Завтра": # elif text == "📅 Завтра":
await cmd_tomorrow(message) # await cmd_tomorrow(message)
# Кнопка "Оновити" # Кнопка "Оновити"
elif text == "🔄 Оновити": elif text == "🔄 Оновити":