import logging
import requests
from telegram import Update
from telegram.ext import ContextTypes
import config
from utils import fetch_webinars, format_webinar_message
logger = logging.getLogger(__name__)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Команда /start"""
welcome_message = """
Привет! Я бот для проверки домашних заданий и вебинаров.
Команды:
/check - Проверить несделанные уроки
/webinar - Проверить активные онлайн уроки
/help - Помощь
"""
await update.message.reply_text(welcome_message, parse_mode='HTML')
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Команда /help"""
help_text = """
Как пользоваться ботом:
/check - Проверка домашних заданий
- Поиск несделанных уроков
⏱ Проверка занимает 10-30 секунд
/webinar - Активные онлайн уроки
- Проверка активных вебинаровв
⏱ Проверка занимает 3-5 секунд
"""
await update.message.reply_text(help_text, parse_mode='HTML')
async def check_homework(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Команда /check - запускает проверку уроков"""
chat_id = update.effective_chat.id
user_id = update.effective_user.id
username = update.effective_user.username or "unknown"
# Отправляем уведомление что начали работу
status_message = await update.message.reply_text("Запускаю проверку уроков...")
# Формируем данные для n8n
payload = {
"chat_id": chat_id,
"user_id": user_id,
"username": username,
"timestamp": update.message.date.isoformat()
}
headers = {
"Authorization": f"Bearer {config.N8N_SECRET}",
"Content-Type": "application/json"
}
try:
logger.info(f"Sending request to n8n for user {user_id}")
# Отправляем запрос в n8n
response = requests.post(
config.N8N_WEBHOOK_URL,
json=payload,
headers=headers,
timeout=5 # Короткий таймаут т.к. это асинхронный запрос
)
if response.status_code == 200:
await status_message.edit_text(
"✅ Запрос принят!\n"
"🔄 Парсинг сайта и анализ данных...\n"
"⏱ Это займет 10-30 секунд"
)
logger.info(f"Request accepted for user {user_id}")
else:
await status_message.edit_text(
f"Ошибка при отправке запроса. Функция в разработке\n"
f"Код: {response.status_code}"
)
logger.error(f"n8n returned status {response.status_code}")
except requests.Timeout:
await status_message.edit_text("⏱ Запрос обрабатывается (таймаут соединения)")
logger.warning(f"Timeout for user {user_id}")
except Exception as e:
await status_message.edit_text(f"❌ Ошибка: {str(e)}")
logger.error(f"Error for user {user_id}: {e}", exc_info=True)
async def check_webinar(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Команда /webinar - проверяет активные онлайн уроки"""
user_id = update.effective_user.id
# Отправляем уведомление что начали работу
status_message = await update.message.reply_text("Проверяю активные вебинары...")
try:
logger.info(f"Checking webinars for user {user_id}")
# Получаем список вебинаров
webinars = fetch_webinars()
if webinars is None:
await status_message.edit_text(
"❌ Не удалось получить информацию о вебинарах\n"
"Попробуйте позже или обратитесь к администратору\n"
"|@MrForust|mr.forust| Либо же прямо сюда."
)
logger.error(f"Failed to fetch webinars for user {user_id}")
return
# Форматируем и отправляем результат
message = format_webinar_message(webinars)
await status_message.edit_text(message, parse_mode='HTML', disable_web_page_preview=True)
logger.info(f"Webinar check completed for user {user_id}: found {len(webinars)} webinars")
except Exception as e:
await status_message.edit_text(f"❌ Ошибка: {str(e)}")
logger.error(f"Error checking webinars for user {user_id}: {e}", exc_info=True)
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Обработчик ошибок"""
logger.error(f"Update {update} caused error {context.error}", exc_info=context.error)