-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathreddit-bot.js
More file actions
481 lines (395 loc) · 14.9 KB
/
reddit-bot.js
File metadata and controls
481 lines (395 loc) · 14.9 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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import { BrowserManager } from "./browser-manager.js";
import { CaptchaSolver } from "./captcha-solver.js";
import { EmailService } from "./email-service.js";
import { config } from "./config.js";
export class RedditBot {
constructor(profileId, testMode = false) {
this.profileId = profileId;
this.browserManager = new BrowserManager(profileId, testMode);
this.captchaSolver = new CaptchaSolver();
this.emailService = new EmailService();
}
async registerAccount(username, password) {
let page;
try {
console.log("\n=== Starting Reddit Account Registration ===\n");
page = await this.browserManager.launch();
const email = await this.emailService.generateTempEmail();
console.log(`Username: ${username}`);
console.log(`Email: ${email}`);
console.log(`Password: ${password}\n`);
console.log("Navigating to Reddit registration page...");
try {
await page.goto(config.reddit.signupUrl, {
waitUntil: "domcontentloaded",
timeout: 60000,
});
} catch (navError) {
console.log("Navigation slow, continuing anyway...");
}
console.log("Waiting for page to stabilize...");
await this.browserManager.randomDelay(5000, 7000);
console.log("Step 1: Entering email...");
await this.enterEmail(page, email);
console.log("Step 2: Checking for email verification...");
await this.skipEmailVerification(page, email);
await this.fillRegistrationForm(page, username, password);
await this.skipAboutYou(page);
await this.selectInterests(page);
console.log("Checking for captcha...");
const captchaResult = await this.handleCaptcha(page);
if (captchaResult) {
console.log("Captcha handled successfully");
}
await this.browserManager.randomDelay(3000, 5000);
const success = await this.verifyRegistration(page);
if (success) {
console.log("\n✓ Account registered successfully!\n");
return {
success: true,
username,
email,
password,
profileId: this.profileId,
};
} else {
throw new Error("Registration verification failed");
}
} catch (error) {
console.error("\n✗ Registration failed:", error.message, "\n");
return {
success: false,
error: error.message,
};
} finally {
await this.browserManager.close();
}
}
async enterEmail(page, email) {
try {
console.log("Waiting for email input field...");
await new Promise((resolve) => setTimeout(resolve, 2000));
await page.waitForSelector("faceplate-text-input#register-email", {
timeout: 15000,
visible: true,
});
console.log("Found email web component, accessing shadow DOM input...");
const inputHandle = await page.evaluateHandle(() => {
const webComponent = document.querySelector(
"faceplate-text-input#register-email"
);
if (!webComponent || !webComponent.shadowRoot) return null;
return webComponent.shadowRoot.querySelector('input[type="email"]');
});
if (!inputHandle) {
throw new Error("Could not access email input in shadow DOM");
}
console.log("Clicking email input...");
await inputHandle.click();
await this.browserManager.randomDelay(500, 1000);
console.log(`Typing email: ${email}`);
await inputHandle.type(email, { delay: 100 });
await this.browserManager.randomDelay(1500, 2500);
console.log("Looking for Continue button...");
await new Promise((resolve) => setTimeout(resolve, 1000));
const continueButton = await page.waitForSelector(
"button.continue, button.button-brand",
{
timeout: 10000,
visible: true,
}
);
console.log("Clicking Continue button...");
await continueButton.click();
await this.browserManager.randomDelay(3000, 5000);
} catch (error) {
throw new Error(`Failed to enter email: ${error.message}`);
}
}
async skipEmailVerification(page, email) {
console.log("Looking for email verification page...");
await new Promise((resolve) => setTimeout(resolve, 3000));
const verificationInput = await page.$('faceplate-text-input[name="code"]');
if (!verificationInput) {
console.log("No email verification page detected, continuing...");
return;
}
console.log("Email verification page detected");
const skipButtons = await page.$$("button");
for (const button of skipButtons) {
const text = await page.evaluate((el) => el.textContent.trim(), button);
if (text.toLowerCase() === "skip") {
console.log("Found Skip button, clicking...");
await button.click();
await this.browserManager.randomDelay(2000, 3000);
return;
}
}
console.log("Skip button not found, fetching verification code from email...");
const code = await this.emailService.getVerificationCode(email);
if (!code) {
throw new Error("Could not retrieve verification code from email");
}
console.log("Entering verification code...");
await this.enterVerificationCode(page, code);
}
async enterVerificationCode(page, code) {
try {
const inputHandle = await page.evaluateHandle(() => {
const webComponent = document.querySelector(
'faceplate-text-input[name="code"]'
);
if (!webComponent || !webComponent.shadowRoot) return null;
return webComponent.shadowRoot.querySelector('input[type="text"]');
});
if (!inputHandle) {
throw new Error(
"Could not access verification code input in shadow DOM"
);
}
await inputHandle.click();
await this.browserManager.randomDelay(300, 600);
await inputHandle.type(code, { delay: 100 });
await this.browserManager.randomDelay(1500, 2500);
console.log("Looking for Continue button...");
const allButtons = await page.$$("button");
let clicked = false;
for (const button of allButtons) {
const text = await page.evaluate((el) => el.textContent.trim(), button);
if (text.toLowerCase() === "continue") {
console.log("Clicking Continue...");
await button.click();
await this.browserManager.randomDelay(3000, 5000);
clicked = true;
break;
}
}
if (!clicked) {
throw new Error("Could not find Continue button");
}
} catch (error) {
throw new Error(`Failed to enter verification code: ${error.message}`);
}
}
async fillRegistrationForm(page, username, password) {
try {
console.log(
"Step 3: Filling password (using Reddit's default username)..."
);
await new Promise((resolve) => setTimeout(resolve, 2000));
console.log("Looking for password input...");
await page.waitForSelector("faceplate-text-input#register-password", {
timeout: 10000,
visible: true,
});
const passwordInputHandle = await page.evaluateHandle(() => {
const webComponent = document.querySelector(
"faceplate-text-input#register-password"
);
if (!webComponent || !webComponent.shadowRoot) return null;
return webComponent.shadowRoot.querySelector('input[type="password"]');
});
if (!passwordInputHandle) {
throw new Error("Could not access password input in shadow DOM");
}
await passwordInputHandle.click();
await this.browserManager.randomDelay(500, 1000);
console.log(`Typing password`);
await passwordInputHandle.type(password, { delay: 100 });
await this.browserManager.randomDelay(1500, 2500);
console.log("Looking for Continue button...");
await new Promise((resolve) => setTimeout(resolve, 1000));
const continueButton = await page.waitForSelector(
'button[type="submit"].create, button.create, button[type="submit"]',
{
timeout: 10000,
visible: true,
}
);
console.log("Clicking Continue...");
await continueButton.click();
await this.browserManager.randomDelay(3000, 5000);
} catch (error) {
throw new Error(`Failed to fill registration form: ${error.message}`);
}
}
async skipAboutYou(page) {
console.log('Step 4: Checking for "About you" page...');
await new Promise((resolve) => setTimeout(resolve, 3000));
await page.waitForSelector('button[name="skip"]', { timeout: 10000 });
console.log('"About you" page detected');
// Find all buttons inside any shadow roots under the whole document
// const allButtons = await page.$$('>>> button');
// for (const handle of allButtons) {
// const text = await handle.evaluate(el => el.innerText?.trim() || '');
// console.log(handle, text)
// if (text.toLowerCase() === 'skip') {
// await handle.click();
// break;
// }
// }
// const skipButton = await page.$('button[name="skip"]');
// await skipButton.click();
console.log('Skip button not found, clicking "Man" option...');
const manButton = await page.$('>>> button[name="genderEnum"][value="MALE"]');
if (manButton) {
console.log('Clicking "Man" button...');
await manButton.click();
await this.browserManager.randomDelay(2000, 3000);
return;
}
throw new Error('Could not skip "About you" page - no Skip or Man button found');
}
async selectInterests(page) {
console.log("Step 5: Checking for Interests page...");
await new Promise((resolve) => setTimeout(resolve, 2000));
const pageContent = await page.evaluate(() => document.body.textContent);
if (!pageContent.toLowerCase().includes("interests")) {
throw new Error("Interests page not found");
}
console.log("Found Interests page, selecting random interests...");
const interestButtons = await page.$$('button[role="checkbox"]');
if (interestButtons.length === 0) {
console.log(
"No interest buttons found, trying alternative selector..."
);
const altButtons = await page.$$('button:not([type="submit"])');
if (altButtons.length > 5) {
const numToSelect = Math.floor(Math.random() * 3) + 3;
console.log(`Selecting ${numToSelect} random interests...`);
for (let i = 0; i < numToSelect && i < altButtons.length; i++) {
const randomIndex = Math.floor(Math.random() * altButtons.length);
try {
await altButtons[randomIndex].click();
await this.browserManager.randomDelay(300, 800);
console.log(`Selected interest ${i + 1}`);
} catch (e) {
console.log(`Failed to click interest ${i + 1}`);
}
}
}
} else {
const numToSelect = Math.floor(Math.random() * 3) + 3;
console.log(`Selecting ${numToSelect} interests...`);
for (let i = 0; i < numToSelect && i < interestButtons.length; i++) {
const randomIndex = Math.floor(
Math.random() * interestButtons.length
);
try {
await interestButtons[randomIndex].click();
await this.browserManager.randomDelay(300, 800);
console.log(`Selected interest ${i + 1}`);
} catch (e) {
console.log(`Failed to click interest ${i + 1}`);
}
}
}
await this.browserManager.randomDelay(1000, 2000);
console.log("Looking for Continue button...");
const allButtons = await page.$$("button");
for (const button of allButtons) {
const text = await page.evaluate((el) => el.textContent.trim(), button);
if (text.toLowerCase() === "continue") {
const isDisabled = await page.evaluate((btn) => btn.disabled, button);
if (!isDisabled) {
console.log("Clicking Continue...");
await button.click();
await this.browserManager.randomDelay(2000, 3000);
return;
} else {
console.log("Continue button is disabled, may need to select more interests");
}
break;
}
}
throw new Error("Could not find enabled Continue button on Interests page");
}
async handleCaptcha(page) {
try {
const recaptchaFrame = await page.$('iframe[src*="recaptcha"]');
if (!recaptchaFrame) {
console.log("No captcha detected");
return false;
}
console.log("Captcha detected, extracting sitekey...");
const siteKey = await page.evaluate(() => {
const iframe = document.querySelector('iframe[src*="recaptcha"]');
if (iframe) {
const src = iframe.getAttribute("src");
const match = src.match(/k=([^&]+)/);
return match ? match[1] : null;
}
return null;
});
if (!siteKey) {
throw new Error("Could not extract reCAPTCHA site key");
}
console.log(`Site key: ${siteKey}`);
const captchaSolution = await this.captchaSolver.solveCaptcha(
siteKey,
page.url()
);
console.log("Injecting captcha solution...");
await page.evaluate((token) => {
const textarea = document.querySelector(
'textarea[name="g-recaptcha-response"]'
);
if (textarea) {
textarea.value = token;
textarea.style.display = "block";
}
if (typeof window.___grecaptcha_cfg !== "undefined") {
const clients = window.___grecaptcha_cfg.clients;
for (let client in clients) {
if (clients[client].callback) {
clients[client].callback(token);
}
}
}
}, captchaSolution);
await this.browserManager.randomDelay(1000, 2000);
return true;
} catch (error) {
console.error("Captcha handling error:", error.message);
return false;
}
}
async verifyRegistration(page) {
try {
await page
.waitForNavigation({ timeout: 15000, waitUntil: "networkidle2" })
.catch(() => {});
const url = page.url();
console.log(`Current URL: ${url}`);
if (url.includes("reddit.com") && !url.includes("register")) {
return true;
}
const errorElement = await page.$('[class*="error"], [class*="Error"]');
if (errorElement) {
const errorText = await page.evaluate(
(el) => el.textContent,
errorElement
);
console.log(`Error detected: ${errorText}`);
return false;
}
return true;
} catch (error) {
console.log("Verification check inconclusive");
return false;
}
}
generateRandomUsername(prefix = "user") {
const random = Math.random().toString(36).substring(2, 10);
return `${prefix}_${random}`;
}
generateRandomPassword(length = 12) {
const charset =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%";
let password = "";
for (let i = 0; i < length; i++) {
password += charset.charAt(Math.floor(Math.random() * charset.length));
}
return password;
}
}