-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCarros 4.gs
210 lines (184 loc) · 6.46 KB
/
Carros 4.gs
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
var telegram_id = "YourTelegramID";
var debug = false;
var date = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd-MM-yyyy");
var fileName = "caetano_car_data.csv";
function main() {
var url = "https://api.gsci.pt/ds/search/v2?numberElements=120&page=1&showReservation=1&withUrl=false&sort=updateTime&orderBy=desc";
var headers = {
"companyid": "24",
"Content-Type": "application/json" // Set the Content-Type header
};
var payload = {
"filters": {'priceInf': [0], 'priceSup': [15000]},
"needle": ""
};
try {
// Fetch JSON content from the API
var response = UrlFetchApp.fetch(url, {
"method": "post",
"headers": headers,
"payload": JSON.stringify(payload), // Convert payload to JSON string
"muteHttpExceptions": true
});
// Log the entire response for debugging
var responseData = JSON.parse(response.getContentText());
// Check for the expected structure
if (responseData.data && responseData.data.searchResult) {
var jsonData = responseData.data.searchResult;
processCarData(jsonData); // Proceed with processing
} else {
Logger.log("Unexpected response structure: " + JSON.stringify(responseData));
}
} catch (e) {
Logger.log("Error fetching data: " + e.toString());
}
}
// Function to process car data
function processCarData(jsonData) {
// Initialize array to store car details
var cars = [];
// Read existing car URLs and prices from Google Drive
var sentCarData = readSentCarData();
// Parse the JSON content to extract car details
jsonData.forEach(function(carData) {
var car = {};
// Extract car details from the response
car.title = carData.brand + " " + carData.model + " " + carData.version;
car.url = 'https://caetanoretail.pt/veiculo/'+carData.vin; // Example URL
car.fuel = carData.fuel;
car.year = carData.year;
car.mileage = carData.kilometers + " km";
car.price = carData.pricePvp;
// Filter cars by price to be under 15000€
if (car.price > 1000 && car.price <= 15000) {
if (!sentCarData[car.url] || sentCarData[car.url] != car.price) {
cars.push(car);
}
}
});
// Sort cars by price from lowest to highest
cars.sort(function(a, b) {
return a.price - b.price;
});
// Prepare car details for the message
var carsMessage = "";
var newCarData = {};
cars.forEach(function(car) {
var oldPrice = sentCarData[car.url] ? sentCarData[car.url] : null;
var priceChange = oldPrice === null ? "🆕" : (car.price > oldPrice ? "🔺" : "🔻");
if (priceChange === "🆕") {
carsMessage += priceChange + " " + car.title + " " + car.fuel + " - " + car.price + "€ - " + car.mileage + " - " + car.year + " - " + car.url + "\n\n";
} else {
carsMessage += car.title + " " + car.fuel + " - " + car.price + "€ " + priceChange + " - " + car.mileage + " - " + car.year + " - " + car.url + "\n\n";
}
newCarData[car.url] = car.price;
});
// Send car details via Telegram if any found
if (carsMessage) {
var parts = splitMessage(carsMessage, 4096 - date.length - 2); // Adjusting the limit to accommodate the date and newline
for (var j = 0; j < parts.length; j++) {
sendTelegramMessage(parts[j]);
}
// Update the CSV file with new URLs and prices
appendCarDataToFile(newCarData);
} else {
Logger.log("No cars found with the specified criteria.");
}
}
// Split the message into parts within the character limit
function splitMessage(message, limit) {
var parts = [];
while (message.length > limit) {
var part = message.substring(0, limit);
var lastNewlineIndex = part.lastIndexOf('\n');
if (lastNewlineIndex > -1) {
part = message.substring(0, lastNewlineIndex + 1);
}
parts.push(part);
message = message.substring(part.length);
}
parts.push(message);
return parts;
}
// Send message via Telegram function
function sendTelegramMessage(message) {
var params = {
"method": "post",
"payload": {
"chat_id": telegram_id,
"text": date + "\n\n" + message
}
};
var response = UrlFetchApp.fetch("https://api.telegram.org/YourBotToken/sendMessage", params);
if (response.getResponseCode() == 200) {
Logger.log("Message sent successfully");
} else {
if (debug) {
Logger.log(response.getContentText());
} else {
Logger.log("Failed to send message");
}
}
}
// Read URLs and prices from the Google Drive CSV file
function readSentCarData() {
var file;
var carData = {};
try {
var files = DriveApp.getFilesByName(fileName);
if (files.hasNext()) {
file = files.next();
var content = file.getBlob().getDataAsString();
var lines = content.split("\n").filter(Boolean);
lines.forEach(function(line) {
var parts = line.split(";");
if (parts.length == 2) {
var url = parts[0].trim();
var price = parseFloat(parts[1].trim());
carData[url] = price;
}
});
}
} catch (e) {
Logger.log("Error reading file: " + e.toString());
}
return carData;
}
// Append new URLs and prices to the Google Drive CSV file
function appendCarDataToFile(newCarData) {
var file;
var newContent = "";
try {
var files = DriveApp.getFilesByName(fileName);
if (files.hasNext()) {
file = files.next();
} else {
file = DriveApp.createFile(fileName, "", MimeType.PLAIN_TEXT);
}
// Read the existing content
var existingContent = file.getBlob().getDataAsString();
var existingData = existingContent.split("\n").filter(Boolean);
var existingCarData = {};
// Populate existing car data
existingData.forEach(function(line) {
var parts = line.split(";");
if (parts.length == 2) {
var url = parts[0].trim();
var price = parseFloat(parts[1].trim());
existingCarData[url] = price;
}
});
// Merge existing data with new data
for (var url in newCarData) {
existingCarData[url] = newCarData[url];
}
// Create new content with merged data
for (var url in existingCarData) {
newContent += url + ";" + existingCarData[url] + "\n";
}
// Update file content
file.setContent(newContent);
} catch (e) {
Logger.log("Error writing to file: " + e.toString());
}
}