File size: 7,091 Bytes
756c103 |
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Otomatik Hatırlatma Zamanlayıcısı
Belirli aralıklarla takipleri kontrol eder ve hatırlatma gönderir
"""
import os
import time
import logging
from datetime import datetime
from typing import List
# Import our modules
from follow_up_system import FollowUpManager, format_reminder_message
from store_notification import send_store_notification
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class ReminderScheduler:
"""Hatırlatma zamanlayıcısı"""
def __init__(self, check_interval_minutes: int = 10):
"""
Args:
check_interval_minutes: Kaç dakikada bir kontrol yapılacak
"""
self.check_interval = check_interval_minutes * 60 # Saniyeye çevir
self.manager = FollowUpManager()
self.running = False
def send_reminder(self, follow_up) -> bool:
"""Hatırlatma mesajı gönder"""
try:
# Hatırlatma mesajını hazırla
reminder_message = format_reminder_message(follow_up)
# Mehmet Bey'e bildirim gönder
result = send_store_notification(
customer_phone=follow_up.customer_phone,
customer_name=follow_up.customer_name,
product_name=follow_up.product_name,
action="reminder", # Yeni tip: hatırlatma
store_name=follow_up.store_name,
additional_info=f"⏰ TAKİP HATIRLATMASI: {follow_up.original_message}"
)
if result:
logger.info(f"✅ Hatırlatma gönderildi: {follow_up.id}")
return True
else:
logger.error(f"❌ Hatırlatma gönderilemedi: {follow_up.id}")
return False
except Exception as e:
logger.error(f"Hatırlatma gönderme hatası: {e}")
return False
def check_and_send_reminders(self):
"""Bekleyen hatırlatmaları kontrol et ve gönder"""
logger.info("🔍 Hatırlatmalar kontrol ediliyor...")
# Bekleyen hatırlatmaları al
pending = self.manager.get_pending_reminders()
if not pending:
logger.info("📭 Bekleyen hatırlatma yok")
return
logger.info(f"📬 {len(pending)} hatırlatma bulundu")
# Her birini gönder
for follow_up in pending:
logger.info(f"📤 Hatırlatma gönderiliyor: {follow_up.customer_phone}")
if self.send_reminder(follow_up):
# Başarılıysa durumu güncelle
self.manager.mark_as_reminded(follow_up.id)
# Eğer çok kez hatırlatma yapıldıysa tamamlanmış say
if follow_up.reminded_count >= 2:
self.manager.mark_as_completed(follow_up.id)
logger.info(f"✅ Takip tamamlandı (2 hatırlatma yapıldı): {follow_up.id}")
# Mesajlar arası bekle (rate limit)
time.sleep(2)
def send_daily_summary(self):
"""Günlük özet gönder"""
now = datetime.now()
todays = self.manager.get_todays_follow_ups()
if not todays:
return
# Özet mesajı hazırla
summary = f"""
📊 **GÜNLÜK TAKİP ÖZETİ**
📅 {now.strftime('%d.%m.%Y')}
Bugün takip edilmesi gereken {len(todays)} müşteri var:
"""
for i, follow_up in enumerate(todays, 1):
status_emoji = "✅" if follow_up.status == "completed" else "⏳"
summary += f"""
{i}. {status_emoji} {follow_up.customer_phone.replace('whatsapp:', '')}
Ürün: {follow_up.product_name}
Durum: {follow_up.status}
"""
summary += "\n📞 Takipleri tamamlamayı unutmayın!"
# Özet bildirimi gönder
send_store_notification(
customer_phone="whatsapp:+905439362335", # Direkt Mehmet Bey
customer_name="Sistem",
product_name="Günlük Özet",
action="info",
additional_info=summary
)
logger.info("📊 Günlük özet gönderildi")
def run(self):
"""Zamanlayıcıyı başlat"""
self.running = True
logger.info(f"⏰ Hatırlatma zamanlayıcısı başlatıldı")
logger.info(f" Kontrol aralığı: {self.check_interval_minutes} dakika")
last_summary_date = None
while self.running:
try:
# Hatırlatmaları kontrol et
self.check_and_send_reminders()
# Günlük özet zamanı mı? (Saat 09:00 ve 18:00)
now = datetime.now()
if now.hour in [9, 18] and now.date() != last_summary_date:
self.send_daily_summary()
last_summary_date = now.date()
# Bekle
logger.info(f"⏳ {self.check_interval_minutes} dakika bekleniyor...")
time.sleep(self.check_interval)
except KeyboardInterrupt:
logger.info("⏹️ Zamanlayıcı durduruldu")
self.running = False
break
except Exception as e:
logger.error(f"Zamanlayıcı hatası: {e}")
time.sleep(60) # Hata durumunda 1 dakika bekle
def stop(self):
"""Zamanlayıcıyı durdur"""
self.running = False
logger.info("⏹️ Zamanlayıcı durduruluyor...")
def run_scheduler():
"""Ana fonksiyon"""
# Twilio credentials'ları ayarla
os.environ['TWILIO_ACCOUNT_SID'] = 'AC643d14a443b9fbcbc17a2828508870a6'
os.environ['TWILIO_AUTH_TOKEN'] = '9203f0328bfd737dc39bf9be5aa97ca9'
print("""
╔════════════════════════════════════════╗
║ TREK TAKİP HATIRLATMA SİSTEMİ ║
║ Otomatik Müşteri Takibi ║
╚════════════════════════════════════════╝
Ayarlar:
- Kontrol aralığı: 10 dakika
- Günlük özet: 09:00 ve 18:00
- Mehmet Bey: +905439362335
Başlatılıyor...
""")
scheduler = ReminderScheduler(check_interval_minutes=10)
try:
scheduler.run()
except KeyboardInterrupt:
print("\n👋 Sistem kapatılıyor...")
scheduler.stop()
if __name__ == "__main__":
# Test modda çalıştır (1 dakika aralıklarla)
if os.getenv("TEST_MODE"):
print("🧪 TEST MODU - 1 dakika aralıklarla kontrol")
scheduler = ReminderScheduler(check_interval_minutes=1)
else:
scheduler = ReminderScheduler(check_interval_minutes=10)
run_scheduler() |