Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,56 +1,125 @@
|
|
| 1 |
-
import socket
|
| 2 |
-
from fastapi import FastAPI, Request as FastAPIRequest
|
| 3 |
-
from telegram import Update, Bot
|
| 4 |
-
from telegram.utils.request import Request
|
| 5 |
-
from telegram.ext import Dispatcher, MessageHandler, Filters
|
| 6 |
-
import telegram.vendor.ptb_urllib3.urllib3 as urllib3
|
| 7 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
#
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
cert_reqs='CERT_NONE'
|
| 28 |
-
)
|
| 29 |
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
return {"status": "running"}
|
| 51 |
|
| 52 |
-
|
| 53 |
-
async def
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import json
|
| 3 |
+
import asyncio
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from aiogram import Bot, Dispatcher, types
|
| 6 |
+
from aiogram.filters import Command
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
|
| 9 |
+
# بارگذاری متغیرهای محیطی
|
| 10 |
+
load_dotenv()
|
| 11 |
+
BOT_TOKEN = os.getenv("TELEGRAM_TOKEN")
|
| 12 |
|
| 13 |
+
# مسیر پوشه اصلی برای ذخیره فایلهای کاربران
|
| 14 |
+
USER_DATA_DIR = "user_data"
|
| 15 |
+
os.makedirs(USER_DATA_DIR, exist_ok=True)
|
| 16 |
|
| 17 |
+
# خواندن پرامپت ثابت از فایل
|
| 18 |
+
def read_prompt():
|
| 19 |
+
with open("prapt.txt", "r", encoding="utf-8") as f:
|
| 20 |
+
return f.read()
|
| 21 |
|
| 22 |
+
# ذخیره یا بهروزرسانی فایل PROFILE_UPDATE.json داخل پوشه کاربر
|
| 23 |
+
def save_profile_update(user_id: str, content: str):
|
| 24 |
+
user_dir = os.path.join(USER_DATA_DIR, user_id)
|
| 25 |
+
os.makedirs(user_dir, exist_ok=True)
|
| 26 |
+
file_path = os.path.join(user_dir, "PROFILE_UPDATE.json")
|
| 27 |
+
with open(file_path, "w", encoding="utf-8") as f:
|
| 28 |
+
f.write(content)
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
# ذخیره تاریخچه چت در فایل history.json داخل پوشه کاربر
|
| 31 |
+
def save_chat_history(user_id: str, user_message: str, bot_response: str):
|
| 32 |
+
user_dir = os.path.join(USER_DATA_DIR, user_id)
|
| 33 |
+
os.makedirs(user_dir, exist_ok=True)
|
| 34 |
+
file_path = os.path.join(user_dir, "history.json")
|
| 35 |
+
history = []
|
| 36 |
+
if os.path.exists(file_path):
|
| 37 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 38 |
+
history = json.load(f)
|
| 39 |
+
history.append({"user": user_message, "bot": bot_response, "time": str(datetime.now())})
|
| 40 |
+
with open(file_path, "w", encoding="utf-8") as f:
|
| 41 |
+
json.dump(history, f, ensure_ascii=False, indent=4)
|
| 42 |
|
| 43 |
+
# استخراج بخش [PROFILE_UPDATE]
|
| 44 |
+
def extract_profile_update(response: str) -> str:
|
| 45 |
+
start_tag = "[PROFILE_UPDATE]"
|
| 46 |
+
end_tag = "[/PROFILE_UPDATE]"
|
| 47 |
+
start_idx = response.find(start_tag)
|
| 48 |
+
end_idx = response.find(end_tag)
|
| 49 |
+
if start_idx != -1 and end_idx != -1:
|
| 50 |
+
return response[start_idx + len(start_tag):end_idx].strip()
|
| 51 |
+
return ""
|
| 52 |
|
| 53 |
+
# پاک کردن بخش [PROFILE_UPDATE] از پاسخ
|
| 54 |
+
def clean_response(response: str) -> str:
|
| 55 |
+
start_tag = "[PROFILE_UPDATE]"
|
| 56 |
+
end_tag = "[/PROFILE_UPDATE]"
|
| 57 |
+
start_idx = response.find(start_tag)
|
| 58 |
+
end_idx = response.find(end_tag)
|
| 59 |
+
if start_idx != -1 and end_idx != -1:
|
| 60 |
+
return response[:start_idx] + response[end_idx + len(end_tag):]
|
| 61 |
+
return response
|
| 62 |
|
| 63 |
+
# ارسال درخواست به API میسترال
|
| 64 |
+
async def call_mistral_api(prompt: str, user_message: str, user_id: str):
|
| 65 |
+
system_prompt = read_prompt()
|
| 66 |
|
| 67 |
+
# خواندن محتویات فایل PROFILE_UPDATE.json (اگر وجود داشته باشد)
|
| 68 |
+
user_profile = ""
|
| 69 |
+
user_dir = os.path.join(USER_DATA_DIR, user_id)
|
| 70 |
+
profile_file_path = os.path.join(user_dir, "PROFILE_UPDATE.json")
|
| 71 |
+
if os.path.exists(profile_file_path):
|
| 72 |
+
with open(profile_file_path, "r", encoding="utf-8") as f:
|
| 73 |
+
user_profile = f.read()
|
| 74 |
|
| 75 |
+
# ساخت context
|
| 76 |
+
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 77 |
+
context = [
|
| 78 |
+
{"role": "system", "content": system_prompt},
|
| 79 |
+
{"role": "user", "content": f"تاریخ و ساعت فعلی: {current_time}"},
|
| 80 |
+
{"role": "user", "content": user_profile},
|
| 81 |
+
{"role": "user", "content": user_message}
|
| 82 |
+
]
|
| 83 |
|
| 84 |
+
# برای تست، یک پاسخ نمونه برمی��ردونیم
|
| 85 |
+
return "این یک پاسخ نمونه است. [PROFILE_UPDATE] اطلاعات جدید کاربر [/PROFILE_UPDATE]"
|
|
|
|
| 86 |
|
| 87 |
+
# هندلر دستور /start
|
| 88 |
+
async def start_handler(message: types.Message):
|
| 89 |
+
await message.answer(
|
| 90 |
+
"سلام! به ربات تلگرام من خوش آمدید.\n"
|
| 91 |
+
"شما میتوانید با ارسال متن، با من چت کنید."
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
# هندلر پیامهای متنی
|
| 95 |
+
async def message_handler(message: types.Message):
|
| 96 |
+
user_id = str(message.from_user.id)
|
| 97 |
+
user_message = message.text
|
| 98 |
+
|
| 99 |
+
# فراخوانی API میسترال
|
| 100 |
+
bot_response = await call_mistral_api(read_prompt(), user_message, user_id)
|
| 101 |
+
|
| 102 |
+
# استخراج و ذخیرهسازی [PROFILE_UPDATE]
|
| 103 |
+
profile_update = extract_profile_update(bot_response)
|
| 104 |
+
if profile_update:
|
| 105 |
+
save_profile_update(user_id, profile_update)
|
| 106 |
+
|
| 107 |
+
# پاک کردن بخش [PROFILE_UPDATE] از پاسخ
|
| 108 |
+
cleaned_response = clean_response(bot_response)
|
| 109 |
+
|
| 110 |
+
# ذخیره تاریخچه چت
|
| 111 |
+
save_chat_history(user_id, user_message, cleaned_response)
|
| 112 |
+
|
| 113 |
+
# نمایش پاسخ پاک شده به کاربر
|
| 114 |
+
await message.answer(cleaned_response)
|
| 115 |
+
|
| 116 |
+
# راهاندازی ربات
|
| 117 |
+
async def main():
|
| 118 |
+
bot = Bot(token=BOT_TOKEN)
|
| 119 |
+
dp = Dispatcher()
|
| 120 |
+
dp.message.register(start_handler, Command("start"))
|
| 121 |
+
dp.message.register(message_handler)
|
| 122 |
+
await dp.start_polling(bot)
|
| 123 |
+
|
| 124 |
+
if __name__ == "__main__":
|
| 125 |
+
asyncio.run(main())
|