-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
161 lines (134 loc) · 6.04 KB
/
main.py
File metadata and controls
161 lines (134 loc) · 6.04 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
import os
import json
import time
from datetime import datetime, timedelta
from dotenv import load_dotenv
from twilio.rest import Client
from sheety_data_manager import SheetyDataManager
from flight_club_ui import FlightClubApp
from flight_search import FlightSearch
from flight_search_token import GetDataFlight, GetToken
from email_sender import SendEmail
from flight_price_search import find_cheapest_flight
# Launch the user interface
FlightClubApp()
# Load environment variables
load_dotenv()
# Set up environment and communication data
EMAIL = os.getenv("SENDER_EMAIL")
TO_EMAIL = os.getenv("TO_EMAIL")
FROM_CITY = "LON"
# Set up Twilio for communication
account_sid = os.getenv("TWILIO_ACCOUNT_SID")
auth_token = os.getenv("TWILIO_AUTH_TOKEN")
client = Client(account_sid, auth_token)
# Set up data management and flight search services
data_manager = SheetyDataManager()
sheet_data = data_manager.get_sheet_data()
token = GetToken() # Creating an instance of GetToken
# Get flight data
flight_data = GetDataFlight(token_id=token, data=data_manager)
flight_search = FlightSearch(token=token, data=data_manager)
# -------------------- Handle missing IATA codes --------------------
for row in sheet_data:
if row["iataCode"] == "TESTING":
data_manager.delete_sheet_data()
elif row["iataCode"] == "":
row["iataCode"] = flight_search.search_iata(row["city"])
data_manager.update_sheet_data()
# -------------------- Prepare flight data -------------------------
file_name = "flight_data.json"
if os.path.exists(file_name):
try:
with open(file_name, mode="r") as file:
data = json.load(file)
except json.JSONDecodeError:
data = []
if isinstance(data, list):
for i, flight in enumerate(data):
if isinstance(flight, dict):
flight["iataCode_to_city"] = []
to_city = flight.get("to_city", [])
for city in to_city:
iata_code = flight_search.search_iata(city)
flight["iataCode_to_city"].append(iata_code)
from_city = flight.get("from_city", "")
iata_code_from_city = flight_search.search_iata(from_city)
flight["iataCode_from_city"] = iata_code_from_city
else:
print(f"Error: Invalid data at index {i}")
with open(file_name, mode="w") as file:
json.dump(data, file, indent=4)
print("Flight data updated.")
else:
print("Flight data file not found.")
# -------------------- Find the cheapest flights --------------------
all_messages = []
today = datetime.now() + timedelta(days=3)
six_months_later = today + timedelta(days=3 * 30)
tomorrow = today.strftime("%Y-%m-%d")
after_six_month = six_months_later.strftime("%Y-%m-%d")
with open(file_name, mode="r") as file:
json_data = json.load(file)
if isinstance(json_data, list):
for data in json_data:
if "iataCode_to_city" in data:
for to_city in data["iataCode_to_city"]:
print(f"Getting flights for {data['name']} from {data['from_city']}...")
flight = flight_data.check_flights(
from_city=data["iataCode_from_city"],
to_city=to_city,
tomorrow=tomorrow,
after_six_month=after_six_month
)
row_data = flight
cheapest_flight = find_cheapest_flight(row_data)
if all([cheapest_flight.price != "N/A",
cheapest_flight.out_date != "N/A",
cheapest_flight.return_date != "N/A",
cheapest_flight.from_airport != "N/A",
cheapest_flight.to_airport != "N/A"]):
message_body = (
f"Destination: {data['from_city']} \n"
f"Price: £{cheapest_flight.price}\n"
f"From: {cheapest_flight.from_airport}\n"
f"To: {cheapest_flight.to_airport}\n"
f"Out Date: {cheapest_flight.out_date}\n"
f"Return Date: {cheapest_flight.return_date}\n"
"---------------------------------\n"
)
all_messages.append(message_body)
time.sleep(1)
with open(file_name, mode="w") as file:
for i, data in enumerate(json_data):
if i < len(all_messages):
data["message"] = all_messages[i]
json.dump(json_data, file, indent=4)
print("Messages added and data updated.")
# -------------------- Send messages --------------------
with open(file_name, mode="r") as file:
messages = json.load(file)
for message in messages:
try:
# Send email if email is provided
if message.get("email") and message["email"] != "@gmail.com":
send_email = SendEmail(message=f"Hello {message['name']}\n{message['message']}")
send_email.send_email(email=EMAIL, to_add=message["email"], password=os.getenv("EMAIL_PASSWORD"))
# Send SMS if phone number is provided
if message.get("phone_number") and message["phone_number"] != "+20":
client.messages.create(
body=f"Hello {message['name']}\n{message['message']}",
from_="+13083652686",
to=message["phone_number"],
)
print("SMS sent.")
else:
print(f"{message['name']} does not have a valid phone number.")
# Clear message field after sending
message["message"] = ""
except Exception as e:
print(f"Error while sending message to {message['name']}: {e}")
# Save updated messages with cleared "message" field
with open(file_name, mode="w") as file:
json.dump(messages, file, indent=4)
print("All messages processed.")