File size: 3,420 Bytes
9675d25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9121797
 
 
9675d25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27b4122
9675d25
 
 
 
 
505bcba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9675d25
 
 
 
 
 
 
 
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
import os
from pymongo import MongoClient
import logging
from dotenv import load_dotenv

# Load biến môi trường từ .env (nếu có)
load_dotenv()

# Cấu hình logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Lấy thông tin kết nối MongoDB từ biến môi trường
MONGODB_URI = os.getenv("MONGODB_URI")
MONGODB_DB = os.getenv("MONGODB_DB")
MONGODB_COLLECTION = os.getenv("MONGODB_COLLECTION")

# Kết nối MongoDB sử dụng pymongo
client = MongoClient(MONGODB_URI)
db = client[MONGODB_DB]
collection = db[MONGODB_COLLECTION]


def get_chat_history(user_id: int) -> str:
    try:
        # Truy vấn tất cả các document có user_id, sắp xếp theo timestamp tăng dần
        # Nếu không có trường timestamp, có thể sort theo _id
        docs = list(collection.find({"user_id": user_id}).sort("timestamp", -1).limit(20))
        docs.reverse()

        if not docs:
            logger.info(f"Không tìm thấy dữ liệu cho user_id: {user_id}")
            return ""
        
        conversation_lines = []
        for doc in docs:
            factor = doc.get("factor", "").lower()
            action = doc.get("action", "").lower()
            message = doc.get("message", "")
            
            if action == "freely asking":
                conversation_lines.append(f"User: {message}")
            elif action == "response":
                conversation_lines.append(f"Bot: {message}")
        
        # Ghép các dòng thành chuỗi, mỗi dòng cách nhau bằng xuống dòng
        logger.info("User ID: " + str(user_id))
        return "\n".join(conversation_lines)
    except Exception as e:
        logger.error(f"Lỗi khi lấy lịch sử chat cho user_id {user_id}: {e}")
        return ""

def get_request_history(user_id: int) -> str:
    try:
        # Truy vấn tất cả các document có user_id, sắp xếp theo timestamp tăng dần
        # Nếu không có trường timestamp, có thể sort theo _id
        docs = list(collection.find({"user_id": user_id}).sort("timestamp", -1).limit(15))
        docs.reverse()

        if not docs:
            logger.info(f"Không tìm thấy dữ liệu cho user_id: {user_id}")
            return ""
        
        conversation_lines = []
        for doc in docs:
            factor = doc.get("factor", "").lower()
            action = doc.get("action", "").lower()
            message = doc.get("message", "")
            
            if action == "freely asking":
                # Only keep the most recent 3 messages
                if len(conversation_lines) >= 3:
                    conversation_lines.pop(0)  # Remove oldest message
                conversation_lines.append(message)
        
        # Ghép các dòng thành chuỗi, mỗi dòng cách nhau bằng xuống dòng
        logger.info("User ID: " + str(user_id))
        return "\n".join(conversation_lines)
    except Exception as e:
        logger.error(f"Lỗi khi lấy lịch sử request cho user_id {user_id}: {e}")
        return ""

# if __name__ == '__main__':
#     user_id = int(input("Nhập user_id cần lấy lịch sử chat: ").strip())
#     history = get_chat_history(user_id)
#     if history:
#         print("\nLịch sử trò chuyện:")
#         print(history)
#     else:
#         print(f"Không tìm thấy lịch sử chat cho user_id: {user_id}")