Spaces:
Runtime error
Runtime error
| 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()) |