Files
lottery_ycms/lottery/bot/welcome.py
2025-06-13 21:10:20 +09:00

83 lines
3.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# bot/welcome.py
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ContextTypes
from asgiref.sync import sync_to_async
from bot.models import WelcomeMessage
class WelcomeHandler:
def __init__(self, bot):
"""
Инициализация обработчика приветственных сообщений.
:param bot: экземпляр telegram.Bot для отправки сообщений.
"""
self.bot = bot
self.logger = logging.getLogger(__name__)
@sync_to_async
def get_welcome_config(self):
"""
Получает первую запись настроек приветствия.
"""
try:
return WelcomeMessage.objects.select_related("bot").first()
except WelcomeMessage.DoesNotExist:
return None
async def send_welcome(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""
Отправляет приветственное сообщение с inline-кнопками, расположенными в 3 строки:
1 кнопка, затем 2 и затем 2.
"""
if not update.message:
return
config = await self.get_welcome_config()
if not config:
await update.message.reply_text("Добро пожаловать!")
return
# Формируем список всех кнопок
buttons = []
if config.admin_contact:
buttons.append(InlineKeyboardButton("📞 Связаться с администратором", url=config.admin_contact))
if config.channel_link:
buttons.append(InlineKeyboardButton(" 📢 Канал", url=config.channel_link))
if config.group_link:
buttons.append(InlineKeyboardButton("👥 Группа", url=config.group_link))
if config.custom_link1_name and config.custom_link1_url:
buttons.append(InlineKeyboardButton(config.custom_link1_name, url=config.custom_link1_url))
if config.custom_link2_name and config.custom_link2_url:
buttons.append(InlineKeyboardButton(config.custom_link2_name, url=config.custom_link2_url))
# Распределяем кнопки по рядам: первая строка 1 кнопка, вторая 2, третья 2.
row1 = buttons[0:1] if len(buttons) >= 1 else []
row2 = buttons[1:3] if len(buttons) >= 3 else buttons[1:] if len(buttons) > 1 else []
row3 = buttons[3:5] if len(buttons) >= 5 else []
# Собираем список рядов, исключая пустые строки
keyboard = []
if row1:
keyboard.append(row1)
if row2:
keyboard.append(row2)
if row3:
keyboard.append(row3)
reply_markup = InlineKeyboardMarkup(keyboard) if keyboard else None
# Отправка сообщения с изображением, если задано
if config.welcome_image:
await update.message.reply_photo(
photo=config.welcome_image,
caption=config.welcome_message,
parse_mode="Markdown",
reply_markup=reply_markup
)
else:
await update.message.reply_text(
text=config.welcome_message,
parse_mode="Markdown",
reply_markup=reply_markup
)