45 lines
1.4 KiB
Python
45 lines
1.4 KiB
Python
from datetime import datetime
|
|
from app.settings_cache import SettingsCache
|
|
from app.conversation import get_or_create_user, get_template_rendered
|
|
from app.fsm import BotState, FSM
|
|
|
|
|
|
async def handle_broadcast_send(bot, user_data: dict, db, max_api):
|
|
from app.models.models import BotUser
|
|
from sqlalchemy import select
|
|
|
|
text = user_data.get("text", "").strip()
|
|
if not text:
|
|
await max_api.send_message(
|
|
user_data["user_id"],
|
|
"Укажите текст рассылки в параметре broadcast_text."
|
|
)
|
|
return
|
|
|
|
result = await db.execute(select(BotUser).where(BotUser.consent_given == True))
|
|
users = result.scalars().all()
|
|
sent = 0
|
|
failed = 0
|
|
sent_ids = []
|
|
for u in users:
|
|
try:
|
|
await max_api.send_message(user_id=u.max_user_id, text=text, format="markdown")
|
|
sent += 1
|
|
sent_ids.append(u.max_user_id)
|
|
except Exception:
|
|
failed += 1
|
|
|
|
from app.models.models import BotBroadcast
|
|
bc = BotBroadcast(
|
|
text=text,
|
|
sent_at=datetime.now(),
|
|
recipient_count=len(users),
|
|
recipient_ids=sent_ids,
|
|
status="sent",
|
|
)
|
|
db.add(bc)
|
|
await db.flush()
|
|
|
|
result = f"📨 Рассылка завершена.\nОтправлено: {sent}\nОшибок: {failed}"
|
|
await max_api.send_message(user_data["user_id"], result)
|