-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.py
More file actions
433 lines (360 loc) · 14.8 KB
/
Copy pathscript.py
File metadata and controls
433 lines (360 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import requests
import json
import time
import os
import sys
import logging
from datetime import datetime, timezone, timedelta
from dotenv import load_dotenv
# Load environment variables (for Telegram Bot Token & Chat ID)
load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")
TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", "")
# Turkey timezone (UTC+3)
TURKEY_TZ = timezone(timedelta(hours=3))
# Configure logging with ISO8601 timestamps
logging.basicConfig(
level=getattr(logging, os.getenv("LOG_LEVEL", "INFO").upper()),
format="%(asctime)s %(levelname)s %(message)s",
datefmt="%Y-%m-%dT%H:%M:%SZ",
stream=sys.stdout,
)
logger = logging.getLogger(__name__)
# Configuration from environment
CHECK_INTERVAL_SECONDS = int(os.getenv("CHECK_INTERVAL", "300"))
# Retry configuration
RETRY_DELAYS = [5, 10, 30, 60] # seconds
REQUEST_TIMEOUT = 30
RATE_LIMIT_BACKOFF = 120 # seconds
# Failure tracking
consecutive_failures = 0
SUSTAINED_FAILURE_THRESHOLD = 4
# To prevent spamming, store which (train_number, date) we have already notified about
notified_trains = set()
# Route mapping for the 3 main stations
ROUTE_MAP = {
"ISTANBUL-KONYA": {
"from_id": 48,
"from_name": "İSTANBUL(PENDİK)",
"to_id": 1336,
"to_name": "SELÇUKLU YHT (KONYA)",
},
"ISTANBUL-ANKARA": {
"from_id": 48,
"from_name": "İSTANBUL(PENDİK)",
"to_id": 98,
"to_name": "ANKARA GAR",
},
"ANKARA-ISTANBUL": {
"from_id": 98,
"from_name": "ANKARA GAR",
"to_id": 48,
"to_name": "İSTANBUL(PENDİK)",
},
"ANKARA-KONYA": {
"from_id": 98,
"from_name": "ANKARA GAR",
"to_id": 1336,
"to_name": "SELÇUKLU YHT (KONYA)",
},
"KONYA-ISTANBUL": {
"from_id": 1336,
"from_name": "SELÇUKLU YHT (KONYA)",
"to_id": 48,
"to_name": "İSTANBUL(PENDİK)",
},
"KONYA-ANKARA": {
"from_id": 1336,
"from_name": "SELÇUKLU YHT (KONYA)",
"to_id": 98,
"to_name": "ANKARA GAR",
},
}
SEAT_CLASS_MAP = {
"EKONOMI": {"id": 2, "name": "EKONOMİ"},
"BUSINESS": {"id": 1, "name": "BUSİNESS"},
"YATAKLI": {"id": 3, "name": "YATAKLI"},
"LOCA": {"id": 11, "name": "LOCA"},
"DISABLED": {"id": 12, "name": "TEKERLEKLİ SANDALYE"},
}
SEAT_CLASS_ANY = ["EKONOMI", "BUSINESS", "YATAKLI", "LOCA"]
SEAT_CLASS_ALL = ["EKONOMI", "BUSINESS", "YATAKLI", "LOCA", "DISABLED"]
def parse_check_dates():
"""Parse CHECK_DATES env var, validate format and not in past."""
dates_str = os.getenv("CHECK_DATES", "")
if not dates_str:
logger.error("CHECK_DATES environment variable is empty")
send_telegram_message(
"🚨 TCDD Bot: CHECK_DATES environment variable is empty. Bot cannot start."
)
sys.exit(1)
valid_dates = []
invalid_dates = []
now_turkey = datetime.now(TURKEY_TZ)
today_start = now_turkey.replace(hour=0, minute=0, second=0, microsecond=0)
for date_str in dates_str.split(","):
date_str = date_str.strip()
if not date_str:
continue
try:
# Parse DD-MM-YYYY format
parsed = datetime.strptime(date_str, "%d-%m-%Y")
# Add timezone info for comparison
parsed_with_tz = parsed.replace(tzinfo=TURKEY_TZ)
# Check not in past
if parsed_with_tz < today_start:
invalid_dates.append(f"{date_str} (past date)")
else:
# Fixed hour at 21:00
valid_dates.append(f"{date_str} 21:00:00")
except ValueError:
invalid_dates.append(f"{date_str} (invalid format)")
if invalid_dates:
send_telegram_message(
f"⚠️ TCDD Bot: Invalid dates in config: {', '.join(invalid_dates)}"
)
logger.warning(f"Invalid dates skipped: {invalid_dates}")
if not valid_dates:
logger.error("No valid dates to monitor")
send_telegram_message(
"🚨 TCDD Bot: No valid dates to monitor. Bot cannot start."
)
sys.exit(1)
logger.info(f"Monitoring {len(valid_dates)} date(s): {valid_dates}")
return valid_dates
def parse_routes():
"""Parse ROUTES env var, validate each route exists in ROUTE_MAP."""
routes_str = os.getenv("ROUTES", "")
if not routes_str:
logger.error("ROUTES environment variable is empty or not set")
send_telegram_message(
"🚨 TCDD Bot: ROUTES environment variable is empty or not set. Bot cannot start."
)
sys.exit(1)
valid_routes = []
invalid_routes = []
for route in routes_str.split(","):
route = route.strip().upper()
if not route:
continue
if route in ROUTE_MAP:
valid_routes.append(route)
else:
invalid_routes.append(route)
if invalid_routes:
error_msg = f"Invalid route(s): {', '.join(invalid_routes)}"
logger.error(error_msg)
send_telegram_message(f"🚨 TCDD Bot: {error_msg}")
sys.exit(1)
if not valid_routes:
logger.error("No valid routes to monitor")
send_telegram_message(
"🚨 TCDD Bot: No valid routes to monitor. Bot cannot start."
)
sys.exit(1)
logger.info(f"Monitoring {len(valid_routes)} route(s): {valid_routes}")
return valid_routes
def parse_seat_classes():
classes_str = os.getenv("SEAT_CLASSES", "")
if not classes_str:
logger.info("SEAT_CLASSES not set, defaulting to EKONOMI")
return ["EKONOMI"]
classes_str = classes_str.strip().upper()
if classes_str == "ANY":
logger.info(f"Monitoring classes: {', '.join(SEAT_CLASS_ANY)}")
return SEAT_CLASS_ANY.copy()
elif classes_str == "ALL":
logger.info(f"Monitoring classes: {', '.join(SEAT_CLASS_ALL)}")
return SEAT_CLASS_ALL.copy()
valid_classes = []
invalid_classes = []
for class_code in classes_str.split(","):
class_code = class_code.strip()
if not class_code:
continue
if class_code in SEAT_CLASS_MAP:
valid_classes.append(class_code)
else:
invalid_classes.append(class_code)
if invalid_classes:
logger.warning(f"Invalid seat class(es): {', '.join(invalid_classes)}")
if not valid_classes:
logger.warning("No valid seat classes, defaulting to EKONOMI")
return ["EKONOMI"]
logger.info(f"Monitoring classes: {', '.join(valid_classes)}")
return valid_classes
def send_telegram_message(message):
"""Send a message via Telegram bot."""
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
logger.warning(
f"Skipping Telegram notification (Token or Chat ID missing). Message:\n{message}"
)
return
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
payload = {"chat_id": TELEGRAM_CHAT_ID, "text": message}
try:
response = requests.post(url, json=payload, timeout=10)
response.raise_for_status()
logger.info("Telegram notification sent successfully")
except Exception as e:
logger.error(f"Failed to send Telegram notification: {e}")
def check_with_retry(departure_date, route):
"""Check train availability with retry logic and exponential backoff."""
global consecutive_failures
route_info = ROUTE_MAP[route]
url = "https://web-api-prod-ytp.tcddtasimacilik.gov.tr/tms/train/train-availability?environment=dev&userId=1"
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:148.0) Gecko/20100101 Firefox/148.0",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "tr",
"User-Authorization": os.getenv("USER_AUTHORIZATION", ""),
"Authorization": os.getenv("AUTHORIZATION", ""),
"unit-id": "3895",
"Content-Type": "application/json",
"Origin": "https://ebilet.tcddtasimacilik.gov.tr",
"Connection": "keep-alive",
}
payload = {
"searchRoutes": [
{
"departureStationId": route_info["from_id"],
"departureStationName": route_info["from_name"],
"arrivalStationId": route_info["to_id"],
"arrivalStationName": route_info["to_name"],
"departureDate": departure_date,
}
],
"passengerTypeCounts": [{"id": 0, "count": 1}],
"searchReservation": False,
"searchType": "DOMESTIC",
"blTrainTypes": ["TURISTIK_TREN"],
}
for attempt, delay in enumerate(RETRY_DELAYS):
try:
response = requests.post(
url, headers=headers, json=payload, timeout=REQUEST_TIMEOUT
)
# Handle 429 rate limit with longer backoff
if response.status_code == 429:
logger.warning(
f"Rate limited (429), waiting {RATE_LIMIT_BACKOFF}s before retry"
)
time.sleep(RATE_LIMIT_BACKOFF)
continue
response.raise_for_status()
data = response.json()
# Success - reset failure counter
was_in_sustained_failure = (
consecutive_failures >= SUSTAINED_FAILURE_THRESHOLD
)
consecutive_failures = 0
if was_in_sustained_failure:
logger.info("API connection restored after sustained failure")
send_telegram_message("✅ TCDD Bot: API connection restored")
logger.info(f"Success! Retrieved API data for {route} on {departure_date}")
return data
except requests.Timeout:
logger.warning(
f"Request timeout (attempt {attempt + 1}/{len(RETRY_DELAYS)}) for {route} on {departure_date}"
)
except requests.ConnectionError as e:
logger.warning(
f"Connection error (attempt {attempt + 1}/{len(RETRY_DELAYS)}): {e}"
)
except requests.HTTPError as e:
status_code = e.response.status_code if e.response else "unknown"
logger.error(f"HTTP error: {e} - Status Code: {status_code}")
except json.JSONDecodeError as e:
logger.error(f"JSON decode error: {e}")
except Exception as e:
logger.error(f"Unexpected error: {e}")
# Wait before next retry (except on last attempt)
if attempt < len(RETRY_DELAYS) - 1:
logger.info(f"Retrying in {delay}s...")
time.sleep(delay)
# All retries exhausted for this check
consecutive_failures += 1
logger.error(
f"API check failed for {route} on {departure_date}. Consecutive failures: {consecutive_failures}"
)
# Send sustained failure alert only once when threshold is reached
if consecutive_failures == SUSTAINED_FAILURE_THRESHOLD:
send_telegram_message(
"🚨 TCDD Bot: API connection failed after multiple retries. Sustained failure detected."
)
return None
def process_train_data(data, departure_date, route, seat_classes):
train_legs = data.get("trainLegs", [])
if not train_legs:
logger.info("No train legs found")
return
for leg in train_legs:
for availability in leg.get("trainAvailabilities", []):
for train in availability.get("trains", []):
train_number = train.get("number", "Unknown")
exact_departure_time = "Unknown Time"
segments = train.get("segments", [])
if segments:
ts = segments[0].get("departureTime")
if ts:
exact_departure_time = datetime.fromtimestamp(
ts / 1000, tz=TURKEY_TZ
).strftime("%H:%M")
available_by_class = {}
for car in train.get("cars", []):
for avail in car.get("availabilities", []):
cabin_class = avail.get("cabinClass")
if cabin_class:
class_id = cabin_class.get("id")
available_seats = avail.get("availability", 0)
for class_code in seat_classes:
if SEAT_CLASS_MAP[class_code]["id"] == class_id:
if class_code not in available_by_class:
available_by_class[class_code] = 0
available_by_class[class_code] += available_seats
base_date = departure_date.split(" ")[0]
if available_by_class:
total_seats = sum(available_by_class.values())
if total_seats > 0:
class_details = ", ".join(
[
f"{count} {SEAT_CLASS_MAP[code]['name']}"
for code, count in available_by_class.items()
]
)
msg = f"Train {train_number} ({exact_departure_time}) has {total_seats} seats AVAILABLE ({class_details}) on {base_date}!"
logger.info(f"AVAILABLE: {msg}")
# Single notification key per train+date (not per class)
notify_key = f"{route}_{train_number}_{base_date}"
if notify_key not in notified_trains:
send_telegram_message(
f"🚂 TCDD Bot Alert!\n[{route.replace('-', '→')}] {msg}"
)
notified_trains.add(notify_key)
else:
logger.info(
f"Train {train_number} ({exact_departure_time}) has 0 seats available on {base_date}"
)
else:
logger.info(
f"Train {train_number} ({exact_departure_time}) has no monitored classes on {base_date}"
)
def check_train_availability(departure_date, route, seat_classes):
logger.info(f"Checking route: {route}")
data = check_with_retry(departure_date, route)
if data:
process_train_data(data, departure_date, route, seat_classes)
if __name__ == "__main__":
logger.info("Starting TCDD Ticket Bot...")
CHECK_ROUTES = parse_routes()
CHECK_DATES = parse_check_dates()
CHECK_SEAT_CLASSES = parse_seat_classes()
logger.info(f"Check interval: {CHECK_INTERVAL_SECONDS} seconds")
while True:
for date in CHECK_DATES:
for route in CHECK_ROUTES:
check_train_availability(date, route, CHECK_SEAT_CLASSES)
logger.info(
f"Waiting {CHECK_INTERVAL_SECONDS} seconds before checking again..."
)
time.sleep(CHECK_INTERVAL_SECONDS)