- 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>
80 lines
3.0 KiB
Python
80 lines
3.0 KiB
Python
from datetime import datetime, timezone
|
||
from threading import Lock
|
||
|
||
import telebot
|
||
|
||
from app import app
|
||
from app.models import UserEvents, Regions, Subscriptions
|
||
from app.models import Users
|
||
from app.extensions.db import db
|
||
|
||
# Lock for database operations
|
||
db_lock = Lock()
|
||
|
||
|
||
|
||
def is_whitelisted(chat_id):
|
||
"""Проверяет, есть ли пользователь с заданным chat_id в базе данных и не заблокирован ли он."""
|
||
try:
|
||
with app.app_context(): # Создаем контекст приложения
|
||
user = db.session.query(Users).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():
|
||
with app.app_context():
|
||
regions = (
|
||
db.session.query(Regions.region_id, Regions.region_name)
|
||
.filter(Regions.active == True)
|
||
.order_by(Regions.region_id.asc())
|
||
.all()
|
||
)
|
||
return regions
|
||
|
||
|
||
def get_user_subscribed_regions(chat_id):
|
||
with app.app_context(): # если вызывается вне контекста Flask
|
||
results = (
|
||
db.session.query(Regions.region_id, Regions.region_name)
|
||
.join(Subscriptions, Subscriptions.region_id == Regions.region_id)
|
||
.filter(
|
||
Subscriptions.chat_id == chat_id,
|
||
Subscriptions.active == True,
|
||
Subscriptions.skip == False
|
||
)
|
||
.order_by(Regions.region_id.asc())
|
||
.all()
|
||
)
|
||
|
||
# results — это список кортежей (region_id, region_name)
|
||
return results
|
||
|
||
|
||
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):
|
||
"""Логирует действие пользователя с использованием ORM."""
|
||
try:
|
||
with app.app_context(): # Создаем контекст приложения
|
||
timestamp = datetime.now(timezone.utc) # Оставляем объект datetime для БД
|
||
formatted_time = timestamp.strftime('%Y-%m-%d %H:%M:%S') # Форматируем для логов
|
||
|
||
event = UserEvents(
|
||
chat_id=chat_id,
|
||
telegram_id=username,
|
||
action=action,
|
||
timestamp=timestamp # В БД передаем объект datetime
|
||
)
|
||
db.session.add(event)
|
||
db.session.commit()
|
||
telebot.logger.info(f"User event logged: {chat_id} ({username}) - {action} at {formatted_time}.")
|
||
except Exception as e:
|
||
telebot.logger.error(f"Error logging user event: {e}") |