File size: 1,577 Bytes
a5b0b44
 
 
 
 
0fc08c5
 
 
a5b0b44
 
0fc08c5
 
 
 
 
 
 
 
 
 
 
 
a5b0b44
 
 
0fc08c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# firebase/firebase_config.py

import firebase_admin
from firebase_admin import credentials, firestore
import os
import json

FALLBACK_LOG_PATH = "data/logs.json"

def init_firebase():
    try:
        if not firebase_admin._apps:
            cred_path = "firebase_credentials.json"
            if not os.path.exists(cred_path):
                raise FileNotFoundError("Firebase credentials file not found.")

            cred = credentials.Certificate(cred_path)
            firebase_admin.initialize_app(cred)
        return firestore.client()
    except Exception as e:
        print(f"[Firebase ERROR] {e}")
        return None

def log_message_to_firestore(message_dict):
    db = init_firebase()
    if db:
        try:
            chat_ref = db.collection("conversations").document("bot_talk_log")
            chat_ref.set({"messages": firestore.ArrayUnion([message_dict])}, merge=True)
            return
        except Exception as e:
            print(f"[Firestore ERROR] {e}")

    # Fallback if Firebase not available
    log_to_local_file(message_dict)

def log_to_local_file(message_dict):
    os.makedirs("data", exist_ok=True)

    # Read existing logs
    if os.path.exists(FALLBACK_LOG_PATH):
        with open(FALLBACK_LOG_PATH, "r") as f:
            try:
                logs = json.load(f)
            except json.JSONDecodeError:
                logs = []
    else:
        logs = []

    logs.append(message_dict)

    with open(FALLBACK_LOG_PATH, "w") as f:
        json.dump(logs, f, indent=2)

    print("[Local LOG] Message saved to fallback log.")