Spaces:
Running
Running
Commit
·
c33fdae
0
Parent(s):
Initial commit for CarBot
Browse files- .gitignore +14 -0
- Dockerfile +5 -0
- app.py +56 -0
- database.py +47 -0
- main.py +563 -0
- requirements.txt +8 -0
- utils.py +152 -0
.gitignore
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.env
|
2 |
+
Open ai Key.txt
|
3 |
+
__pycache__/
|
4 |
+
*.log
|
5 |
+
*.db
|
6 |
+
dump.rdb
|
7 |
+
redis-*
|
8 |
+
*.exe
|
9 |
+
*.pdb
|
10 |
+
*.zip
|
11 |
+
redis.windows*.conf
|
12 |
+
*.docx
|
13 |
+
EventLog.dll
|
14 |
+
test_model.py
|
Dockerfile
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.10
|
2 |
+
WORKDIR /app
|
3 |
+
COPY . /app
|
4 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
5 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from pydantic import BaseModel
|
3 |
+
from typing import Optional
|
4 |
+
from database import get_car_by_id, get_all_cars, create_car
|
5 |
+
from transformers import pipeline
|
6 |
+
from cachetools import TTLCache
|
7 |
+
|
8 |
+
app = FastAPI()
|
9 |
+
|
10 |
+
# إعداد التخزين المؤقت للاستعلامات (5 دقائق)
|
11 |
+
cache = TTLCache(maxsize=100, ttl=300)
|
12 |
+
|
13 |
+
# إعداد نموذج AraGPT2 لتوليد النصوص
|
14 |
+
generator = pipeline('text-generation', model='aubmindlab/aragpt2-base')
|
15 |
+
|
16 |
+
class Car(BaseModel):
|
17 |
+
model: str
|
18 |
+
price: float
|
19 |
+
status: str
|
20 |
+
description: Optional[str] = None
|
21 |
+
|
22 |
+
@app.post("/cars/")
|
23 |
+
async def add_car(car: Car):
|
24 |
+
car_id = create_car(car.model, car.price, car.status, car.description)
|
25 |
+
return {"id": car_id, **car.dict()}
|
26 |
+
|
27 |
+
@app.get("/cars/")
|
28 |
+
async def list_cars():
|
29 |
+
cached_result = cache.get("all_cars")
|
30 |
+
if cached_result:
|
31 |
+
return cached_result
|
32 |
+
cars = get_all_cars()
|
33 |
+
cache["all_cars"] = cars
|
34 |
+
return cars
|
35 |
+
|
36 |
+
@app.get("/cars/{car_id}")
|
37 |
+
async def get_car(car_id: int):
|
38 |
+
car = get_car_by_id(car_id)
|
39 |
+
if not car:
|
40 |
+
raise HTTPException(status_code=404, detail="السيارة مو موجودة")
|
41 |
+
return car
|
42 |
+
|
43 |
+
@app.get("/car_info/")
|
44 |
+
async def get_car_info(model: str):
|
45 |
+
cars = get_all_cars()
|
46 |
+
available_cars = [car for car in cars if car['model'].lower() == model.lower()]
|
47 |
+
|
48 |
+
if not available_cars:
|
49 |
+
prompt = f"ما اعرف هذا الموديل '{model}'، ممكن تكلي شنو تعرف عنه؟"
|
50 |
+
response = generator(prompt, max_length=100, num_return_sequences=1)[0]['generated_text']
|
51 |
+
return {"message": response}
|
52 |
+
|
53 |
+
car = available_cars[0]
|
54 |
+
prompt = f"زبون يريد يعرف عن سيارة {car['model']}، سعرها {car['price']} ووضعها {car['status']}، كله بلهجة عراقية طبيعية."
|
55 |
+
response = generator(prompt, max_length=150, num_return_sequences=1)[0]['generated_text']
|
56 |
+
return {"message": response}
|
database.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sqlite3
|
2 |
+
|
3 |
+
def init_db():
|
4 |
+
conn = sqlite3.connect('cars.db')
|
5 |
+
c = conn.cursor()
|
6 |
+
c.execute('''CREATE TABLE IF NOT EXISTS cars
|
7 |
+
(id INTEGER PRIMARY KEY AUTOINCREMENT,
|
8 |
+
model TEXT NOT NULL,
|
9 |
+
price REAL NOT NULL,
|
10 |
+
status TEXT NOT NULL,
|
11 |
+
description TEXT,
|
12 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
|
13 |
+
c.execute("CREATE INDEX IF NOT EXISTS idx_model ON cars (model)")
|
14 |
+
c.execute("CREATE INDEX IF NOT EXISTS idx_status ON cars (status)")
|
15 |
+
c.execute("CREATE INDEX IF NOT EXISTS idx_created_at ON cars (created_at)")
|
16 |
+
conn.commit()
|
17 |
+
conn.close()
|
18 |
+
|
19 |
+
def create_car(model, price, status, description=None):
|
20 |
+
conn = sqlite3.connect('cars.db')
|
21 |
+
c = conn.cursor()
|
22 |
+
c.execute("INSERT INTO cars (model, price, status, description) VALUES (?, ?, ?, ?)",
|
23 |
+
(model, price, status, description))
|
24 |
+
conn.commit()
|
25 |
+
car_id = c.lastrowid
|
26 |
+
conn.close()
|
27 |
+
return car_id
|
28 |
+
|
29 |
+
def get_car_by_id(car_id):
|
30 |
+
conn = sqlite3.connect('cars.db')
|
31 |
+
c = conn.cursor()
|
32 |
+
c.execute("SELECT * FROM cars WHERE id = ?", (car_id,))
|
33 |
+
car = c.fetchone()
|
34 |
+
conn.close()
|
35 |
+
if car:
|
36 |
+
return {"id": car[0], "model": car[1], "price": car[2], "status": car[3], "description": car[4], "created_at": car[5]}
|
37 |
+
return None
|
38 |
+
|
39 |
+
def get_all_cars():
|
40 |
+
conn = sqlite3.connect('cars.db')
|
41 |
+
c = conn.cursor()
|
42 |
+
c.execute("SELECT * FROM cars")
|
43 |
+
cars = c.fetchall()
|
44 |
+
conn.close()
|
45 |
+
return [{"id": car[0], "model": car[1], "price": car[2], "status": car[3], "description": car[4], "created_at": car[5]} for car in cars]
|
46 |
+
|
47 |
+
init_db()
|
main.py
ADDED
@@ -0,0 +1,563 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import random
|
3 |
+
import logging
|
4 |
+
from datetime import datetime, timedelta
|
5 |
+
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
|
6 |
+
from telegram.ext import (
|
7 |
+
Application,
|
8 |
+
CommandHandler,
|
9 |
+
MessageHandler,
|
10 |
+
CallbackQueryHandler,
|
11 |
+
ContextTypes,
|
12 |
+
filters,
|
13 |
+
)
|
14 |
+
from telegram.error import TelegramError
|
15 |
+
from dotenv import load_dotenv
|
16 |
+
import requests
|
17 |
+
from enum import Enum # إضافة لإدارة الحالات
|
18 |
+
from database import Database
|
19 |
+
from utils import (
|
20 |
+
escape_markdown,
|
21 |
+
generate_positive_message,
|
22 |
+
format_ad,
|
23 |
+
validate_phone,
|
24 |
+
send_admin_notification,
|
25 |
+
post_to_channel,
|
26 |
+
delete_channel_post,
|
27 |
+
generate_reactions,
|
28 |
+
)
|
29 |
+
|
30 |
+
# Logging setup
|
31 |
+
logging.basicConfig(
|
32 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
33 |
+
level=logging.INFO,
|
34 |
+
handlers=[
|
35 |
+
logging.FileHandler("bot.log", encoding='utf-8'),
|
36 |
+
logging.StreamHandler()
|
37 |
+
]
|
38 |
+
)
|
39 |
+
logger = logging.getLogger(__name__)
|
40 |
+
|
41 |
+
# Load environment variables
|
42 |
+
load_dotenv()
|
43 |
+
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
|
44 |
+
ADMIN_CHAT_ID = os.getenv("ADMIN_CHAT_ID")
|
45 |
+
CHANNEL_ID = os.getenv("CHANNEL_ID")
|
46 |
+
SUPPORT_USERNAME = os.getenv("SUPPORT_USERNAME", "@Support")
|
47 |
+
|
48 |
+
# API endpoint for CarBot (update this if using Hugging Face Spaces)
|
49 |
+
CARBOT_API_URL = "http://localhost:8000/chat"
|
50 |
+
|
51 |
+
# Initialize database
|
52 |
+
db = Database()
|
53 |
+
|
54 |
+
# تعريف الحالات باستخدام enum لتجنب الأخطاء
|
55 |
+
class UserState(Enum):
|
56 |
+
AD_INTRO = "ad_intro"
|
57 |
+
AD_CAR_NAME_AR = "ad_car_name_ar"
|
58 |
+
AD_CAR_NAME_EN = "ad_car_name_en"
|
59 |
+
AD_PRICE = "ad_price"
|
60 |
+
AD_MODEL = "ad_model"
|
61 |
+
AD_ENGINE_SPECS = "ad_engine_specs"
|
62 |
+
AD_MILEAGE = "ad_mileage"
|
63 |
+
AD_ORIGIN = "ad_origin"
|
64 |
+
AD_PLATE = "ad_plate"
|
65 |
+
AD_ACCIDENTS = "ad_accidents"
|
66 |
+
AD_SPECS = "ad_specs"
|
67 |
+
AD_NOTES = "ad_notes"
|
68 |
+
AD_LOCATION = "ad_location"
|
69 |
+
AD_PHONE = "ad_phone"
|
70 |
+
AD_PHOTOS = "ad_photos"
|
71 |
+
SEARCHING_AD = "searching_ad"
|
72 |
+
CAR_GPT = "car_gpt"
|
73 |
+
ADMIN_EDIT = "admin_edit"
|
74 |
+
|
75 |
+
# Start command
|
76 |
+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
77 |
+
user_id = str(update.effective_user.id)
|
78 |
+
username = update.effective_user.username or "غير معروف"
|
79 |
+
logger.info(f"User {user_id} ({username}) started the bot")
|
80 |
+
db.add_user(user_id, username)
|
81 |
+
|
82 |
+
keyboard = [
|
83 |
+
[InlineKeyboardButton("🚗 إضافة إعلان", callback_data="add_ad")],
|
84 |
+
[InlineKeyboardButton("🔍 البحث عن سيارة", callback_data="search_ad")],
|
85 |
+
[InlineKeyboardButton("🤖 توصية من CarBot", callback_data="car_gpt")],
|
86 |
+
[InlineKeyboardButton("📊 إعلاناتي", callback_data="my_ads")]
|
87 |
+
]
|
88 |
+
if user_id == ADMIN_CHAT_ID:
|
89 |
+
keyboard.append([InlineKeyboardButton("👩💼 لوحة التحكم", callback_data="admin_dashboard")])
|
90 |
+
|
91 |
+
message = f"مرحبًا {escape_markdown(username)}\! 😍 {escape_markdown(generate_positive_message())}\nاختري خيار:"
|
92 |
+
await update.message.reply_text(
|
93 |
+
message,
|
94 |
+
reply_markup=InlineKeyboardMarkup(keyboard),
|
95 |
+
parse_mode='MarkdownV2'
|
96 |
+
)
|
97 |
+
|
98 |
+
# Button callback handler
|
99 |
+
async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
100 |
+
query = update.callback_query
|
101 |
+
await query.answer()
|
102 |
+
user_id = str(query.from_user.id)
|
103 |
+
data = query.data
|
104 |
+
logger.info(f"Button callback: {data} by user {user_id}")
|
105 |
+
|
106 |
+
if data == "main_menu":
|
107 |
+
await start(update, context)
|
108 |
+
return
|
109 |
+
|
110 |
+
if data == "add_ad":
|
111 |
+
context.user_data["state"] = UserState.AD_INTRO.value
|
112 |
+
context.user_data["ad"] = {}
|
113 |
+
context.user_data["photos"] = []
|
114 |
+
intro_message = (
|
115 |
+
"📢 *إضافة إعلان جديد*\n"
|
116 |
+
"لإضافة إعلان، بنحتاج منك المعلومات التالية:\n"
|
117 |
+
"1. اسم السيارة بالعربي\n"
|
118 |
+
"2. اسم السيارة بالإنجليزي\n"
|
119 |
+
"3. السعر\n"
|
120 |
+
"4. الموديل\n"
|
121 |
+
"5. المحرك\n"
|
122 |
+
"6. عداد الأميال\n"
|
123 |
+
"7. الوارد\n"
|
124 |
+
"8. رقم السيارة\n"
|
125 |
+
"9. الحوادث\n"
|
126 |
+
"10. المواصفات\n"
|
127 |
+
"11. الملاحظات\n"
|
128 |
+
"12. الموقع\n"
|
129 |
+
"13. رقم الهاتف\n"
|
130 |
+
"14. صور السيارة (1-5 صور)\n\n"
|
131 |
+
"📌 بناخد المعلومات خطوة بخطوة. هل أنتِ جاهزة؟"
|
132 |
+
)
|
133 |
+
keyboard = [
|
134 |
+
[InlineKeyboardButton("نعم، جاهزة!", callback_data="ad_ready")],
|
135 |
+
[InlineKeyboardButton("لا، رجعيني للقائمة", callback_data="main_menu")]
|
136 |
+
]
|
137 |
+
await query.message.reply_text(
|
138 |
+
escape_markdown(intro_message),
|
139 |
+
reply_markup=InlineKeyboardMarkup(keyboard),
|
140 |
+
parse_mode='MarkdownV2'
|
141 |
+
)
|
142 |
+
return
|
143 |
+
|
144 |
+
if data == "ad_ready":
|
145 |
+
context.user_data["state"] = UserState.AD_CAR_NAME_AR.value
|
146 |
+
await query.message.reply_text(
|
147 |
+
escape_markdown("📝 أكتبي اسم السيارة بالعربي (مثل: تويوتا كورولا):"),
|
148 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]]),
|
149 |
+
parse_mode='MarkdownV2'
|
150 |
+
)
|
151 |
+
return
|
152 |
+
|
153 |
+
if data == "search_ad":
|
154 |
+
context.user_data["state"] = UserState.SEARCHING_AD.value
|
155 |
+
await query.message.reply_text(
|
156 |
+
escape_markdown("🔍 أكتبي تفاصيل البحث (مثل: تويوتا، 2020، بغداد، 20-30 ألف دولار):"),
|
157 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]]),
|
158 |
+
parse_mode='MarkdownV2'
|
159 |
+
)
|
160 |
+
return
|
161 |
+
|
162 |
+
if data == "car_gpt":
|
163 |
+
context.bot_data.setdefault("car_gpt_active", {})[user_id] = True
|
164 |
+
context.user_data["state"] = UserState.CAR_GPT.value
|
165 |
+
await query.message.reply_text(
|
166 |
+
escape_markdown("🤖 أكتبي طلبك لـ CarBot (مثل: سيارة رخيصة 50 ورقة):\nاكتبي 'قائمة' للرجوع."),
|
167 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]]),
|
168 |
+
parse_mode='MarkdownV2'
|
169 |
+
)
|
170 |
+
return
|
171 |
+
|
172 |
+
if data == "my_ads":
|
173 |
+
ads = db.get_user_ads(user_id)
|
174 |
+
if not ads:
|
175 |
+
await query.message.reply_text(
|
176 |
+
escape_markdown("😔 ما عندك إعلانات! جربي تضيفي إعلان جديد."),
|
177 |
+
reply_markup=InlineKeyboardMarkup([
|
178 |
+
[InlineKeyboardButton("🚗 إضافة إعلان", callback_data="add_ad")],
|
179 |
+
[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]
|
180 |
+
]),
|
181 |
+
parse_mode='MarkdownV2'
|
182 |
+
)
|
183 |
+
return
|
184 |
+
for ad in ads:
|
185 |
+
await query.message.reply_text(
|
186 |
+
format_ad(ad),
|
187 |
+
parse_mode='MarkdownV2',
|
188 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
189 |
+
)
|
190 |
+
return
|
191 |
+
|
192 |
+
if data == "admin_dashboard" and user_id == ADMIN_CHAT_ID:
|
193 |
+
stats = db.get_stats()
|
194 |
+
message = f"📊 *لوحة التحكم:*\n👥 *المستخدمين*: {stats['users']}\n🚗 *الإعلانات*: {stats['ads']}\n🔎 *التوصيات*: {stats.get('recommendations', 0)}"
|
195 |
+
await query.message.reply_text(
|
196 |
+
escape_markdown(message),
|
197 |
+
parse_mode='MarkdownV2',
|
198 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
199 |
+
)
|
200 |
+
return
|
201 |
+
|
202 |
+
if data.startswith("admin_approve_") and user_id == ADMIN_CHAT_ID:
|
203 |
+
ad_id = data[len("admin_approve_"):]
|
204 |
+
try:
|
205 |
+
ad = db.get_ad(ad_id)
|
206 |
+
ad['reactions'] = generate_reactions(ad)
|
207 |
+
message_id = await post_to_channel(context, CHANNEL_ID, format_ad(ad), ad.get('photos', [None])[0])
|
208 |
+
if message_id:
|
209 |
+
db.update_ad_status(ad_id, "approved", message_id=message_id)
|
210 |
+
context.job_queue.run_once(
|
211 |
+
delete_channel_post,
|
212 |
+
when=timedelta(days=30),
|
213 |
+
data={"ad_id": ad_id, "message_id": message_id, "channel_id": CHANNEL_ID},
|
214 |
+
name=f"delete_ad_{ad_id}"
|
215 |
+
)
|
216 |
+
await query.message.reply_text(escape_markdown(f"✅ تم الموافقة على الإعلان {ad_id}\\!"), parse_mode='MarkdownV2')
|
217 |
+
logger.info(f"Ad {ad_id} approved by admin {user_id}")
|
218 |
+
else:
|
219 |
+
await query.message.reply_text(escape_markdown(f"�潛 خطأ بنشر الإعلان! تواصلي مع \\{SUPPORT_USERNAME}\\!"), parse_mode='MarkdownV2')
|
220 |
+
logger.error(f"Failed to post ad {ad_id}")
|
221 |
+
except Exception as e:
|
222 |
+
logger.error(f"Error approving ad {ad_id}: {str(e)}")
|
223 |
+
await query.message.reply_text(escape_markdown(f"❌ فشل الموافقة! تواصلي مع \\{SUPPORT_USERNAME}\\!"), parse_mode='MarkdownV2')
|
224 |
+
return
|
225 |
+
|
226 |
+
if data.startswith("admin_reject_") and user_id == ADMIN_CHAT_ID:
|
227 |
+
ad_id = data[len("admin_reject_"):]
|
228 |
+
try:
|
229 |
+
db.update_ad_status(ad_id, "rejected")
|
230 |
+
await query.message.reply_text(escape_markdown(f"🗑️ تم رفض الإعلان {ad_id}\\!"), parse_mode='MarkdownV2')
|
231 |
+
logger.info(f"Ad {ad_id} rejected by admin {user_id}")
|
232 |
+
except Exception as e:
|
233 |
+
logger.error(f"Error rejecting ad {ad_id}: {str(e)}")
|
234 |
+
await query.message.reply_text(escape_markdown(f"❌ خطأ برفض الإعلان! تواصلي مع \\{SUPPORT_USERNAME}\\!"), parse_mode='MarkdownV2')
|
235 |
+
return
|
236 |
+
|
237 |
+
if data.startswith("admin_edit_ad_") and user_id == ADMIN_CHAT_ID:
|
238 |
+
ad_id = data[len("admin_edit_ad_"):]
|
239 |
+
context.user_data["state"] = UserState.ADMIN_EDIT.value + f"_{ad_id}"
|
240 |
+
context.user_data["ad_id"] = ad_id
|
241 |
+
await query.message.reply_text(
|
242 |
+
escape_markdown(f"📝 أكتبي التعديلات للإعلان (ID: {ad_id}):"),
|
243 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]]),
|
244 |
+
parse_mode='MarkdownV2'
|
245 |
+
)
|
246 |
+
return
|
247 |
+
|
248 |
+
await query.message.reply_text(
|
249 |
+
escape_markdown("❓ خيار غير معروف! جربي من القائمة:"),
|
250 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]]),
|
251 |
+
parse_mode='MarkdownV2'
|
252 |
+
)
|
253 |
+
|
254 |
+
# CarBot recommendation generator using API
|
255 |
+
async def generate_car_recommendation(user_input: str) -> str:
|
256 |
+
try:
|
257 |
+
response = requests.post(CARBOT_API_URL, json={"message": user_input})
|
258 |
+
response.raise_for_status()
|
259 |
+
return response.json()["response"]
|
260 |
+
except Exception as e:
|
261 |
+
logger.error(f"Error generating recommendation: {str(e)}")
|
262 |
+
return await generate_fallback_recommendation(user_input)
|
263 |
+
|
264 |
+
# Fallback recommendation
|
265 |
+
async def generate_fallback_recommendation(user_input: str) -> str:
|
266 |
+
cars = [
|
267 |
+
{"name": "كيا أوبتيما", "price": "20-30 ألف دولار", "type": "سيدان", "location": "بغداد"},
|
268 |
+
{"name": "تويوتا كورولا", "price": "18-25 ألف دولار", "type": "سيدان", "location": "البصرة"},
|
269 |
+
{"name": "هيونداي توسان", "price": "25-35 ألف دولار", "type": "دفع رباعي", "location": "أربيل"}
|
270 |
+
]
|
271 |
+
message = (
|
272 |
+
f"🔍 ما لقيت نتايج دقيقة لـ '{escape_markdown(user_input)}'، بس أنصحك بهي السيارات الشائعة بالعراق:\n\n" +
|
273 |
+
"\n".join([f"🚗 *{c['name']}*: {c['price']} \\({c['type']}\\) \\- متوفرة بـ {c['location']}" for c in cars]) +
|
274 |
+
f"\n📌 الذكاء الاصطناعي غير متاح حاليًا! جربي طلب ثاني أو تواصلي مع \\{SUPPORT_USERNAME}\\!"
|
275 |
+
)
|
276 |
+
return message
|
277 |
+
|
278 |
+
# Message handler
|
279 |
+
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
280 |
+
user_id = str(update.effective_user.id)
|
281 |
+
state = context.user_data.get("state")
|
282 |
+
logger.info(f"Message from user {user_id} in state {state}")
|
283 |
+
|
284 |
+
if update.message.photo and state == UserState.AD_PHOTOS.value:
|
285 |
+
if len(context.user_data["photos"]) >= 5:
|
286 |
+
await update.message.reply_text(
|
287 |
+
escape_markdown("❌ وصلتِ للحد الأقصى (5 صور)! أرسلي 'تم' للمتابعة أو 'قائمة' للرجوع:"),
|
288 |
+
parse_mode='MarkdownV2',
|
289 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
290 |
+
)
|
291 |
+
return
|
292 |
+
context.user_data["photos"].append(update.message.photo[-1].file_id)
|
293 |
+
await update.message.reply_text(
|
294 |
+
escape_markdown(f"📸 تم استلام صورة ({len(context.user_data['photos'])}/5). أرسلي صورة ثانية أو اكتبي 'تم' إذا خلّصتِ:"),
|
295 |
+
parse_mode='MarkdownV2',
|
296 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
297 |
+
)
|
298 |
+
return
|
299 |
+
|
300 |
+
if not update.message.text:
|
301 |
+
await update.message.reply_text(
|
302 |
+
escape_markdown("❌ أرسلي نص أو صورة حسب الخطوة!"),
|
303 |
+
parse_mode='MarkdownV2',
|
304 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
305 |
+
)
|
306 |
+
return
|
307 |
+
|
308 |
+
text = update.message.text.strip()
|
309 |
+
logger.info(f"Message from user {user_id} in state {state}: {text}")
|
310 |
+
|
311 |
+
if state == UserState.CAR_GPT.value:
|
312 |
+
if text.lower() == "قائمة":
|
313 |
+
await start(update, context)
|
314 |
+
return
|
315 |
+
recommendation = await generate_car_recommendation(text)
|
316 |
+
await update.message.reply_text(
|
317 |
+
escape_markdown(recommendation),
|
318 |
+
parse_mode='MarkdownV2',
|
319 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
320 |
+
)
|
321 |
+
return
|
322 |
+
|
323 |
+
if state == UserState.SEARCHING_AD.value:
|
324 |
+
ads = db.search_ads(text)
|
325 |
+
if not ads:
|
326 |
+
await update.message.reply_text(
|
327 |
+
escape_markdown("😔 ما لقيت إعلانات تطابق بحثك! جربي كلمات ثانية:"),
|
328 |
+
parse_mode='MarkdownV2',
|
329 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
330 |
+
)
|
331 |
+
return
|
332 |
+
for ad in ads:
|
333 |
+
await update.message.reply_text(
|
334 |
+
format_ad(ad),
|
335 |
+
parse_mode='MarkdownV2',
|
336 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
337 |
+
)
|
338 |
+
return
|
339 |
+
|
340 |
+
if state == UserState.AD_CAR_NAME_AR.value:
|
341 |
+
context.user_data["ad"]["car_name_ar"] = text
|
342 |
+
context.user_data["state"] = UserState.AD_CAR_NAME_EN.value
|
343 |
+
await update.message.reply_text(
|
344 |
+
escape_markdown("📝 أكتبي اسم السيارة بالإنجليزي (مثل: Toyota Corolla):"),
|
345 |
+
parse_mode='MarkdownV2',
|
346 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
347 |
+
)
|
348 |
+
return
|
349 |
+
|
350 |
+
if state == UserState.AD_CAR_NAME_EN.value:
|
351 |
+
context.user_data["ad"]["car_name_en"] = text
|
352 |
+
context.user_data["state"] = UserState.AD_PRICE.value
|
353 |
+
await update.message.reply_text(
|
354 |
+
escape_markdown("💰 أكتبي السعر (مثل: 25 ألف دولار):"),
|
355 |
+
parse_mode='MarkdownV2',
|
356 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
357 |
+
)
|
358 |
+
return
|
359 |
+
|
360 |
+
if state == UserState.AD_PRICE.value:
|
361 |
+
# تحقق بسيط إن السعر يحتوي على أرقام
|
362 |
+
if not any(char.isdigit() for char in text):
|
363 |
+
await update.message.reply_text(
|
364 |
+
escape_markdown("❌ السعر لازم يحتوي على أرقام! جربي مرة ثانية:"),
|
365 |
+
parse_mode='MarkdownV2',
|
366 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
367 |
+
)
|
368 |
+
return
|
369 |
+
context.user_data["ad"]["price"] = text
|
370 |
+
context.user_data["state"] = UserState.AD_MODEL.value
|
371 |
+
await update.message.reply_text(
|
372 |
+
escape_markdown("📅 أكتبي الموديل (مثل: 2020):"),
|
373 |
+
parse_mode='MarkdownV2',
|
374 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
375 |
+
)
|
376 |
+
return
|
377 |
+
|
378 |
+
if state == UserState.AD_MODEL.value:
|
379 |
+
# تحقق بسيط إن الموديل رقم
|
380 |
+
if not text.isdigit():
|
381 |
+
await update.message.reply_text(
|
382 |
+
escape_markdown("❌ الموديل لازم يكون رقم! جربي مرة ثانية:"),
|
383 |
+
parse_mode='MarkdownV2',
|
384 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
385 |
+
)
|
386 |
+
return
|
387 |
+
context.user_data["ad"]["model"] = text
|
388 |
+
context.user_data["state"] = UserState.AD_ENGINE_SPECS.value
|
389 |
+
await update.message.reply_text(
|
390 |
+
escape_markdown("⚙️ أكتبي مواصفات المحرك (مثل: 1.8L):"),
|
391 |
+
parse_mode='MarkdownV2',
|
392 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
393 |
+
)
|
394 |
+
return
|
395 |
+
|
396 |
+
if state == UserState.AD_ENGINE_SPECS.value:
|
397 |
+
context.user_data["ad"]["engine_specs"] = text
|
398 |
+
context.user_data["state"] = UserState.AD_MILEAGE.value
|
399 |
+
await update.message.reply_text(
|
400 |
+
escape_markdown("🛣️ أكتبي عداد الأميال (مثل: 50 ألف كم):"),
|
401 |
+
parse_mode='MarkdownV2',
|
402 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
403 |
+
)
|
404 |
+
return
|
405 |
+
|
406 |
+
if state == UserState.AD_MILEAGE.value:
|
407 |
+
context.user_data["ad"]["mileage"] = text
|
408 |
+
context.user_data["state"] = UserState.AD_ORIGIN.value
|
409 |
+
await update.message.reply_text(
|
410 |
+
escape_markdown("🌎 أكتبي الوارد (مثل: أمريكي):"),
|
411 |
+
parse_mode='MarkdownV2',
|
412 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
413 |
+
)
|
414 |
+
return
|
415 |
+
|
416 |
+
if state == UserState.AD_ORIGIN.value:
|
417 |
+
context.user_data["ad"]["origin"] = text
|
418 |
+
context.user_data["state"] = UserState.AD_PLATE.value
|
419 |
+
await update.message.reply_text(
|
420 |
+
escape_markdown("🔢 أكتبي رقم السيارة (مثل: بغداد 123):"),
|
421 |
+
parse_mode='MarkdownV2',
|
422 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
423 |
+
)
|
424 |
+
return
|
425 |
+
|
426 |
+
if state == UserState.AD_PLATE.value:
|
427 |
+
context.user_data["ad"]["plate"] = text
|
428 |
+
context.user_data["state"] = UserState.AD_ACCIDENTS.value
|
429 |
+
await update.message.reply_text(
|
430 |
+
escape_markdown("🚨 أكتبي حالة الحوادث (مثل: بدون حوادث):"),
|
431 |
+
parse_mode='MarkdownV2',
|
432 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
433 |
+
)
|
434 |
+
return
|
435 |
+
|
436 |
+
if state == UserState.AD_ACCIDENTS.value:
|
437 |
+
context.user_data["ad"]["accidents"] = text
|
438 |
+
context.user_data["state"] = UserState.AD_SPECS.value
|
439 |
+
await update.message.reply_text(
|
440 |
+
escape_markdown("🛠️ أكتبي المواصفات (مثل: فل مواصفات):"),
|
441 |
+
parse_mode='MarkdownV2',
|
442 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
443 |
+
)
|
444 |
+
return
|
445 |
+
|
446 |
+
if state == UserState.AD_SPECS.value:
|
447 |
+
context.user_data["ad"]["specs"] = text
|
448 |
+
context.user_data["state"] = UserState.AD_NOTES.value
|
449 |
+
await update.message.reply_text(
|
450 |
+
escape_markdown("📋 أكتبي الملاحظات (مثل: نظيفة، أو اتركيها فاضية إذا ما في):"),
|
451 |
+
parse_mode='MarkdownV2',
|
452 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
453 |
+
)
|
454 |
+
return
|
455 |
+
|
456 |
+
if state == UserState.AD_NOTES.value:
|
457 |
+
context.user_data["ad"]["notes"] = text if text else "غير محدد"
|
458 |
+
context.user_data["state"] = UserState.AD_LOCATION.value
|
459 |
+
await update.message.reply_text(
|
460 |
+
escape_markdown("📍 أكتبي الموقع (مثل: بغداد):"),
|
461 |
+
parse_mode='MarkdownV2',
|
462 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
463 |
+
)
|
464 |
+
return
|
465 |
+
|
466 |
+
if state == UserState.AD_LOCATION.value:
|
467 |
+
context.user_data["ad"]["location"] = text
|
468 |
+
context.user_data["state"] = UserState.AD_PHONE.value
|
469 |
+
await update.message.reply_text(
|
470 |
+
escape_markdown("📞 أكتبي رقم الهاتف (مثال: +9647712345678):"),
|
471 |
+
parse_mode='MarkdownV2',
|
472 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
473 |
+
)
|
474 |
+
return
|
475 |
+
|
476 |
+
if state == UserState.AD_PHONE.value:
|
477 |
+
phone_number, error_message = validate_phone(text)
|
478 |
+
if not phone_number:
|
479 |
+
await update.message.reply_text(
|
480 |
+
escape_markdown(error_message),
|
481 |
+
parse_mode='MarkdownV2',
|
482 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
483 |
+
)
|
484 |
+
logger.warning(f"Invalid phone by user {user_id}: {text}")
|
485 |
+
return
|
486 |
+
context.user_data["ad"]["phone"] = phone_number
|
487 |
+
context.user_data["state"] = UserState.AD_PHOTOS.value
|
488 |
+
await update.message.reply_text(
|
489 |
+
escape_markdown("📸 أرسلي صور السيارة (من 1 إلى 5 صور). أرسلي صورة واحدة في كل رسالة، وبعد ما تخلّصي أرسلي 'تم':"),
|
490 |
+
parse_mode='MarkdownV2',
|
491 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
492 |
+
)
|
493 |
+
return
|
494 |
+
|
495 |
+
if state == UserState.AD_PHOTOS.value:
|
496 |
+
if text.lower() == "تم":
|
497 |
+
if not context.user_data["photos"]:
|
498 |
+
await update.message.reply_text(
|
499 |
+
escape_markdown("❌ لازم ترسلي صورة وحدة على الأقل! أرسلي صورة أو اكتبي 'قائمة' للرجوع:"),
|
500 |
+
parse_mode='MarkdownV2',
|
501 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
502 |
+
)
|
503 |
+
return
|
504 |
+
ad = context.user_data["ad"]
|
505 |
+
ad["photos"] = context.user_data["photos"]
|
506 |
+
ad["user_id"] = user_id
|
507 |
+
ad["created_at"] = datetime.now()
|
508 |
+
ad_id = db.add_ad(ad)
|
509 |
+
await send_admin_notification(
|
510 |
+
context.bot,
|
511 |
+
ADMIN_CHAT_ID,
|
512 |
+
f"إعلان جديد من {escape_markdown(update.effective_user.username or 'غير معروف')}:\n{format_ad(ad)}",
|
513 |
+
ad_id
|
514 |
+
)
|
515 |
+
await update.message.reply_text(
|
516 |
+
escape_markdown("✅ تم إرسال الإعلان للمراجعة! بنخبرك لما ينعتمد."),
|
517 |
+
parse_mode='MarkdownV2',
|
518 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
519 |
+
)
|
520 |
+
context.user_data.clear()
|
521 |
+
return
|
522 |
+
|
523 |
+
if state and state.startswith(UserState.ADMIN_EDIT.value):
|
524 |
+
ad_id = context.user_data.get("ad_id")
|
525 |
+
try:
|
526 |
+
updates = {}
|
527 |
+
for field_value in text.split("\n"):
|
528 |
+
if ":" in field_value:
|
529 |
+
field, value = field_value.split(":", 1)
|
530 |
+
updates[field.strip()] = value.strip()
|
531 |
+
db.update_ad(ad_id, updates)
|
532 |
+
await update.message.reply_text(
|
533 |
+
escape_markdown(f"✅ تم تعديل الإعلان {ad_id}\\!"),
|
534 |
+
parse_mode='MarkdownV2',
|
535 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
536 |
+
)
|
537 |
+
context.user_data.clear()
|
538 |
+
except Exception as e:
|
539 |
+
logger.error(f"Error editing ad {ad_id}: {str(e)}")
|
540 |
+
await update.message.reply_text(
|
541 |
+
escape_markdown(f"❌ خطأ بتعديل الإعلان! تواصلي مع \\{SUPPORT_USERNAME}\\!"),
|
542 |
+
parse_mode='MarkdownV2'
|
543 |
+
)
|
544 |
+
return
|
545 |
+
|
546 |
+
await update.message.reply_text(
|
547 |
+
escape_markdown("❓ أكتبي شي يناسب الخطوة أو ارجعي للقائمة!"),
|
548 |
+
parse_mode='MarkdownV2',
|
549 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
|
550 |
+
)
|
551 |
+
|
552 |
+
# Main function to run the bot
|
553 |
+
def main():
|
554 |
+
application = Application.builder().token(TELEGRAM_TOKEN).build()
|
555 |
+
|
556 |
+
application.add_handler(CommandHandler("start", start))
|
557 |
+
application.add_handler(CallbackQueryHandler(button_callback))
|
558 |
+
application.add_handler(MessageHandler(filters.ALL & ~filters.COMMAND, handle_message))
|
559 |
+
|
560 |
+
application.run_polling(allowed_updates=Update.ALL_TYPES)
|
561 |
+
|
562 |
+
if __name__ == "__main__":
|
563 |
+
main()
|
requirements.txt
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
fastapi
|
2 |
+
uvicorn
|
3 |
+
transformers==4.44.2
|
4 |
+
torch==2.4.1
|
5 |
+
pydantic
|
6 |
+
python-telegram-bot==20.7
|
7 |
+
python-dotenv==1.0.1
|
8 |
+
cachetools
|
utils.py
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import random
|
3 |
+
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
|
4 |
+
from telegram.error import TelegramError
|
5 |
+
import logging
|
6 |
+
from typing import Dict, Any, Optional, Tuple
|
7 |
+
|
8 |
+
logging.basicConfig(
|
9 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
10 |
+
level=logging.INFO,
|
11 |
+
handlers=[
|
12 |
+
logging.FileHandler("bot.log", encoding='utf-8'),
|
13 |
+
logging.StreamHandler()
|
14 |
+
]
|
15 |
+
)
|
16 |
+
logger = logging.getLogger(__name__)
|
17 |
+
|
18 |
+
def escape_markdown(text: str) -> str:
|
19 |
+
if not text:
|
20 |
+
return ""
|
21 |
+
# إضافة دعم للهروب من المزيد من الأحرف الخاصة في MarkdownV2
|
22 |
+
escape_chars = r'_*[]()~`>#+=|{.!-}'
|
23 |
+
return ''.join(f'\\{char}' if char in escape_chars else char for char in str(text))
|
24 |
+
|
25 |
+
def generate_positive_message() -> str:
|
26 |
+
messages = [
|
27 |
+
"🚗 يلا نلقى سيارة أحلامك! 😍",
|
28 |
+
"💥 جاهزة لأحلى صفقة بالعراق! 🌟",
|
29 |
+
"🔥 بيع وشراء السيارات صار متعة! 🚘",
|
30 |
+
"😎 مع CarBot، كل شي أسهل! 💨"
|
31 |
+
]
|
32 |
+
return random.choice(messages)
|
33 |
+
|
34 |
+
def format_ad(ad: Dict[str, Any]) -> str:
|
35 |
+
if not ad:
|
36 |
+
return escape_markdown("❌ لا توجد بيانات!")
|
37 |
+
reactions = ad.get('reactions', '')
|
38 |
+
photos = ad.get('photos', [])
|
39 |
+
photo_count = len(photos) if photos else 0
|
40 |
+
fields = [
|
41 |
+
f"*السيارة*: {escape_markdown(ad.get('car_name_ar', ''))} \\({escape_markdown(ad.get('car_name_en', ''))}\\)",
|
42 |
+
f"*السعر*: {escape_markdown(ad.get('price', ''))}",
|
43 |
+
f"*الموديل*: {escape_markdown(ad.get('model', ''))}",
|
44 |
+
f"*المحرك*: {escape_markdown(ad.get('engine_specs', ''))}",
|
45 |
+
f"*عداد الأميال*: {escape_markdown(ad.get('mileage', ''))}",
|
46 |
+
f"*الوارد*: {escape_markdown(ad.get('origin', ''))}",
|
47 |
+
f"*رقم السيارة*: {escape_markdown(ad.get('plate', ''))}",
|
48 |
+
f"*الحوادث*: {escape_markdown(ad.get('accidents', ''))}",
|
49 |
+
f"*المواصفات*: {escape_markdown(ad.get('specs', ''))}",
|
50 |
+
f"*الملاحظات*: {escape_markdown(ad.get('notes', 'غير محدد'))}",
|
51 |
+
f"*الموقع*: {escape_markdown(ad.get('location', ''))}",
|
52 |
+
f"*رقم الهاتف*: {escape_markdown(ad.get('phone', ''))}",
|
53 |
+
f"*عدد الصور*: {photo_count}",
|
54 |
+
f"{reactions}"
|
55 |
+
]
|
56 |
+
return "\n".join(fields)
|
57 |
+
|
58 |
+
def validate_phone(phone: str) -> Tuple[Optional[str], Optional[str]]:
|
59 |
+
if not phone:
|
60 |
+
logger.warning("Empty phone number provided")
|
61 |
+
return None, "❌ أدخلي رقم هاتف صحيح (مثال: +9647712345678)"
|
62 |
+
try:
|
63 |
+
arabic_to_latin = str.maketrans('٠١٢٣٤٥٦٧٨٩', '0123456789')
|
64 |
+
phone = phone.translate(arabic_to_latin)
|
65 |
+
phone = re.sub(r'[\s\-]', '', phone)
|
66 |
+
# تحقق إضافي للتأكد إن الرقم يبدأ بـ +964 أو 0
|
67 |
+
if not (phone.startswith('+964') or phone.startswith('0')):
|
68 |
+
return None, "❌ الرقم لازم يبدأ بـ +964 أو 0! جربي مرة ثانية"
|
69 |
+
pattern = r'^(\+964|0)(77[0-7]|78[0-9]|79[0-9]|75[0-1][0-9])[0-9]{7}$'
|
70 |
+
if re.match(pattern, phone):
|
71 |
+
if not phone.startswith('+964'):
|
72 |
+
phone = '+964' + phone.lstrip('0')
|
73 |
+
return phone, None
|
74 |
+
logger.warning(f"Invalid phone number format: {phone}")
|
75 |
+
return None, "❌ رقم غير صحيح! جربي مثال: +9647712345678"
|
76 |
+
except Exception as e:
|
77 |
+
logger.error(f"Error validating phone number: {str(e)}")
|
78 |
+
return None, "❌ خطأ بالتحقق من الرقم! جربي مرة ثانية"
|
79 |
+
|
80 |
+
async def send_admin_notification(bot, admin_id: str, message: str, ad_id: Optional[int] = None):
|
81 |
+
if not admin_id:
|
82 |
+
logger.error("Admin chat ID not set")
|
83 |
+
return
|
84 |
+
try:
|
85 |
+
keyboard = []
|
86 |
+
if ad_id:
|
87 |
+
keyboard.append([
|
88 |
+
InlineKeyboardButton("✅ الموافقة", callback_data=f"admin_approve_{ad_id}"),
|
89 |
+
InlineKeyboardButton("❌ الرفض", callback_data=f"admin_reject_{ad_id}"),
|
90 |
+
InlineKeyboardButton("✏️ تعديل", callback_data=f"admin_edit_ad_{ad_id}")
|
91 |
+
])
|
92 |
+
await bot.send_message(
|
93 |
+
chat_id=admin_id,
|
94 |
+
text=escape_markdown(message),
|
95 |
+
reply_markup=InlineKeyboardMarkup(keyboard),
|
96 |
+
parse_mode='MarkdownV2'
|
97 |
+
)
|
98 |
+
logger.info(f"Admin notification sent: {message}")
|
99 |
+
except TelegramError as e:
|
100 |
+
logger.error(f"Failed to send admin notification: {str(e)}")
|
101 |
+
|
102 |
+
async def post_to_channel(context, channel_id: str, ad_text: str, photo: Optional[str] = None) -> Optional[int]:
|
103 |
+
try:
|
104 |
+
if photo:
|
105 |
+
message = await context.bot.send_photo(
|
106 |
+
chat_id=channel_id,
|
107 |
+
photo=photo,
|
108 |
+
caption=ad_text,
|
109 |
+
parse_mode='MarkdownV2'
|
110 |
+
)
|
111 |
+
else:
|
112 |
+
message = await context.bot.send_message(
|
113 |
+
chat_id=channel_id,
|
114 |
+
text=ad_text,
|
115 |
+
parse_mode='MarkdownV2'
|
116 |
+
)
|
117 |
+
logger.info(f"Posted to channel {channel_id}: {message.message_id}")
|
118 |
+
return message.message_id
|
119 |
+
except TelegramError as e:
|
120 |
+
logger.error(f"Failed to post to channel {channel_id}: {str(e)}")
|
121 |
+
return None
|
122 |
+
|
123 |
+
async def delete_channel_post(context):
|
124 |
+
from database import Database
|
125 |
+
try:
|
126 |
+
job_data = context.job.data
|
127 |
+
await context.bot.delete_message(
|
128 |
+
chat_id=job_data["channel_id"],
|
129 |
+
message_id=job_data["message_id"]
|
130 |
+
)
|
131 |
+
db = Database()
|
132 |
+
db.update_ad_status(job_data["ad_id"], "expired")
|
133 |
+
logger.info(f"Deleted channel post {job_data['message_id']} for ad {job_data['ad_id']}")
|
134 |
+
except TelegramError as e:
|
135 |
+
logger.error(f"Failed to delete channel post: {str(e)}")
|
136 |
+
|
137 |
+
def generate_reactions(ad: Dict[str, Any]) -> str:
|
138 |
+
reactions = ['👍', '❤️', '⭐', '🔥']
|
139 |
+
try:
|
140 |
+
price = float(re.sub(r'[^\d.]', '', ad.get('price', '0')))
|
141 |
+
num_reactions = random.randint(5, min(15, int(price / 1000)))
|
142 |
+
selected_reactions = random.choices(reactions, k=num_reactions)
|
143 |
+
reaction_counts = {r: selected_reactions.count(r) for r in set(selected_reactions)}
|
144 |
+
return ''.join([f"{r}{count} " for r, count in reaction_counts.items()])
|
145 |
+
except Exception as e:
|
146 |
+
logger.error(f"Error generating reactions: {str(e)}")
|
147 |
+
return ""
|
148 |
+
|
149 |
+
# دالة جديدة لتحسين الردود (اختياري)
|
150 |
+
def generate_smart_response(user_input: str, ad_data: Dict[str, Any]) -> str:
|
151 |
+
# هذه دالة اختيارية يمكن استخدامها لتوليد ردود ذكية بناءً على بيانات الإعلان
|
152 |
+
return f"شكرًا على سؤالك عن {ad_data.get('car_name_ar', '')}! هذه السيارة متوفرة بسعر {ad_data.get('price', '')}."
|