File size: 2,575 Bytes
402cc44 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | import os
import datetime
import firebase_admin
from firebase_admin import credentials, firestore, messaging
# V5.9.10: Inactivity Poker - Sends push to users inactive for 7 days
def run_inactivity_check():
# 1. Initialize Firebase (assuming creds are in environment or default)
if not firebase_admin._apps:
cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred)
db = firestore.client()
# 2. Fetch CMS templates
print("📡 Fetching CMS templates...")
cms_doc = db.collection('system_config').document('notifications').get()
if cms_doc.exists:
template = cms_doc.to_dict().get('practice_reminder', {})
else:
template = {
'title': 'המורה מתגעגעת 🧮',
'body': 'היי! לא תרגלנו כבר שבוע. יש משהו שאפשר לעזור בו?'
}
print(f"📝 CMS Template loaded: {template.get('title')}")
# 3. Calculate 7 days ago
seven_days_ago = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime('%Y-%m-%d')
print(f"🔍 Searching for users active last on: {seven_days_ago}")
# 4. Query users
users_ref = db.collection('users')
inactive_users = users_ref.where('last_active_date', '==', seven_days_ago).stream()
total_sent = 0
for user in inactive_users:
data = user.to_dict()
fcm_token = data.get('fcm_token') or data.get('fcmToken')
uid = data.get('uid')
name = data.get('name', 'תלמיד/ה')
if fcm_token:
print(f"🚀 Sending push to {name} ({uid})...")
try:
# Build localized message
body = template.get('body', '').replace('{name}', name)
message = messaging.Message(
notification=messaging.Notification(
title=template.get('title'),
body=body,
),
token=fcm_token,
data={
'type': 'practice_reminder',
'click_action': 'FLUTTER_NOTIFICATION_CLICK'
}
)
messaging.send(message)
total_sent += 1
except Exception as e:
print(f"❌ Failed to send to {uid}: {e}")
else:
print(f"⚠️ No FCM token for {name} ({uid})")
print(f"✅ Inactivity check done. Total pushes sent: {total_sent}")
if __name__ == "__main__":
run_inactivity_check()
|