- Implemented the initial version of the web interface. refactor: Begin Telegram bot refactoring - Started restructuring the bot’s code for better maintainability. chore: Migrate to Flask project structure - Reorganized the application to follow Flask's project structure. cleanup: Extensive code cleanup - Removed redundant code and improved readability. Signed-off-by: UdoChudo <stream@udochudo.ru>
73 lines
2.7 KiB
Python
73 lines
2.7 KiB
Python
from datetime import datetime, timezone
|
||
|
||
from app.extensions.db import db
|
||
from app.models import Users, Regions, Subscriptions, UserEvents
|
||
|
||
import telebot # Для логов, можно заменить на кастомный логгер
|
||
|
||
|
||
def is_whitelisted(chat_id):
|
||
"""Проверяет, есть ли пользователь с заданным chat_id в базе данных и не заблокирован ли он."""
|
||
try:
|
||
user = Users.query.filter_by(chat_id=chat_id).first()
|
||
if user:
|
||
if user.is_blocked:
|
||
return False, "Ваш доступ заблокирован."
|
||
return True, None
|
||
return False, None
|
||
except Exception as e:
|
||
telebot.logger.error(f"Ошибка при проверке пользователя: {e}")
|
||
return False, "Произошла ошибка при проверке доступа."
|
||
|
||
|
||
def get_sorted_regions():
|
||
"""Получить список активных регионов, отсортированных по region_id."""
|
||
return (
|
||
Regions.query
|
||
.filter_by(active=True)
|
||
.order_by(Regions.region_id.asc())
|
||
.with_entities(Regions.region_id, Regions.region_name)
|
||
.all()
|
||
)
|
||
|
||
|
||
def get_user_subscribed_regions(chat_id):
|
||
"""Получить список регионов, на которые подписан пользователь."""
|
||
return (
|
||
Regions.query
|
||
.join(Subscriptions, Subscriptions.region_id == Regions.region_id)
|
||
.filter(
|
||
Subscriptions.chat_id == chat_id,
|
||
Subscriptions.active.is_(True),
|
||
Subscriptions.skip.is_(False)
|
||
)
|
||
.order_by(Regions.region_id.asc())
|
||
.with_entities(Regions.region_id, Regions.region_name)
|
||
.all()
|
||
)
|
||
|
||
|
||
def format_regions_list(regions):
|
||
"""Сформировать строку для отображения списка регионов."""
|
||
return '\n'.join([f"{region_id} - {region_name}" for region_id, region_name in regions])
|
||
|
||
|
||
def log_user_event(chat_id, username, action):
|
||
"""Логирует действие пользователя."""
|
||
try:
|
||
timestamp = datetime.now(timezone.utc)
|
||
event = UserEvents(
|
||
chat_id=chat_id,
|
||
telegram_id=username,
|
||
action=action,
|
||
timestamp=timestamp
|
||
)
|
||
db.session.add(event)
|
||
db.session.commit()
|
||
|
||
formatted_time = timestamp.strftime('%Y-%m-%d %H:%M:%S')
|
||
telebot.logger.info(f"User event logged: {chat_id} ({username}) - {action} at {formatted_time}.")
|
||
except Exception as e:
|
||
db.session.rollback()
|
||
telebot.logger.error(f"Error logging user event: {e}")
|