Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
|
|
| 1 |
from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify
|
| 2 |
import json
|
| 3 |
import os
|
| 4 |
import logging
|
| 5 |
import threading
|
| 6 |
import time
|
| 7 |
-
import asyncio
|
| 8 |
from datetime import datetime
|
| 9 |
from huggingface_hub import HfApi, hf_hub_download
|
| 10 |
from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
|
|
@@ -12,9 +12,7 @@ from werkzeug.utils import secure_filename
|
|
| 12 |
from dotenv import load_dotenv
|
| 13 |
import requests
|
| 14 |
import uuid
|
| 15 |
-
|
| 16 |
-
from aiogram.filters import CommandStart
|
| 17 |
-
from aiogram.types import Message
|
| 18 |
|
| 19 |
load_dotenv()
|
| 20 |
|
|
@@ -49,9 +47,9 @@ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(
|
|
| 49 |
data_lock = threading.Lock()
|
| 50 |
|
| 51 |
bot = None
|
| 52 |
-
|
|
|
|
| 53 |
|
| 54 |
-
# Вспомогательные функции для работы с данными внутри потока бота
|
| 55 |
def load_data_internal():
|
| 56 |
default_data = {'products': [], 'categories': [], 'orders': {}, 'telegram_users': {}}
|
| 57 |
try:
|
|
@@ -76,18 +74,12 @@ def save_data_internal(data):
|
|
| 76 |
|
| 77 |
with open(DATA_FILE, 'w', encoding='utf-8') as file:
|
| 78 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
| 79 |
-
# Внутри обработчика бота мы не делаем загрузку на HF, чтобы не блокировать,
|
| 80 |
-
# сохраняем только локально. Синхронизация произойдет при периодическом бэкапе.
|
| 81 |
except Exception as e:
|
| 82 |
logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True)
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
dp = Dispatcher()
|
| 88 |
-
|
| 89 |
-
@dp.message(CommandStart())
|
| 90 |
-
async def command_start_handler(message: Message):
|
| 91 |
user_id = message.from_user.id
|
| 92 |
username = message.from_user.username
|
| 93 |
first_name = message.from_user.first_name
|
|
@@ -98,7 +90,6 @@ if TELEGRAM_BOT_TOKEN:
|
|
| 98 |
data['telegram_users'] = {}
|
| 99 |
|
| 100 |
str_id = str(user_id)
|
| 101 |
-
# Сохраняем или обновляем пользователя
|
| 102 |
data['telegram_users'][str_id] = {
|
| 103 |
'username': username,
|
| 104 |
'first_name': first_name,
|
|
@@ -107,8 +98,7 @@ if TELEGRAM_BOT_TOKEN:
|
|
| 107 |
save_data_internal(data)
|
| 108 |
logging.info(f"New Telegram user registered: {user_id}")
|
| 109 |
|
| 110 |
-
|
| 111 |
-
await message.answer("Вы зарегистрированы. Теперь мы сможем присылать вам уведомления.")
|
| 112 |
|
| 113 |
def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY):
|
| 114 |
if not HF_TOKEN_READ and not HF_TOKEN_WRITE:
|
|
@@ -270,34 +260,22 @@ def save_data(data):
|
|
| 270 |
logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True)
|
| 271 |
|
| 272 |
def start_bot_polling():
|
| 273 |
-
if bot
|
| 274 |
-
logging.info("Starting
|
| 275 |
-
|
| 276 |
-
while True:
|
| 277 |
-
try:
|
| 278 |
-
# handle_signals=False критически важен при запуске в отдельном потоке
|
| 279 |
-
# asyncio.run создает и закрывает цикл событий автоматически
|
| 280 |
-
asyncio.run(dp.start_polling(bot, handle_signals=False))
|
| 281 |
-
except Exception as e:
|
| 282 |
-
logging.error(f"Bot polling crashed: {e}. Restarting in 10 seconds...")
|
| 283 |
-
time.sleep(10)
|
| 284 |
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
# с основным ботом, который работает в другом потоке.
|
| 288 |
-
if not TELEGRAM_BOT_TOKEN:
|
| 289 |
return 0
|
| 290 |
|
| 291 |
count = 0
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
except Exception as e:
|
| 300 |
-
logging.error(f"Failed to send message to {user_id}: {e}")
|
| 301 |
return count
|
| 302 |
|
| 303 |
CATALOG_TEMPLATE = '''
|
|
@@ -1795,13 +1773,7 @@ def admin():
|
|
| 1795 |
if message_text:
|
| 1796 |
if telegram_users:
|
| 1797 |
user_ids = list(telegram_users.keys())
|
| 1798 |
-
|
| 1799 |
-
# Запускаем рассылку в event loop текущего потока
|
| 1800 |
-
loop = asyncio.new_event_loop()
|
| 1801 |
-
asyncio.set_event_loop(loop)
|
| 1802 |
-
sent_count = loop.run_until_complete(broadcast_message(user_ids, message_text))
|
| 1803 |
-
loop.close()
|
| 1804 |
-
|
| 1805 |
flash(f"Сообщение отправлено {sent_count} из {len(user_ids)} пользователей.", 'success')
|
| 1806 |
else:
|
| 1807 |
flash("Нет зарегистрированных пользователей Telegram для рассылки.", 'warning')
|
|
|
|
| 1 |
+
|
| 2 |
from flask import Flask, render_template_string, request, redirect, url_for, send_file, flash, jsonify
|
| 3 |
import json
|
| 4 |
import os
|
| 5 |
import logging
|
| 6 |
import threading
|
| 7 |
import time
|
|
|
|
| 8 |
from datetime import datetime
|
| 9 |
from huggingface_hub import HfApi, hf_hub_download
|
| 10 |
from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
|
|
|
|
| 12 |
from dotenv import load_dotenv
|
| 13 |
import requests
|
| 14 |
import uuid
|
| 15 |
+
import telebot
|
|
|
|
|
|
|
| 16 |
|
| 17 |
load_dotenv()
|
| 18 |
|
|
|
|
| 47 |
data_lock = threading.Lock()
|
| 48 |
|
| 49 |
bot = None
|
| 50 |
+
if TELEGRAM_BOT_TOKEN:
|
| 51 |
+
bot = telebot.TeleBot(TELEGRAM_BOT_TOKEN, threaded=False)
|
| 52 |
|
|
|
|
| 53 |
def load_data_internal():
|
| 54 |
default_data = {'products': [], 'categories': [], 'orders': {}, 'telegram_users': {}}
|
| 55 |
try:
|
|
|
|
| 74 |
|
| 75 |
with open(DATA_FILE, 'w', encoding='utf-8') as file:
|
| 76 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
|
|
|
|
|
|
| 77 |
except Exception as e:
|
| 78 |
logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True)
|
| 79 |
|
| 80 |
+
if bot:
|
| 81 |
+
@bot.message_handler(commands=['start'])
|
| 82 |
+
def send_welcome(message):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
user_id = message.from_user.id
|
| 84 |
username = message.from_user.username
|
| 85 |
first_name = message.from_user.first_name
|
|
|
|
| 90 |
data['telegram_users'] = {}
|
| 91 |
|
| 92 |
str_id = str(user_id)
|
|
|
|
| 93 |
data['telegram_users'][str_id] = {
|
| 94 |
'username': username,
|
| 95 |
'first_name': first_name,
|
|
|
|
| 98 |
save_data_internal(data)
|
| 99 |
logging.info(f"New Telegram user registered: {user_id}")
|
| 100 |
|
| 101 |
+
bot.send_message(message.chat.id, "Вы зарегистрированы. Теперь мы сможем присылать вам уведомления.")
|
|
|
|
| 102 |
|
| 103 |
def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY):
|
| 104 |
if not HF_TOKEN_READ and not HF_TOKEN_WRITE:
|
|
|
|
| 260 |
logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True)
|
| 261 |
|
| 262 |
def start_bot_polling():
|
| 263 |
+
if bot:
|
| 264 |
+
logging.info("Starting Telebot polling...")
|
| 265 |
+
bot.infinity_polling()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
|
| 267 |
+
def broadcast_message(user_ids, text):
|
| 268 |
+
if not bot:
|
|
|
|
|
|
|
| 269 |
return 0
|
| 270 |
|
| 271 |
count = 0
|
| 272 |
+
for user_id in user_ids:
|
| 273 |
+
try:
|
| 274 |
+
bot.send_message(chat_id=user_id, text=text)
|
| 275 |
+
count += 1
|
| 276 |
+
time.sleep(0.05)
|
| 277 |
+
except Exception as e:
|
| 278 |
+
logging.error(f"Failed to send message to {user_id}: {e}")
|
|
|
|
|
|
|
| 279 |
return count
|
| 280 |
|
| 281 |
CATALOG_TEMPLATE = '''
|
|
|
|
| 1773 |
if message_text:
|
| 1774 |
if telegram_users:
|
| 1775 |
user_ids = list(telegram_users.keys())
|
| 1776 |
+
sent_count = broadcast_message(user_ids, message_text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1777 |
flash(f"Сообщение отправлено {sent_count} из {len(user_ids)} пользователей.", 'success')
|
| 1778 |
else:
|
| 1779 |
flash("Нет зарегистрированных пользователей Telegram для рассылки.", 'warning')
|