-
Notifications
You must be signed in to change notification settings - Fork 0
/
dotita2.js
325 lines (285 loc) · 9.4 KB
/
dotita2.js
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
const fs = require('fs');
const csv = require('csv-parser');
const axios = require('axios');
const i18next = require('i18next');
const Backend = require('i18next-fs-backend');
const { select } = require('@inquirer/prompts');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const config = JSON.parse(fs.readFileSync('config.json', 'utf8'));
const steamId = config.steamId;
if (steamId === 'your_steam_id_here') {
console.error('Please provide your STEAM_ID in the config.json file');
process.exit(1);
}
// SET LANGUAGE
async function askForLanguage() {
const answers = await select({
message: 'Select your language:',
choices: [
{
name: 'English',
value: 'en',
},
{
name: 'Español',
value: 'es',
},
{
name: '中文',
value: 'zh',
},
{
name: 'Русский',
value: 'ru',
},
{
name: 'Português',
value: 'pt',
},
{
name: 'Français',
value: 'fr',
},
{
name: 'Deutsch',
value: 'de',
},
{
name: '한국어',
value: 'ko',
},
{
name: '日本語',
value: 'ja',
},
{
name: 'Türkçe',
value: 'tr',
},
{
name: 'Italiano',
value: 'it',
},
{
name: 'Polski',
value: 'pl',
},
{
name: 'Tiếng Việt',
value: 'vi',
},
{
name: 'ไทย',
value: 'th',
},
{
name: 'Bahasa Indonesia',
value: 'id',
},
{
name: 'العربية',
value: 'ar',
},
],
});
return answers;
}
askForLanguage().then(selectedLanguage => {
i18next.use(Backend).init(
{
lng: selectedLanguage,
fallbackLng: 'en',
backend: {
loadPath: './locales/{{lng}}/translation.json',
},
},
(err, t) => {
if (err) return console.error(err);
// FUNCTION CONVERT STEAM ID TO DOTA 2
function convertToDotaId(steamId) {
const steamIdInt = BigInt(steamId);
const base = BigInt('76561197960265728');
return steamIdInt - base;
}
// CONVERT steamId TO DOTA 2 ACCOUNT
const dotaId = convertToDotaId(steamId);
console.log(`${t('steamId')}: ${steamId}, ${t('dotaAccountId')}: ${dotaId.toString()}`);
// FUNCTION TO DOWNLOAD THE DETAILS OF EACH MATCH
async function downloadMatchDetails(matchId) {
const url = `https://api.opendota.com/api/matches/${matchId}`;
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
if (error.response && error.response.status === 404) {
console.error(`${t('matchDetails404')} ${matchId}`);
} else {
console.error(`${t('matchDetailsError')}: ${error.message}`);
}
return null;
}
}
// FUNCTION TO LOAD PREVIOUS GAMES
function loadPreviousMatches() {
const previousMatches = new Set();
const jsonExists = fs.existsSync('partidas.json');
const csvExists = fs.existsSync('partidas.csv');
if (jsonExists) {
const partidasJSON = JSON.parse(fs.readFileSync('partidas.json', 'utf8'));
partidasJSON.forEach(partida => previousMatches.add(partida.match_id));
}
if (!jsonExists && csvExists) {
fs.createReadStream('partidas.csv')
.pipe(csv())
.on('data', row => {
previousMatches.add(row.match_id);
});
}
return previousMatches;
}
function awaiting(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
//FULL MATCH HISTORY DOWNLOAD FUNCTION
async function downloadAllMatches(dotaId) {
let previousMatches = loadPreviousMatches();
let matchCounter = 0;
let callsPerMinute = 0;
let contadorLlamadas = 0;
let csvWriter;
let encabezados = [];
let inicializadoCSV = false;
setInterval(() => {
callsPerMinute = 0;
}, 65000);
initializeJson();
try {
while (true) {
let url = `https://api.opendota.com/api/players/${dotaId}/matches`;
console.log(`${t('urlConstructed')}: ${url}`);
const response = await axios.get(url);
let partidas = response.data;
console.log(`${t('matchesObtained')}: ${JSON.stringify(partidas.map(p => p.match_id))}`);
partidas = partidas.filter(p => !previousMatches.has(p.match_id));
console.log(`${t('matchesFiltered')}: ${JSON.stringify(partidas.map(p => p.match_id))}`);
if (!partidas || partidas.length === 0) {
console.log(t('noMoreMatches'));
break;
}
for (const partida of partidas) {
if (contadorLlamadas >= 1975) {
console.log(t('apiLimitReached'));
return;
}
await awaiting(2000);
const matchDetails = await downloadMatchDetails(partida.match_id);
if (matchDetails) {
if (callsPerMinute >= 40) {
console.log(t('waitingForRateLimit'));
await awaiting(60000);
callsPerMinute = 0;
}
await awaiting(2000);
const matchWithDetails = {
...partida,
...matchDetails,
};
const dissagregateMatch = dissagregateObject(matchWithDetails);
matchCounter++;
console.log(`${t('matchesDownloaded')} ${matchCounter} - ID: ${partida.match_id}`);
if (!inicializadoCSV) {
encabezados = agregarColumnasFaltantes(Object.keys(dissagregateMatch));
csvWriter = initializeCsvWriter(encabezados);
inicializadoCSV = true;
}
await saveMatchInJSON(matchWithDetails);
await saveMatchInCSV(matchWithDetails, csvWriter);
callsPerMinute++;
contadorLlamadas++;
} else {
console.log(t('detailsNotObtained'));
await awaiting(2500);
}
}
}
console.log(`${t('totalMatchesDownloaded')}: ${matchCounter}`);
} catch (error) {
console.error(`${t('matchDetailsError')}: ${error.message}`);
return console.log(`${t('apiLimitReached')}`);
}
}
// INITIALIZE CSV COLUMNS - UPDATE
function agregarColumnasFaltantes(encabezados) {
for (let i = 0; i < 10; i++) {
const prefijo = `players.${i}.`;
const posAccountId = encabezados.indexOf(`${prefijo}player_slot`) + 1;
const posPersonaname = encabezados.indexOf(`${prefijo}item_neutral`) + 1;
const posName = encabezados.indexOf(`${prefijo}kills`) + 1;
const posLastLogin = encabezados.indexOf(`${prefijo}gold`) + 1;
if (!encabezados.includes(`${prefijo}account_id`)) {
encabezados.splice(posAccountId, 0, `${prefijo}account_id`);
}
if (!encabezados.includes(`${prefijo}personaname`)) {
encabezados.splice(posPersonaname, 0, `${prefijo}personaname`);
}
if (!encabezados.includes(`${prefijo}name`)) {
encabezados.splice(posName, 0, `${prefijo}name`);
}
if (!encabezados.includes(`${prefijo}last_login`)) {
encabezados.splice(posLastLogin, 0, `${prefijo}last_login`);
}
}
return encabezados;
}
//FUNCTION TO HANDLE NESTED ARRAYS
function dissagregateObject(objeto, prefijo = '') {
let output = {};
for (let [clave, valor] of Object.entries(objeto)) {
if (typeof valor === 'object' && valor != null) {
output = {
...output,
...dissagregateObject(valor, `${prefijo}${clave}.`),
};
} else {
output[`${prefijo}${clave}`] = valor;
}
}
return output;
}
// FUNCTION TO INITIALIZE JSON
function initializeJson() {
if (!fs.existsSync('partidas.json')) {
fs.writeFileSync('partidas.json', '[]', 'utf8');
console.log(t('jsonCreated'));
}
}
// FUNCTION TO SAVE MATCH IN JSON
async function saveMatchInJSON(partida) {
let partidas = [];
const data = fs.readFileSync('partidas.json', 'utf8');
partidas = JSON.parse(data);
partidas.push(partida);
fs.writeFileSync('partidas.json', JSON.stringify(partidas, null, 2), 'utf8');
console.log(t('matchSavedToJSON'));
}
// FUNCTION TO INITIALIZE CSV WRITER
function initializeCsvWriter(encabezados) {
return createCsvWriter({
path: 'partidas.csv',
header: encabezados.map(campo => ({
id: campo,
title: campo,
})),
append: fs.existsSync('partidas.csv'),
});
}
// FUNCTION TO SAVE GAME IN CSV
async function saveMatchInCSV(partida, csvWriter) {
let dissagregateMatch = dissagregateObject(partida);
await csvWriter.writeRecords([dissagregateMatch]);
console.log(t('matchSavedToCSV'));
}
downloadAllMatches(dotaId.toString());
}
);
});