BuddyMath / inactivity_poker.py
dotandru's picture
V5.9.10: Inactivity Push Notifications & CMS Implementation
402cc44
Raw
History Blame Contribute Delete
2.58 kB
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()