imstevenleo commited on
Commit
4e127d3
·
verified ·
1 Parent(s): 16675b1

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +78 -0
  2. database.py +422 -0
  3. main.py +566 -0
  4. utils.py +147 -0
app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import logging
8
+
9
+ app = FastAPI()
10
+ cache = TTLCache(maxsize=200, ttl=300) # Increased maxsize to 200
11
+ generator = None
12
+
13
+ class Car(BaseModel):
14
+ model: str
15
+ price: float
16
+ status: str
17
+ description: Optional[str] = None
18
+
19
+ def load_generator():
20
+ global generator
21
+ if generator is None:
22
+ try:
23
+ generator = pipeline('text-generation', model='aubmindlab/aragpt2-base')
24
+ logging.info("Successfully loaded AraGPT2 model")
25
+ except Exception as e:
26
+ logging.error(f"Failed to load AraGPT2 model: {str(e)}")
27
+ raise
28
+ return generator
29
+
30
+ @app.post("/cars/")
31
+ async def add_car(car: Car):
32
+ car_id = create_car(car.model, car.price, car.status, car.description)
33
+ return {"id": car_id, **car.dict()}
34
+
35
+ @app.get("/cars/")
36
+ async def list_cars():
37
+ cached_result = cache.get("all_cars")
38
+ if cached_result:
39
+ return cached_result
40
+ cars = get_all_cars()
41
+ cache["all_cars"] = cars
42
+ return cars
43
+
44
+ @app.get("/cars/{car_id}")
45
+ async def get_car(car_id: int):
46
+ car = get_car_by_id(car_id)
47
+ if not car:
48
+ raise HTTPException(status_code=404, detail="السيارة مو موجودة")
49
+ return car
50
+
51
+ @app.get("/car_info/")
52
+ async def get_car_info(model: str):
53
+ cars = get_all_cars()
54
+ available_cars = [car for car in cars if car['model'].lower() == model.lower()]
55
+
56
+ if not available_cars:
57
+ prompt = f"ما اعرف هذا الموديل '{model}'، ممكن تكلي شنو تعرف عنه؟"
58
+ try:
59
+ gen = load_generator()
60
+ response = gen(prompt, max_length=100, num_return_sequences=1)[0]['generated_text']
61
+ return {"message": response}
62
+ except Exception as e:
63
+ logging.error(f"Error generating response for unknown model: {str(e)}")
64
+ return {"message": "عذرًا، حدث خطأ أثناء توليد الرد."}
65
+
66
+ car = available_cars[0]
67
+ prompt = f"زبون يريد يعرف عن سيارة {car['model']}، سعرها {car['price']} ووضعها {car['status']}، كله بلهجة عراقية طبيعية."
68
+ try:
69
+ gen = load_generator()
70
+ response = gen(prompt, max_length=150, num_return_sequences=1)[0]['generated_text']
71
+ return {"message": response}
72
+ except Exception as e:
73
+ logging.error(f"Error generating response for car info: {str(e)}")
74
+ return {"message": "عذرًا، حدث خطأ أثناء توليد الرد."}
75
+
76
+ @app.get("/")
77
+ async def root():
78
+ return {"message": "CarBot API is running!"}
database.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+ import random
3
+ import string
4
+ import logging
5
+ import re
6
+ from typing import List, Dict, Any, Optional
7
+ from datetime import datetime
8
+
9
+ # Configure logging
10
+ logging.basicConfig(
11
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
12
+ level=logging.INFO,
13
+ handlers=[
14
+ logging.FileHandler("bot.log", encoding='utf-8'),
15
+ logging.StreamHandler()
16
+ ]
17
+ )
18
+ logger = logging.getLogger(__name__)
19
+
20
+ class Database:
21
+ def __init__(self, db_name: str = "cars.db"):
22
+ try:
23
+ self.conn = sqlite3.connect(db_name, check_same_thread=False)
24
+ self.cursor = self.conn.cursor()
25
+ self.create_tables()
26
+ self.update_schema()
27
+ logger.info(f"Successfully connected to database: {db_name}")
28
+ except sqlite3.Error as e:
29
+ logger.error(f"Failed to connect to database: {str(e)}")
30
+ raise
31
+
32
+ def create_tables(self):
33
+ try:
34
+ self.cursor.executescript('''
35
+ -- Table for users
36
+ CREATE TABLE IF NOT EXISTS users (
37
+ user_id INTEGER PRIMARY KEY,
38
+ username TEXT,
39
+ phone TEXT,
40
+ shares INTEGER DEFAULT 0,
41
+ daily_recommendations INTEGER DEFAULT 0,
42
+ last_recommendation_date TEXT
43
+ );
44
+
45
+ -- Table for ads
46
+ CREATE TABLE IF NOT EXISTS ads (
47
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
48
+ user_id INTEGER,
49
+ price TEXT,
50
+ car_name_ar TEXT,
51
+ car_name_en TEXT,
52
+ model TEXT,
53
+ engine_specs TEXT,
54
+ mileage TEXT,
55
+ origin TEXT,
56
+ plate TEXT,
57
+ accidents TEXT,
58
+ specs TEXT,
59
+ notes TEXT,
60
+ location TEXT,
61
+ phone TEXT,
62
+ main_photo TEXT,
63
+ photos TEXT,
64
+ status TEXT DEFAULT 'pending',
65
+ channel_message_id INTEGER,
66
+ created_at TEXT,
67
+ reactions TEXT DEFAULT '',
68
+ FOREIGN KEY(user_id) REFERENCES users(user_id)
69
+ );
70
+
71
+ -- Table for verification codes
72
+ CREATE TABLE IF NOT EXISTS verification_codes (
73
+ user_id INTEGER,
74
+ phone TEXT,
75
+ code TEXT,
76
+ PRIMARY KEY(user_id, phone)
77
+ );
78
+
79
+ -- Table for reactions
80
+ CREATE TABLE IF NOT EXISTS reactions (
81
+ ad_id INTEGER,
82
+ reaction_type TEXT,
83
+ count INTEGER,
84
+ last_updated TEXT,
85
+ PRIMARY KEY(ad_id, reaction_type),
86
+ FOREIGN KEY(ad_id) REFERENCES ads(id)
87
+ );
88
+
89
+ -- Table for stats
90
+ CREATE TABLE IF NOT EXISTS stats (
91
+ id INTEGER PRIMARY KEY,
92
+ subscribers_count INTEGER DEFAULT 1300,
93
+ last_updated TEXT
94
+ );
95
+
96
+ -- Insert default stats
97
+ INSERT OR IGNORE INTO stats (id, subscribers_count) VALUES (1, 1300);
98
+
99
+ -- Indexes for faster queries
100
+ CREATE INDEX IF NOT EXISTS idx_ads_user_id ON ads(user_id);
101
+ CREATE INDEX IF NOT EXISTS idx_ads_status ON ads(status);
102
+ CREATE INDEX IF NOT EXISTS idx_ads_car_name_ar ON ads(car_name_ar);
103
+ CREATE INDEX IF NOT EXISTS idx_ads_location ON ads(location);
104
+ CREATE INDEX IF NOT EXISTS idx_users_phone ON users(phone);
105
+ CREATE INDEX IF NOT EXISTS idx_ads_created_at ON ads(created_at); # Added index on created_at
106
+ ''')
107
+ self.conn.commit()
108
+ logger.info("Database tables and indexes created successfully")
109
+ except sqlite3.Error as e:
110
+ logger.error(f"Error creating tables: {str(e)}")
111
+ raise
112
+
113
+ def update_schema(self):
114
+ try:
115
+ # Check if 'username' column exists in users table
116
+ self.cursor.execute("PRAGMA table_info(users)")
117
+ columns = [info[1] for info in self.cursor.fetchall()]
118
+ if 'username' not in columns:
119
+ self.cursor.execute('ALTER TABLE users ADD COLUMN username TEXT')
120
+ self.conn.commit()
121
+ logger.info("Added 'username' column to users table")
122
+ except sqlite3.Error as e:
123
+ logger.error(f"Error updating schema: {str(e)}")
124
+ raise
125
+
126
+ def add_user(self, user_id: int, username: Optional[str] = None):
127
+ try:
128
+ self.cursor.execute('''
129
+ INSERT OR IGNORE INTO users (user_id, username, shares, daily_recommendations)
130
+ VALUES (?, ?, 0, 0)
131
+ ''', (user_id, username))
132
+ self.cursor.execute('''
133
+ UPDATE stats SET subscribers_count = subscribers_count + 1, last_updated = ?
134
+ WHERE id = 1
135
+ ''', (datetime.now().strftime('%Y-%m-%d %H:%M:%S'),))
136
+ self.conn.commit()
137
+ logger.info(f"User {user_id} (username: {username}) added/updated")
138
+ except sqlite3.Error as e:
139
+ logger.error(f"Error adding user {user_id}: {str(e)}")
140
+ raise
141
+
142
+ def get_user_shares(self, user_id: int) -> int:
143
+ try:
144
+ self.cursor.execute('SELECT shares FROM users WHERE user_id = ?', (user_id,))
145
+ result = self.cursor.fetchone()
146
+ return result[0] if result else 0
147
+ except sqlite3.Error as e:
148
+ logger.error(f"Error retrieving shares for user {user_id}: {str(e)}")
149
+ return 0
150
+
151
+ def increment_shares(self, user_id: int):
152
+ try:
153
+ self.cursor.execute('UPDATE users SET shares = shares + 1 WHERE user_id = ?', (user_id,))
154
+ self.conn.commit()
155
+ logger.info(f"Shares incremented for user {user_id}")
156
+ except sqlite3.Error as e:
157
+ logger.error(f"Error incrementing shares for user {user_id}: {str(e)}")
158
+
159
+ def get_daily_recommendations(self, user_id: int) -> int:
160
+ try:
161
+ self.cursor.execute('SELECT daily_recommendations, last_recommendation_date FROM users WHERE user_id = ?', (user_id,))
162
+ result = self.cursor.fetchone()
163
+ if result:
164
+ count, date = result
165
+ today = datetime.now().strftime('%Y-%m-%d')
166
+ if date != today:
167
+ self.cursor.execute('UPDATE users SET daily_recommendations = 0, last_recommendation_date = ? WHERE user_id = ?', (today, user_id))
168
+ self.conn.commit()
169
+ logger.info(f"Reset daily recommendations for user {user_id} to 0")
170
+ return 0
171
+ return count
172
+ return 0
173
+ except sqlite3.Error as e:
174
+ logger.error(f"Error retrieving daily recommendations for user {user_id}: {str(e)}")
175
+ return 0
176
+
177
+ def increment_recommendations(self, user_id: int):
178
+ try:
179
+ today = datetime.now().strftime('%Y-%m-%d')
180
+ self.cursor.execute('''
181
+ UPDATE users SET daily_recommendations = daily_recommendations + 1,
182
+ last_recommendation_date = ? WHERE user_id = ?
183
+ ''', (today, user_id))
184
+ self.conn.commit()
185
+ logger.info(f"Recommendations incremented for user {user_id}")
186
+ except sqlite3.Error as e:
187
+ logger.error(f"Error incrementing recommendations for user {user_id}: {str(e)}")
188
+
189
+ def generate_verification_code(self, user_id: int, phone: str) -> str:
190
+ try:
191
+ code = ''.join(random.choices(string.digits, k=6))
192
+ self.cursor.execute('INSERT OR REPLACE INTO verification_codes (user_id, phone, code) VALUES (?, ?, ?)',
193
+ (user_id, phone, code))
194
+ self.conn.commit()
195
+ logger.info(f"Generated verification code for user {user_id} with phone {phone}")
196
+ return code
197
+ except sqlite3.Error as e:
198
+ logger.error(f"Error generating verification code for user {user_id}: {str(e)}")
199
+ raise
200
+
201
+ def verify_phone_code(self, user_id: int, code: str) -> bool:
202
+ try:
203
+ self.cursor.execute('SELECT code FROM verification_codes WHERE user_id = ?', (user_id,))
204
+ result = self.cursor.fetchone()
205
+ if result and result[0] == code:
206
+ self.cursor.execute('DELETE FROM verification_codes WHERE user_id = ?', (user_id,))
207
+ self.conn.commit()
208
+ logger.info(f"Phone code verified for user {user_id}")
209
+ return True
210
+ logger.warning(f"Invalid phone code for user {user_id}")
211
+ return False
212
+ except sqlite3.Error as e:
213
+ logger.error(f"Error verifying phone code for user {user_id}: {str(e)}")
214
+ return False
215
+
216
+ def create_car(self, model: str, price: float, status: str, description: Optional[str] = None) -> int:
217
+ try:
218
+ created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
219
+ self.cursor.execute('''
220
+ INSERT INTO ads (price, car_name_ar, car_name_en, model, status, notes, created_at)
221
+ VALUES (?, ?, ?, ?, ?, ?, ?)
222
+ ''', (
223
+ str(price), model, model, model, status, description, created_at
224
+ ))
225
+ ad_id = self.cursor.lastrowid
226
+ self.conn.commit()
227
+ logger.info(f"Created car ad {ad_id} with model {model}")
228
+ return ad_id
229
+ except sqlite3.Error as e:
230
+ logger.error(f"Error creating car ad: {str(e)}")
231
+ raise
232
+
233
+ def get_car_by_id(self, car_id: int) -> Optional[Dict[str, Any]]:
234
+ try:
235
+ self.cursor.execute('SELECT id, price, car_name_ar AS model, status, notes AS description, created_at FROM ads WHERE id = ?', (car_id,))
236
+ car = self.cursor.fetchone()
237
+ if car:
238
+ columns = [desc[0] for desc in self.cursor.description]
239
+ car_dict = dict(zip(columns, car))
240
+ logger.info(f"Retrieved car {car_id}")
241
+ return car_dict
242
+ logger.warning(f"Car {car_id} not found")
243
+ return None
244
+ except sqlite3.Error as e:
245
+ logger.error(f"Error retrieving car {car_id}: {str(e)}")
246
+ raise
247
+
248
+ def get_all_cars(self) -> List[Dict[str, Any]]:
249
+ try:
250
+ self.cursor.execute('SELECT id, price, car_name_ar AS model, status, notes AS description, created_at FROM ads WHERE status = "approved"')
251
+ cars = self.cursor.fetchall()
252
+ columns = [desc[0] for desc in self.cursor.description]
253
+ cars_list = [dict(zip(columns, car)) for car in cars]
254
+ logger.info(f"Retrieved {len(cars_list)} approved cars")
255
+ return cars_list
256
+ except sqlite3.Error as e:
257
+ logger.error(f"Error retrieving all cars: {str(e)}")
258
+ raise
259
+
260
+ def save_ad(self, ad_data: Dict[str, Any], user_id: int) -> int:
261
+ try:
262
+ created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
263
+ self.cursor.execute('''
264
+ INSERT INTO ads (user_id, price, car_name_ar, car_name_en, model, engine_specs, mileage, origin, plate,
265
+ accidents, specs, notes, location, phone, main_photo, photos, created_at)
266
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
267
+ ''', (
268
+ user_id, ad_data['price'], ad_data['car_name_ar'], ad_data['car_name_en'], ad_data['model'],
269
+ ad_data['engine_specs'], ad_data['mileage'], ad_data['origin'], ad_data['plate'], ad_data['accidents'],
270
+ ad_data['specs'], ad_data.get('notes'), ad_data['location'], ad_data['phone'], ad_data['main_photo'],
271
+ ','.join(ad_data['photos']), created_at
272
+ ))
273
+ ad_id = self.cursor.lastrowid
274
+ self.conn.commit()
275
+ logger.info(f"Ad {ad_id} saved for user {user_id}")
276
+ return ad_id
277
+ except sqlite3.Error as e:
278
+ logger.error(f"Error saving ad for user {user_id}: {str(e)}")
279
+ raise
280
+
281
+ def get_ad(self, ad_id: int) -> Optional[Dict[str, Any]]:
282
+ try:
283
+ self.cursor.execute('SELECT * FROM ads WHERE id = ?', (ad_id,))
284
+ ad = self.cursor.fetchone()
285
+ if ad:
286
+ columns = [desc[0] for desc in self.cursor.description]
287
+ ad_dict = dict(zip(columns, ad))
288
+ ad_dict['photos'] = ad_dict['photos'].split(',') if ad_dict['photos'] else []
289
+ logger.info(f"Retrieved ad {ad_id}")
290
+ return ad_dict
291
+ logger.warning(f"Ad {ad_id} not found")
292
+ return None
293
+ except sqlite3.Error as e:
294
+ logger.error(f"Error retrieving ad {ad_id}: {str(e)}")
295
+ raise
296
+
297
+ def update_ad_field(self, ad_id: int, field: str, value: Any):
298
+ try:
299
+ self.cursor.execute(f'UPDATE ads SET {field} = ? WHERE id = ?', (value, ad_id))
300
+ self.conn.commit()
301
+ logger.info(f"Updated field {field} for ad {ad_id}")
302
+ except sqlite3.Error as e:
303
+ logger.error(f"Error updating field {field} for ad {ad_id}: {str(e)}")
304
+ raise
305
+
306
+ def update_ad_status(self, ad_id: int, status: str):
307
+ try:
308
+ self.cursor.execute('UPDATE ads SET status = ? WHERE id = ?', (status, ad_id))
309
+ self.conn.commit()
310
+ logger.info(f"Updated status to {status} for ad {ad_id}")
311
+ except sqlite3.Error as e:
312
+ logger.error(f"Error updating status for ad {ad_id}: {str(e)}")
313
+ raise
314
+
315
+ def get_available_cars(self, user_id: Optional[int] = None) -> List[Dict[str, Any]]:
316
+ try:
317
+ if user_id:
318
+ self.cursor.execute('SELECT * FROM ads WHERE status = "approved" AND user_id = ?', (user_id,))
319
+ else:
320
+ self.cursor.execute('SELECT * FROM ads WHERE status = "approved"')
321
+ ads = self.cursor.fetchall()
322
+ columns = [desc[0] for desc in self.cursor.description]
323
+ result = []
324
+ for ad in ads:
325
+ ad_dict = dict(zip(columns, ad))
326
+ ad_dict['photos'] = ad_dict['photos'].split(',') if ad_dict['photos'] else []
327
+ result.append(ad_dict)
328
+ logger.info(f"Retrieved {len(result)} available cars")
329
+ return result
330
+ except sqlite3.Error as e:
331
+ logger.error(f"Error retrieving available cars: {str(e)}")
332
+ raise
333
+
334
+ def save_channel_message(self, ad_id: int, message_id: int):
335
+ try:
336
+ self.cursor.execute('UPDATE ads SET channel_message_id = ? WHERE id = ?', (message_id, ad_id))
337
+ self.conn.commit()
338
+ logger.info(f"Saved channel message ID {message_id} for ad {ad_id}")
339
+ except sqlite3.Error as e:
340
+ logger.error(f"Error saving channel message for ad {ad_id}: {str(e)}")
341
+ raise
342
+
343
+ def get_total_users(self) -> int:
344
+ try:
345
+ self.cursor.execute("SELECT subscribers_count FROM stats WHERE id = 1")
346
+ result = self.cursor.fetchone()
347
+ count = result[0] if result else 1300
348
+ logger.info(f"Retrieved total users: {count}")
349
+ return count
350
+ except sqlite3.Error as e:
351
+ logger.error(f"Error retrieving total users: {str(e)}")
352
+ return 1300
353
+
354
+ def search_ads(self, query: str) -> List[Dict[str, Any]]:
355
+ try:
356
+ query = query.lower().strip()
357
+ search_terms = re.split(r'\s+', query)
358
+ conditions = ["status = 'approved'"]
359
+ params = []
360
+
361
+ for term in search_terms:
362
+ if term.isdigit() and len(term) == 4: # Model year (e.g., 2020)
363
+ conditions.append("model LIKE ?")
364
+ params.append(f"%{term}%")
365
+ elif re.match(r'(\d+\.?\d*)\s*(دولار|دينار|-)?(?:\s*(\d+\.?\d*))?', term): # Price or range (e.g., 20 دولار, 20-30)
366
+ price_match = re.match(r'(\d+\.?\d*)\s*(دولار|دينار|-)?(?:\s*(\d+\.?\d*))?', term)
367
+ if price_match:
368
+ low_price = float(price_match.group(1))
369
+ currency = price_match.group(2)
370
+ high_price = float(price_match.group(3)) if price_match.group(3) else None
371
+ if currency == '-':
372
+ conditions.append("CAST(replace(replace(price, '$', ''), ' ألف دولار', '000') AS REAL) BETWEEN ? AND ?")
373
+ params.extend([low_price * 1000, high_price * 1000])
374
+ else:
375
+ conditions.append("LOWER(price) LIKE ?")
376
+ params.append(f'%{low_price}%{currency if currency else ""}%')
377
+ else: # Car name, location, or specs
378
+ conditions.append("(LOWER(car_name_ar) LIKE ? OR LOWER(car_name_en) LIKE ? OR LOWER(location) LIKE ? OR LOWER(specs) LIKE ?)")
379
+ params.extend([f"%{term}%", f"%{term}%", f"%{term}%", f"%{term}%"])
380
+
381
+ where_clause = " AND ".join(conditions) if conditions else "1=1"
382
+ self.cursor.execute(f'SELECT * FROM ads WHERE {where_clause}', params)
383
+ ads = self.cursor.fetchall()
384
+ columns = [desc[0] for desc in self.cursor.description]
385
+ result = [dict(zip(columns, ad)) for ad in ads]
386
+ for ad in result:
387
+ ad['photos'] = ad['photos'].split(',') if ad['photos'] else []
388
+ logger.info(f"Found {len(result)} ads for query: {query}")
389
+ return result
390
+ except sqlite3.Error as e:
391
+ logger.error(f"Error searching ads for query {query}: {str(e)}")
392
+ raise
393
+
394
+ def add_reaction(self, ad_id: int, ad: Dict[str, Any]):
395
+ try:
396
+ from utils import generate_reactions
397
+ reactions = generate_reactions(ad)
398
+ self.cursor.execute('UPDATE ads SET reactions = ? WHERE id = ?', (reactions, ad_id))
399
+ self.conn.commit()
400
+ logger.info(f"Added reactions for ad {ad_id}")
401
+ except sqlite3.Error as e:
402
+ logger.error(f"Error adding reactions for ad {ad_id}: {str(e)}")
403
+ raise
404
+ except ImportError:
405
+ logger.error(f"Failed to import generate_reactions from utils for ad {ad_id}")
406
+ raise
407
+
408
+ def extend_ad_duration(self, ad_id: int):
409
+ try:
410
+ self.cursor.execute('UPDATE ads SET status = "approved" WHERE id = ?', (ad_id,))
411
+ self.conn.commit()
412
+ logger.info(f"Extended duration for ad {ad_id}")
413
+ except sqlite3.Error as e:
414
+ logger.error(f"Error extending duration for ad {ad_id}: {str(e)}")
415
+ raise
416
+
417
+ def close(self):
418
+ try:
419
+ self.conn.close()
420
+ logger.info("Database connection closed successfully")
421
+ except sqlite3.Error as e:
422
+ logger.error(f"Error closing database: {str(e)}")
main.py ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 to the public URL of your Space)
49
+ CARBOT_API_URL = "https://imstevenleo-carbot-mixtral.hf.space/chat" # Change to your Space URL
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
+ Shadow]),
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 requests.exceptions.RequestException as e:
261
+ logger.error(f"API request failed: {str(e)}")
262
+ return await generate_fallback_recommendation(user_input)
263
+ except Exception as e:
264
+ logger.error(f"Unexpected error in generate_car_recommendation: {str(e)}")
265
+ return await generate_fallback_recommendation(user_input)
266
+
267
+ # Fallback recommendation
268
+ async def generate_fallback_recommendation(user_input: str) -> str:
269
+ cars = [
270
+ {"name": "كيا أوبتيما", "price": "20-30 ألف دولار", "type": "سيدان", "location": "بغداد"},
271
+ {"name": "تويوتا كورولا", "price": "18-25 ألف دولار", "type": "سيدان", "location": "البصرة"},
272
+ {"name": "هيونداي توسان", "price": "25-35 ألف دولار", "type": "دفع رباعي", "location": "أربيل"}
273
+ ]
274
+ message = (
275
+ f"🔍 ما لقيت نتايج دقيقة لـ '{escape_markdown(user_input)}'، بس أنصحك بهي السيارات الشائعة بالعراق:\n\n" +
276
+ "\n".join([f"🚗 *{c['name']}*: {c['price']} \\({c['type']}\\) \\- متوفرة بـ {c['location']}" for c in cars]) +
277
+ f"\n📌 الذكاء الاصطناعي غير متاح حاليًا! جربي طلب ثاني أو تواصلي مع \\{SUPPORT_USERNAME}\\!"
278
+ )
279
+ return message
280
+
281
+ # Message handler
282
+ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
283
+ user_id = str(update.effective_user.id)
284
+ state = context.user_data.get("state")
285
+ logger.info(f"Message from user {user_id} in state {state}")
286
+
287
+ if update.message.photo and state == UserState.AD_PHOTOS.value:
288
+ if len(context.user_data["photos"]) >= 5:
289
+ await update.message.reply_text(
290
+ escape_markdown("❌ وصلتِ للحد الأقصى (5 صور)! أرسلي 'تم' للمتابعة أو 'قائمة' للرجوع:"),
291
+ parse_mode='MarkdownV2',
292
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
293
+ )
294
+ return
295
+ context.user_data["photos"].append(update.message.photo[-1].file_id)
296
+ await update.message.reply_text(
297
+ escape_markdown(f"📸 تم استلام صورة ({len(context.user_data['photos'])}/5). أرسلي صورة ثانية أو اكتبي 'تم' إذا خلّصتِ:"),
298
+ parse_mode='MarkdownV2',
299
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
300
+ )
301
+ return
302
+
303
+ if not update.message.text:
304
+ await update.message.reply_text(
305
+ escape_markdown("❌ أرسلي نص أو صورة حسب الخطوة!"),
306
+ parse_mode='MarkdownV2',
307
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
308
+ )
309
+ return
310
+
311
+ text = update.message.text.strip()
312
+ logger.info(f"Message from user {user_id} in state {state}: {text}")
313
+
314
+ if state == UserState.CAR_GPT.value:
315
+ if text.lower() == "قائمة":
316
+ await start(update, context)
317
+ return
318
+ recommendation = await generate_car_recommendation(text)
319
+ await update.message.reply_text(
320
+ escape_markdown(recommendation),
321
+ parse_mode='MarkdownV2',
322
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
323
+ )
324
+ return
325
+
326
+ if state == UserState.SEARCHING_AD.value:
327
+ ads = db.search_ads(text)
328
+ if not ads:
329
+ await update.message.reply_text(
330
+ escape_markdown("😔 ما لقيت إعلانات تطابق بحثك! جربي كلمات ثانية:"),
331
+ parse_mode='MarkdownV2',
332
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
333
+ )
334
+ return
335
+ for ad in ads:
336
+ await update.message.reply_text(
337
+ format_ad(ad),
338
+ parse_mode='MarkdownV2',
339
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
340
+ )
341
+ return
342
+
343
+ if state == UserState.AD_CAR_NAME_AR.value:
344
+ context.user_data["ad"]["car_name_ar"] = text
345
+ context.user_data["state"] = UserState.AD_CAR_NAME_EN.value
346
+ await update.message.reply_text(
347
+ escape_markdown("📝 أكتبي اسم السيارة بالإنجليزي (مثل: Toyota Corolla):"),
348
+ parse_mode='MarkdownV2',
349
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
350
+ )
351
+ return
352
+
353
+ if state == UserState.AD_CAR_NAME_EN.value:
354
+ context.user_data["ad"]["car_name_en"] = text
355
+ context.user_data["state"] = UserState.AD_PRICE.value
356
+ await update.message.reply_text(
357
+ escape_markdown("💰 أكتبي السعر (مثل: 25 ألف دولار):"),
358
+ parse_mode='MarkdownV2',
359
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
360
+ )
361
+ return
362
+
363
+ if state == UserState.AD_PRICE.value:
364
+ # تحقق بسيط إن السعر يحتوي على أرقام
365
+ if not any(char.isdigit() for char in text):
366
+ await update.message.reply_text(
367
+ escape_markdown("❌ السعر لازم يحتوي على أرقام! جربي مرة ثانية:"),
368
+ parse_mode='MarkdownV2',
369
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
370
+ )
371
+ return
372
+ context.user_data["ad"]["price"] = text
373
+ context.user_data["state"] = UserState.AD_MODEL.value
374
+ await update.message.reply_text(
375
+ escape_markdown("📅 أكتبي الموديل (مثل: 2020):"),
376
+ parse_mode='MarkdownV2',
377
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
378
+ )
379
+ return
380
+
381
+ if state == UserState.AD_MODEL.value:
382
+ # تحقق بسيط إن الموديل رقم
383
+ if not text.isdigit():
384
+ await update.message.reply_text(
385
+ escape_markdown("❌ الموديل لازم يكون رقم! جربي مرة ثانية:"),
386
+ parse_mode='MarkdownV2',
387
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
388
+ )
389
+ return
390
+ context.user_data["ad"]["model"] = text
391
+ context.user_data["state"] = UserState.AD_ENGINE_SPECS.value
392
+ await update.message.reply_text(
393
+ escape_markdown("⚙️ أكتبي مواصفات المحرك (مثل: 1.8L):"),
394
+ parse_mode='MarkdownV2',
395
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
396
+ )
397
+ return
398
+
399
+ if state == UserState.AD_ENGINE_SPECS.value:
400
+ context.user_data["ad"]["engine_specs"] = text
401
+ context.user_data["state"] = UserState.AD_MILEAGE.value
402
+ await update.message.reply_text(
403
+ escape_markdown("🛣️ أكتبي عداد الأميال (مثل: 50 ألف كم):"),
404
+ parse_mode='MarkdownV2',
405
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
406
+ )
407
+ return
408
+
409
+ if state == UserState.AD_MILEAGE.value:
410
+ context.user_data["ad"]["mileage"] = text
411
+ context.user_data["state"] = UserState.AD_ORIGIN.value
412
+ await update.message.reply_text(
413
+ escape_markdown("🌎 أكتبي الوارد (مثل: أمريكي):"),
414
+ parse_mode='MarkdownV2',
415
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
416
+ )
417
+ return
418
+
419
+ if state == UserState.AD_ORIGIN.value:
420
+ context.user_data["ad"]["origin"] = text
421
+ context.user_data["state"] = UserState.AD_PLATE.value
422
+ await update.message.reply_text(
423
+ escape_markdown("🔢 أكتبي رقم السيارة (مثل: بغداد 123):"),
424
+ parse_mode='MarkdownV2',
425
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
426
+ )
427
+ return
428
+
429
+ if state == UserState.AD_PLATE.value:
430
+ context.user_data["ad"]["plate"] = text
431
+ context.user_data["state"] = UserState.AD_ACCIDENTS.value
432
+ await update.message.reply_text(
433
+ escape_markdown("🚨 أكتبي حالة الحوادث (مثل: بدون حوادث):"),
434
+ parse_mode='MarkdownV2',
435
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
436
+ )
437
+ return
438
+
439
+ if state == UserState.AD_ACCIDENTS.value:
440
+ context.user_data["ad"]["accidents"] = text
441
+ context.user_data["state"] = UserState.AD_SPECS.value
442
+ await update.message.reply_text(
443
+ escape_markdown("🛠️ أكتبي المواصفات (مثل: فل مواصفات):"),
444
+ parse_mode='MarkdownV2',
445
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
446
+ )
447
+ return
448
+
449
+ if state == UserState.AD_SPECS.value:
450
+ context.user_data["ad"]["specs"] = text
451
+ context.user_data["state"] = UserState.AD_NOTES.value
452
+ await update.message.reply_text(
453
+ escape_markdown("📋 أكتبي الملاحظات (مثل: نظيفة، أو اتركيها فاضية إذا ما في):"),
454
+ parse_mode='MarkdownV2',
455
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
456
+ )
457
+ return
458
+
459
+ if state == UserState.AD_NOTES.value:
460
+ context.user_data["ad"]["notes"] = text if text else "غير محدد"
461
+ context.user_data["state"] = UserState.AD_LOCATION.value
462
+ await update.message.reply_text(
463
+ escape_markdown("📍 أكتبي الموقع (مثل: بغداد):"),
464
+ parse_mode='MarkdownV2',
465
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
466
+ )
467
+ return
468
+
469
+ if state == UserState.AD_LOCATION.value:
470
+ context.user_data["ad"]["location"] = text
471
+ context.user_data["state"] = UserState.AD_PHONE.value
472
+ await update.message.reply_text(
473
+ escape_markdown("📞 أكتبي رقم الهاتف (مثال: +9647712345678):"),
474
+ parse_mode='MarkdownV2',
475
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
476
+ )
477
+ return
478
+
479
+ if state == UserState.AD_PHONE.value:
480
+ phone_number, error_message = validate_phone(text)
481
+ if not phone_number:
482
+ await update.message.reply_text(
483
+ escape_markdown(error_message),
484
+ parse_mode='MarkdownV2',
485
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
486
+ )
487
+ logger.warning(f"Invalid phone by user {user_id}: {text}")
488
+ return
489
+ context.user_data["ad"]["phone"] = phone_number
490
+ context.user_data["state"] = UserState.AD_PHOTOS.value
491
+ await update.message.reply_text(
492
+ escape_markdown("📸 أرسلي صور السيارة (من 1 إلى 5 صور). أرسلي صورة واحدة في كل رسالة، وبعد ما تخلّصي أرسلي 'تم':"),
493
+ parse_mode='MarkdownV2',
494
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
495
+ )
496
+ return
497
+
498
+ if state == UserState.AD_PHOTOS.value:
499
+ if text.lower() == "تم":
500
+ if not context.user_data["photos"]:
501
+ await update.message.reply_text(
502
+ escape_markdown("❌ لازم ترسلي صورة وحدة على الأقل! أرسلي صورة أو اكتبي 'قائمة' للرجوع:"),
503
+ parse_mode='MarkdownV2',
504
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
505
+ )
506
+ return
507
+ ad = context.user_data["ad"]
508
+ ad["photos"] = context.user_data["photos"]
509
+ ad["user_id"] = user_id
510
+ ad["created_at"] = datetime.now()
511
+ ad_id = db.add_ad(ad)
512
+ await send_admin_notification(
513
+ context.bot,
514
+ ADMIN_CHAT_ID,
515
+ f"إعلان جديد من {escape_markdown(update.effective_user.username or 'غير معروف')}:\n{format_ad(ad)}",
516
+ ad_id
517
+ )
518
+ await update.message.reply_text(
519
+ escape_markdown("✅ تم إرسال الإعلان للمراجعة! بنخبرك لما ينعتمد."),
520
+ parse_mode='MarkdownV2',
521
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
522
+ )
523
+ context.user_data.clear()
524
+ return
525
+
526
+ if state and state.startswith(UserState.ADMIN_EDIT.value):
527
+ ad_id = context.user_data.get("ad_id")
528
+ try:
529
+ updates = {}
530
+ for field_value in text.split("\n"):
531
+ if ":" in field_value:
532
+ field, value = field_value.split(":", 1)
533
+ updates[field.strip()] = value.strip()
534
+ db.update_ad(ad_id, updates)
535
+ await update.message.reply_text(
536
+ escape_markdown(f"✅ تم تعديل الإعلان {ad_id}\\!"),
537
+ parse_mode='MarkdownV2',
538
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
539
+ )
540
+ context.user_data.clear()
541
+ except Exception as e:
542
+ logger.error(f"Error editing ad {ad_id}: {str(e)}")
543
+ await update.message.reply_text(
544
+ escape_markdown(f"❌ خطأ بتعديل الإعلان! تواصلي مع \\{SUPPORT_USERNAME}\\!"),
545
+ parse_mode='MarkdownV2'
546
+ )
547
+ return
548
+
549
+ await update.message.reply_text(
550
+ escape_markdown("❓ أكتبي شي يناسب الخطوة أو ارجعي للقائمة!"),
551
+ parse_mode='MarkdownV2',
552
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🏠 القائمة", callback_data="main_menu")]])
553
+ )
554
+
555
+ # Main function to run the bot
556
+ def main():
557
+ application = Application.builder().token(TELEGRAM_TOKEN).build()
558
+
559
+ application.add_handler(CommandHandler("start", start))
560
+ application.add_handler(CallbackQueryHandler(button_callback))
561
+ application.add_handler(MessageHandler(filters.ALL & ~filters.COMMAND, handle_message))
562
+
563
+ application.run_polling(allowed_updates=Update.ALL_TYPES)
564
+
565
+ if __name__ == "__main__":
566
+ main()
utils.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ""