-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
263 lines (200 loc) · 6.26 KB
/
index.ts
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
import App from "./App";
import * as fs from "fs";
import { execSync } from 'child_process';
import * as inquirer from "@inquirer/prompts";
import { list } from "regedit";
const regedit = require('regedit').promisified
const config = {
TW_USERNAME: process.env.TW_USERNAME,
TW_PASSWORD: process.env.TW_PASSWORD,
TW_SEARCH: process.env.TW_SEARCH,
CHROME_PATH: process.env.CHROME_PATH,
};
async function searchChrome() {
try {
const registry = "HKCR\\ChromeHTML\\shell\\open\\command"
const chromeBin = (await regedit.list(registry))[registry]?.values?.['']?.value?.split("\"")[1]
if (chromeBin) {
return chromeBin
}
} catch {
}
const possiblePaths = [
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
];
for (const path of possiblePaths) {
try {
fs.statSync(path)
return path;
} catch {
}
}
return null; // Chrome not found
}
const login = async (app: App) => {
await app.page.goto("https://twitter.com/i/flow/login");
await app.type(
"input[autocomplete=username]",
config.TW_USERNAME.toString() ?? "LlenaElEnv"
);
await app.delay(1);
const nextButton = await app.findByText("span", ["Next", "Siguiente"]);
await app.cursor.click(nextButton.element);
await app.delay(1.5);
await app.type(
"input[autocomplete=current-password]",
config.TW_PASSWORD?.toString() ?? "LlenaElEnv"
);
await app.delay(1);
await app.page.click('button[aria-label="Mostrar contraseña"]');
await app.delay(1);
const loginButton = await app.findByText("span", [
"Log in",
"Iniciar sesión",
]);
await app.cursor.click(loginButton.element);
await app.page.waitForSelector('a[href="/explore"]');
};
const search = async (app: App) => {
await app.cursor.click('a[href="/explore"]');
await app.delay(1);
await app.type('input[aria-label="Search query"]', app.config.TW_SEARCH);
await app.delay(0.5);
await app.page.keyboard.press("Enter");
console.log("Esperando por resultados...");
await app.page.waitForSelector("[data-testid=tweetText]");
await app.delay(2);
let tweets: { text: string; tag: string; username: string; time: string, comment: number, like: number, view: number, retweet: number }[] =
[];
while (true) {
console.log("Guardando tweets...");
const elements = await app.page.$$("[data-testid=tweet]");
if (elements.length === 0) {
throw new Error("No se encontraron tweets");
}
try {
const users = await Promise.all(
elements.map((e) =>
e.evaluate(
(t) => t.querySelector("[data-testid=User-Name]").textContent
)
)
);
const texts = await Promise.all(
elements.map((e) =>
e.evaluate(
(t) => t.querySelector("[data-testid=tweetText]").textContent
)
)
);
const comments = await Promise.all(
elements.map((e) =>
e.evaluate(
(t) => t.querySelector("[data-testid=reply]").textContent ?? "0"
)
)
)
const retweets = await Promise.all(
elements.map((e) =>
e.evaluate(
(t) => t.querySelector("[data-testid=retweet]").textContent ?? "0"
)
)
)
const likes = await Promise.all(
elements.map((e) =>
e.evaluate(
(t) => t.querySelector("[data-testid=like]").textContent ?? "0"
)
)
)
const views = await Promise.all(
elements.map((e) =>
e.evaluate(
(t) => t.querySelector("a[href*=analytics]").textContent ?? "0"
)
)
)
users.forEach((user, i) => {
const text = texts[i];
const comment = +getDefaultValue(comments[i], "0")
const retweet = +getDefaultValue(retweets[i], "0")
const like = +getDefaultValue(likes[i], "0")
const view = +getDefaultValue(views[i], "0")
if (tweets.some((t) => t.text === text)) {
return;
}
const [username, rest] = user.split("@");
const [tag, time] = rest.split("·");
tweets.push({ username, tag, time, text, comment, retweet, like, view });
});
await fs.promises.writeFile(
`tweets-${config.TW_SEARCH.toLowerCase()}.json`,
JSON.stringify(tweets)
);
} catch (error) {
console.log(`Error guardando tweets: ${error}`);
} finally {
const lastTweet = elements[elements.length - 1];
await lastTweet.scrollIntoView();
await app.delay(5);
}
}
};
(async () => {
const configFileName = "./twitter-config.json";
const configExists = await fs.promises
.access(configFileName)
.then(() => true)
.catch(() => false);
if (configExists) {
const configFile = JSON.parse(
(await fs.promises.readFile(configFileName)).toString()
);
config.CHROME_PATH = configFile.CHROME_PATH;
config.TW_USERNAME = configFile.TW_USERNAME;
config.TW_PASSWORD = configFile.TW_PASSWORD;
config.TW_SEARCH = configFile.TW_SEARCH;
}
const user = await inquirer.input({
message: "Introduce el usuario de Twitter",
default: config.TW_USERNAME,
});
const password = await inquirer.input({
message: "Introduce la contraseña de Twitter",
default: config.TW_PASSWORD,
});
const twSearch = await inquirer.input({
message: "Introduce el texto a buscar",
default: config.TW_SEARCH,
});
const chrome = config.CHROME_PATH || await searchChrome()
const chromePath = await inquirer.input({
message: "Introduce la ruta de chrome",
default: chrome ?? "",
});
try {
fs.statSync(chromePath)
} catch {
throw Error("La ruta de chrome es incorrecta")
}
config.CHROME_PATH = chromePath;
config.TW_USERNAME = user;
config.TW_PASSWORD = password;
config.TW_SEARCH = twSearch;
await fs.writeFileSync(configFileName, JSON.stringify(config));
const app = new App(config);
await app.init();
console.log("Iniciando sesion...");
await login(app);
console.log("Se ha iniciado sesion correctamente");
console.log("Buscando tweets...");
await search(app);
})();
function getDefaultValue(value: any, defaultValue: any) {
if(!value) {
return defaultValue
}
return value
}