from bs4 import BeautifulSoup
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from django.template.loader import render_to_string
def render_keyboard(template_name, context=None):
if context is None:
context = {}
html_content = render_to_string(template_name, context)
soup = BeautifulSoup(html_content, 'html.parser')
keyboard = []
# Если есть списки
, считаем их строками
rows = soup.find_all('li')
if not rows:
# Если списков нет, собираем все ссылки в одну строку
buttons = []
for a in soup.find_all('a'):
text = a.get_text(strip=True)
callback_data = a.get('href')
buttons.append(InlineKeyboardButton(text=text, callback_data=callback_data))
if buttons:
keyboard.append(buttons)
else:
for row in rows:
row_buttons = []
for a in row.find_all('a'):
text = a.get_text(strip=True)
callback_data = a.get('href')
row_buttons.append(InlineKeyboardButton(text=text, callback_data=callback_data))
if row_buttons:
keyboard.append(row_buttons)
return InlineKeyboardMarkup(keyboard)
def render_message(template_name, context=None):
html_content = render_to_string(template_name, context)
soup = BeautifulSoup(html_content, 'html.parser')
for tag in soup.find_all(['ul', 'li', 'a']):
tag.decompose()
return soup.get_text(separator='\n', strip=True)