File size: 5,148 Bytes
3d431c0
943c3e5
 
 
 
 
 
3d431c0
943c3e5
 
 
a1d6e10
943c3e5
 
 
a1d6e10
943c3e5
 
 
 
a1d6e10
943c3e5
 
 
 
 
 
 
edbf3c5
943c3e5
 
 
 
 
 
 
 
 
 
 
 
12956c2
943c3e5
 
 
 
 
 
 
 
 
12956c2
943c3e5
 
 
 
 
 
 
 
 
3d431c0
943c3e5
 
 
3d431c0
943c3e5
 
 
 
 
 
 
3d431c0
943c3e5
 
 
 
 
 
 
 
3d431c0
c02e6c2
 
 
 
 
943c3e5
 
5629318
943c3e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import asyncio
from datetime import datetime
from aiogram import Bot, Dispatcher, types
from aiogram.filters import Command
from dotenv import load_dotenv

# بارگذاری متغیرهای محیطی
load_dotenv()
BOT_TOKEN = os.getenv("TELEGRAM_TOKEN")

# مسیر پوشه اصلی برای ذخیره فایل‌های کاربران
USER_DATA_DIR = "user_data"
os.makedirs(USER_DATA_DIR, exist_ok=True)

# خواندن پرامپت ثابت از فایل
def read_prompt():
    with open("prapt.txt", "r", encoding="utf-8") as f:
        return f.read()

# ذخیره یا به‌روزرسانی فایل PROFILE_UPDATE.json داخل پوشه کاربر
def save_profile_update(user_id: str, content: str):
    user_dir = os.path.join(USER_DATA_DIR, user_id)
    os.makedirs(user_dir, exist_ok=True)
    file_path = os.path.join(user_dir, "PROFILE_UPDATE.json")
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(content)

# ذخیره تاریخچه چت در فایل history.json داخل پوشه کاربر
def save_chat_history(user_id: str, user_message: str, bot_response: str):
    user_dir = os.path.join(USER_DATA_DIR, user_id)
    os.makedirs(user_dir, exist_ok=True)
    file_path = os.path.join(user_dir, "history.json")
    history = []
    if os.path.exists(file_path):
        with open(file_path, "r", encoding="utf-8") as f:
            history = json.load(f)
    history.append({"user": user_message, "bot": bot_response, "time": str(datetime.now())})
    with open(file_path, "w", encoding="utf-8") as f:
        json.dump(history, f, ensure_ascii=False, indent=4)

# استخراج بخش [PROFILE_UPDATE]
def extract_profile_update(response: str) -> str:
    start_tag = "[PROFILE_UPDATE]"
    end_tag = "[/PROFILE_UPDATE]"
    start_idx = response.find(start_tag)
    end_idx = response.find(end_tag)
    if start_idx != -1 and end_idx != -1:
        return response[start_idx + len(start_tag):end_idx].strip()
    return ""

# پاک کردن بخش [PROFILE_UPDATE] از پاسخ
def clean_response(response: str) -> str:
    start_tag = "[PROFILE_UPDATE]"
    end_tag = "[/PROFILE_UPDATE]"
    start_idx = response.find(start_tag)
    end_idx = response.find(end_tag)
    if start_idx != -1 and end_idx != -1:
        return response[:start_idx] + response[end_idx + len(end_tag):]
    return response

# ارسال درخواست به API میسترال
async def call_mistral_api(prompt: str, user_message: str, user_id: str):
    system_prompt = read_prompt()

    # خواندن محتویات فایل PROFILE_UPDATE.json (اگر وجود داشته باشد)
    user_profile = ""
    user_dir = os.path.join(USER_DATA_DIR, user_id)
    profile_file_path = os.path.join(user_dir, "PROFILE_UPDATE.json")
    if os.path.exists(profile_file_path):
        with open(profile_file_path, "r", encoding="utf-8") as f:
            user_profile = f.read()

    # ساخت context
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    context = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": f"تاریخ و ساعت فعلی: {current_time}"},
        {"role": "user", "content": user_profile},
        {"role": "user", "content": user_message}
    ]

    # در اینجا باید درخواست به API میسترال ارسال شود
    # برای مثال، با استفاده از کتابخانه requests:
    # response = requests.post(MISTRAL_API_URL, json={"messages": context})
    # return response.json()["choices"][0]["message"]["content"]

    # برای تست، یک پاسخ نمونه برمی‌گردونیم
    return "این یک پاسخ نمونه است. [PROFILE_UPDATE] اطلاعات جدید کاربر [/PROFILE_UPDATE]"

# هندلر دستور /start
async def start_handler(message: types.Message):
    await message.answer(
        "سلام! به ربات تلگرام من خوش آمدید.\n"
        "شما می‌توانید با ارسال متن، با من چت کنید."
    )

# هندلر پیام‌های متنی
async def message_handler(message: types.Message):
    user_id = str(message.from_user.id)
    user_message = message.text

    # فراخوانی API میسترال
    bot_response = await call_mistral_api(read_prompt(), user_message, user_id)

    # استخراج و ذخیره‌سازی [PROFILE_UPDATE]
    profile_update = extract_profile_update(bot_response)
    if profile_update:
        save_profile_update(user_id, profile_update)

    # پاک کردن بخش [PROFILE_UPDATE] از پاسخ
    cleaned_response = clean_response(bot_response)

    # ذخیره تاریخچه چت
    save_chat_history(user_id, user_message, cleaned_response)

    # نمایش پاسخ پاک شده به کاربر
    await message.answer(cleaned_response)

# راه‌اندازی ربات
async def main():
    bot = Bot(token=BOT_TOKEN)
    dp = Dispatcher()
    dp.message.register(start_handler, Command("start"))
    dp.message.register(message_handler)
    await dp.start_polling(bot)

if __name__ == "__main__":
    asyncio.run(main())