Files
duty-teller/handlers/commands.py
Nikolay Tatarinov dd960dc5cc Enhance Telegram bot functionality and improve error handling
- Introduced a new function to set the default menu button for the Telegram bot's Web App.
- Updated the initData validation process to provide detailed error messages for authorization failures.
- Refactored the validate_init_data function to return both username and reason for validation failure.
- Enhanced the web application to handle access denial more gracefully, providing users with hints on how to access the calendar.
- Improved the README with additional instructions for configuring the bot's menu button and Web App URL.
- Updated tests to reflect changes in the validation process and error handling.
2026-02-17 19:08:14 +03:00

72 lines
2.3 KiB
Python

"""Command handlers: /start, /help; /start registers user and shows Calendar button."""
import asyncio
import config
from telegram import Update, WebAppInfo, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import CommandHandler, ContextTypes
from db.session import get_session
from db.repository import get_or_create_user
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if not update.message:
return
user = update.effective_user
if not user:
return
full_name = (
" ".join(filter(None, [user.first_name or "", user.last_name or ""])).strip()
or "User"
)
telegram_user_id = user.id
username = user.username
first_name = user.first_name
last_name = user.last_name
def do_get_or_create() -> None:
session = get_session(config.DATABASE_URL)
try:
get_or_create_user(
session,
telegram_user_id=telegram_user_id,
full_name=full_name,
username=username,
first_name=first_name,
last_name=last_name,
)
finally:
session.close()
await asyncio.get_running_loop().run_in_executor(None, do_get_or_create)
text = "Привет! Я бот календаря дежурств. Используй /help для списка команд."
if config.MINI_APP_BASE_URL:
keyboard = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
"📅 Календарь",
web_app=WebAppInfo(url=config.MINI_APP_BASE_URL + "/app/"),
)
],
]
)
await update.message.reply_text(text, reply_markup=keyboard)
else:
await update.message.reply_text(text)
async def help_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if update.message:
await update.message.reply_text(
"Доступные команды:\n"
"/start — Начать и открыть календарь\n"
"/help — Показать эту справку"
)
start_handler = CommandHandler("start", start)
help_handler = CommandHandler("help", help_cmd)