Добавлена функция escape_markdown для экранирования специальных символов Markdown перед отправкой сообщений в Telegram. Обновлены обработчики успешной оплаты для использования этой функции, что улучшает форматирование отчетов. Также добавлено детальное логирование для отладки, что поможет в выявлении ошибок при отправке сообщений.
This commit is contained in:
parent
74c37930fe
commit
991f1d74b1
103
main.py
103
main.py
@ -78,11 +78,31 @@ def parse_location(location_str: str) -> str:
|
|||||||
return location_str
|
return location_str
|
||||||
|
|
||||||
|
|
||||||
|
def escape_markdown(text: str) -> str:
|
||||||
|
"""
|
||||||
|
Экранирует специальные символы Markdown для безопасной отправки в Telegram
|
||||||
|
"""
|
||||||
|
if not text:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# Символы которые нужно экранировать для Markdown
|
||||||
|
escape_chars = ['*', '_', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']
|
||||||
|
|
||||||
|
escaped_text = str(text)
|
||||||
|
for char in escape_chars:
|
||||||
|
escaped_text = escaped_text.replace(char, f'\\{char}')
|
||||||
|
|
||||||
|
return escaped_text
|
||||||
|
|
||||||
|
|
||||||
if getenv("DEBUG",'0') == '1':
|
if getenv("DEBUG",'0') == '1':
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
else:
|
else:
|
||||||
logging.basicConfig(level=logging.WARNING)
|
logging.basicConfig(level=logging.WARNING)
|
||||||
|
|
||||||
|
# Временно включаем детальное логирование для отладки
|
||||||
|
logging.getLogger().setLevel(logging.INFO)
|
||||||
|
|
||||||
|
|
||||||
TOKEN = getenv("BOT_TOKEN")
|
TOKEN = getenv("BOT_TOKEN")
|
||||||
BOTNAME = getenv("BOT_NAME")
|
BOTNAME = getenv("BOT_NAME")
|
||||||
@ -482,7 +502,8 @@ async def successful_payment_handler(message: Message, db: OracleDatabase = None
|
|||||||
|
|
||||||
report += "---\n"
|
report += "---\n"
|
||||||
report += f"📋 **VIN:** {vin}\n"
|
report += f"📋 **VIN:** {vin}\n"
|
||||||
report += f"💰 **Transaction ID:** {message.successful_payment.telegram_payment_charge_id}"
|
report += f"💰 **Transaction ID:** {escape_markdown(message.successful_payment.telegram_payment_charge_id)}\n"
|
||||||
|
report += "⚠️ **This report shows salvage/damage history. Please consult with automotive experts for vehicle evaluation.**"
|
||||||
|
|
||||||
# Create keyboard with action buttons
|
# Create keyboard with action buttons
|
||||||
builder = InlineKeyboardBuilder()
|
builder = InlineKeyboardBuilder()
|
||||||
@ -490,7 +511,17 @@ async def successful_payment_handler(message: Message, db: OracleDatabase = None
|
|||||||
builder.button(text="Back to Main Menu", callback_data="main_menu")
|
builder.button(text="Back to Main Menu", callback_data="main_menu")
|
||||||
builder.adjust(2) # Two buttons on one row
|
builder.adjust(2) # Two buttons on one row
|
||||||
|
|
||||||
await message.answer(report, reply_markup=builder.as_markup(), parse_mode="Markdown")
|
logging.info("Attempting to send message with Markdown...")
|
||||||
|
try:
|
||||||
|
await message.answer(report, reply_markup=builder.as_markup(), parse_mode="Markdown")
|
||||||
|
logging.info("Message sent successfully!")
|
||||||
|
except Exception as markdown_error:
|
||||||
|
logging.error(f"Markdown parsing failed: {markdown_error}")
|
||||||
|
logging.info("Attempting to send without Markdown...")
|
||||||
|
# Удаляем markdown символы и отправляем как обычный текст
|
||||||
|
plain_report = report.replace("**", "").replace("*", "")
|
||||||
|
await message.answer(plain_report, reply_markup=builder.as_markup())
|
||||||
|
logging.info("Plain text message sent successfully!")
|
||||||
else:
|
else:
|
||||||
# No detailed information found - refund the payment
|
# No detailed information found - refund the payment
|
||||||
try:
|
try:
|
||||||
@ -538,78 +569,116 @@ async def successful_payment_handler(message: Message, db: OracleDatabase = None
|
|||||||
vin = payload.split(":")[1]
|
vin = payload.split(":")[1]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
logging.info(f"=== DETAILED SALVAGE CHECK DEBUG START for VIN: {vin} ===")
|
||||||
|
|
||||||
# Получаем детальную информацию о salvage записях
|
# Получаем детальную информацию о salvage записях
|
||||||
salvage_records = await database.fetch_salvage_detailed_info(vin)
|
salvage_records = await database.fetch_salvage_detailed_info(vin)
|
||||||
|
logging.info(f"Salvage records count: {len(salvage_records) if salvage_records else 0}")
|
||||||
|
|
||||||
if salvage_records:
|
if salvage_records:
|
||||||
|
# Логируем первую запись для отладки
|
||||||
|
if len(salvage_records) > 0:
|
||||||
|
logging.info(f"First record data: {salvage_records[0]}")
|
||||||
|
|
||||||
# Получаем базовую информацию о VIN для заголовка
|
# Получаем базовую информацию о VIN для заголовка
|
||||||
make, model, year, cnt = await database.fetch_vin_info(vin)
|
make, model, year, cnt = await database.fetch_vin_info(vin)
|
||||||
|
logging.info(f"VIN info: make={make}, model={model}, year={year}, cnt={cnt}")
|
||||||
|
|
||||||
report = f"🚗 **{year} {make} {model}**\n"
|
report = f"🚗 **{year} {make} {model}**\n"
|
||||||
report += f"📋 **VIN:** {vin}\n\n"
|
report += f"📋 **VIN:** {escape_markdown(vin)}\n\n"
|
||||||
report += f"🔍 **DETAILED SALVAGE HISTORY REPORT**\n"
|
report += f"🔍 **DETAILED SALVAGE HISTORY REPORT**\n"
|
||||||
report += f"📊 **Total Records Found:** {len(salvage_records)}\n\n"
|
report += f"📊 **Total Records Found:** {len(salvage_records)}\n\n"
|
||||||
|
|
||||||
|
logging.info(f"Report header created, length: {len(report)}")
|
||||||
|
|
||||||
# Добавляем информацию по каждой записи
|
# Добавляем информацию по каждой записи
|
||||||
for idx, record in enumerate(salvage_records[:5], 1): # Показываем максимум 5 записей
|
for idx, record in enumerate(salvage_records[:5], 1): # Показываем максимум 5 записей
|
||||||
report += f"📋 **Record #{idx}**\n"
|
logging.info(f"Processing record #{idx}: {record}")
|
||||||
|
|
||||||
|
record_text = f"📋 **Record #{idx}**\n"
|
||||||
|
|
||||||
# Дата продажи с красивым форматированием
|
# Дата продажи с красивым форматированием
|
||||||
if record['sale_date']:
|
if record['sale_date']:
|
||||||
formatted_date = format_sale_date(record['sale_date'])
|
formatted_date = format_sale_date(record['sale_date'])
|
||||||
report += f"📅 **Sale Date:** {formatted_date}\n"
|
logging.info(f"Formatted date: {formatted_date}")
|
||||||
|
record_text += f"📅 **Sale Date:** {formatted_date}\n"
|
||||||
|
|
||||||
# Основное повреждение
|
# Основное повреждение
|
||||||
if record['dem1']:
|
if record['dem1']:
|
||||||
report += f"⚠️ **Primary Damage:** {record['dem1']}\n"
|
logging.info(f"Primary damage: {record['dem1']}")
|
||||||
|
record_text += f"⚠️ **Primary Damage:** {escape_markdown(record['dem1'])}\n"
|
||||||
|
|
||||||
# Вторичное повреждение
|
# Вторичное повреждение
|
||||||
if record['dem2']:
|
if record['dem2']:
|
||||||
report += f"⚠️ **Secondary Damage:** {record['dem2']}\n"
|
logging.info(f"Secondary damage: {record['dem2']}")
|
||||||
|
record_text += f"⚠️ **Secondary Damage:** {escape_markdown(record['dem2'])}\n"
|
||||||
|
|
||||||
# Одометр
|
# Одометр
|
||||||
if record['odo']:
|
if record['odo']:
|
||||||
try:
|
try:
|
||||||
odo_value = int(record['odo']) if record['odo'] else 0
|
odo_value = int(record['odo']) if record['odo'] else 0
|
||||||
odo_status = f" ({record['odos']})" if record['odos'] else ""
|
odo_status = f" ({record['odos']})" if record['odos'] else ""
|
||||||
report += f"🛣️ **Odometer:** {odo_value:,} miles{odo_status}\n"
|
logging.info(f"Odometer: {odo_value}, status: {record['odos']}")
|
||||||
|
record_text += f"🛣️ **Odometer:** {odo_value:,} miles{odo_status}\n"
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
report += f"🛣️ **Odometer:** {record['odo']}\n"
|
logging.info(f"Odometer parsing error for: {record['odo']}")
|
||||||
|
record_text += f"🛣️ **Odometer:** {record['odo']}\n"
|
||||||
|
|
||||||
# Стоимость ремонта
|
# Стоимость ремонта
|
||||||
if record['j_rep_cost']:
|
if record['j_rep_cost']:
|
||||||
try:
|
try:
|
||||||
repair_cost = float(record['j_rep_cost']) if record['j_rep_cost'] else 0
|
repair_cost = float(record['j_rep_cost']) if record['j_rep_cost'] else 0
|
||||||
if repair_cost > 0:
|
if repair_cost > 0:
|
||||||
report += f"💰 **Repair Cost:** ${repair_cost:,.2f}\n"
|
logging.info(f"Repair cost: {repair_cost}")
|
||||||
|
record_text += f"💰 **Repair Cost:** ${repair_cost:,.2f}\n"
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
report += f"💰 **Repair Cost:** ${record['j_rep_cost']}\n"
|
logging.info(f"Repair cost parsing error for: {record['j_rep_cost']}")
|
||||||
|
record_text += f"💰 **Repair Cost:** {record['j_rep_cost']}\n"
|
||||||
|
|
||||||
# Состояние двигателя/движения
|
# Состояние двигателя/движения
|
||||||
if record['j_runs_drive']:
|
if record['j_runs_drive']:
|
||||||
report += f"🔧 **Engine Status:** {record['j_runs_drive']}\n"
|
logging.info(f"Engine status: {record['j_runs_drive']}")
|
||||||
|
record_text += f"🔧 **Engine Status:** {escape_markdown(record['j_runs_drive'])}\n"
|
||||||
|
|
||||||
# Локация с конвертированными штатами
|
# Локация с конвертированными штатами
|
||||||
if record['j_locate']:
|
if record['j_locate']:
|
||||||
formatted_location = parse_location(record['j_locate'])
|
formatted_location = parse_location(record['j_locate'])
|
||||||
report += f"📍 **Sale Location:** {formatted_location}\n"
|
logging.info(f"Location: {record['j_locate']} -> {formatted_location}")
|
||||||
|
record_text += f"📍 **Sale Location:** {formatted_location}\n"
|
||||||
|
|
||||||
report += "\n"
|
record_text += "\n"
|
||||||
|
report += record_text
|
||||||
|
logging.info(f"Record #{idx} text length: {len(record_text)}")
|
||||||
|
|
||||||
if len(salvage_records) > 5:
|
if len(salvage_records) > 5:
|
||||||
report += f"📋 **... and {len(salvage_records) - 5} more records**\n\n"
|
report += f"📋 **... and {len(salvage_records) - 5} more records**\n\n"
|
||||||
|
|
||||||
report += "---\n"
|
report += "---\n"
|
||||||
report += f"💰 **Transaction ID:** {message.successful_payment.telegram_payment_charge_id}\n"
|
report += f"💰 **Transaction ID:** {escape_markdown(message.successful_payment.telegram_payment_charge_id)}\n"
|
||||||
report += "⚠️ **This report shows salvage/damage history. Please consult with automotive experts for vehicle evaluation.**"
|
report += "⚠️ **This report shows salvage/damage history. Please consult with automotive experts for vehicle evaluation.**"
|
||||||
|
|
||||||
|
logging.info(f"Final report length: {len(report)}")
|
||||||
|
logging.info("=== REPORT CONTENT START ===")
|
||||||
|
logging.info(report)
|
||||||
|
logging.info("=== REPORT CONTENT END ===")
|
||||||
|
|
||||||
# Создаем клавиатуру
|
# Создаем клавиатуру
|
||||||
builder = InlineKeyboardBuilder()
|
builder = InlineKeyboardBuilder()
|
||||||
builder.button(text="Try another VIN", callback_data="check_vin")
|
builder.button(text="Try another VIN", callback_data="check_vin")
|
||||||
builder.button(text="Back to Main Menu", callback_data="main_menu")
|
builder.button(text="Back to Main Menu", callback_data="main_menu")
|
||||||
builder.adjust(2)
|
builder.adjust(2)
|
||||||
|
|
||||||
await message.answer(report, reply_markup=builder.as_markup(), parse_mode="Markdown")
|
logging.info("Attempting to send message with Markdown...")
|
||||||
|
try:
|
||||||
|
await message.answer(report, reply_markup=builder.as_markup(), parse_mode="Markdown")
|
||||||
|
logging.info("Message sent successfully!")
|
||||||
|
except Exception as markdown_error:
|
||||||
|
logging.error(f"Markdown parsing failed: {markdown_error}")
|
||||||
|
logging.info("Attempting to send without Markdown...")
|
||||||
|
# Удаляем markdown символы и отправляем как обычный текст
|
||||||
|
plain_report = report.replace("**", "").replace("*", "")
|
||||||
|
await message.answer(plain_report, reply_markup=builder.as_markup())
|
||||||
|
logging.info("Plain text message sent successfully!")
|
||||||
|
|
||||||
# Отправляем отдельное сообщение о фотографиях
|
# Отправляем отдельное сообщение о фотографиях
|
||||||
if salvage_records and salvage_records[0]['img_count'] > 0:
|
if salvage_records and salvage_records[0]['img_count'] > 0:
|
||||||
@ -617,7 +686,9 @@ async def successful_payment_handler(message: Message, db: OracleDatabase = None
|
|||||||
photo_message = f"📸 **Photo Information**\n\n"
|
photo_message = f"📸 **Photo Information**\n\n"
|
||||||
photo_message += f"🖼️ **{img_count} damage photos** found in our database for this vehicle.\n"
|
photo_message += f"🖼️ **{img_count} damage photos** found in our database for this vehicle.\n"
|
||||||
photo_message += f"These photos show the actual condition and damage of the vehicle during auction."
|
photo_message += f"These photos show the actual condition and damage of the vehicle during auction."
|
||||||
|
logging.info("Sending photo information message...")
|
||||||
await message.answer(photo_message, parse_mode="Markdown")
|
await message.answer(photo_message, parse_mode="Markdown")
|
||||||
|
logging.info("Photo message sent successfully!")
|
||||||
else:
|
else:
|
||||||
# Нет записей - возвращаем деньги
|
# Нет записей - возвращаем деньги
|
||||||
try:
|
try:
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user