-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtweet.js
More file actions
526 lines (446 loc) · 16.8 KB
/
Copy pathtweet.js
File metadata and controls
526 lines (446 loc) · 16.8 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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
require('dotenv').config();
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const { authenticator } = require('otplib');
const { chromium, webkit, devices } = require('playwright');
const STORAGE_PATH = path.join(__dirname, 'twitter-auth.json');
const HOME_SELECTOR = '[data-testid="SideNav_NewTweet_Button"], [data-testid="tweetTextarea_0"]';
const BROWSER = process.env.BROWSER || 'chromium'; // chromium|webkit
const DESKTOP_CHROME = devices['Desktop Chrome'];
const DESKTOP_SAFARI = devices['Desktop Safari'];
const LOGIN_URLS = [
'https://x.com/i/flow/login',
'https://x.com/login',
'https://mobile.x.com/login'
];
async function isLoggedIn(page) {
const selectors = [
HOME_SELECTOR,
'[data-testid="AppTabBar_Profile_Link"]',
'[data-testid="primaryColumn"]'
];
for (const sel of selectors) {
try {
await page.waitForSelector(sel, { timeout: 4000 });
return true;
} catch {
// try next
}
}
return false;
}
async function waitForHomeOr2FA(page) {
const twoFaInput = page.locator('input[name="text"]');
const twoFaPrompt = page.getByText(/verification code|two[- ]?factor/i);
const result = await Promise.race([
page.waitForSelector(HOME_SELECTOR, { timeout: 20000 }).then(() => 'home').catch(() => null),
twoFaInput.waitFor({ state: 'visible', timeout: 20000 }).then(() => '2fa').catch(() => null),
twoFaPrompt.waitFor({ state: 'visible', timeout: 20000 }).then(() => '2fa').catch(() => null)
]);
if (!result) {
throw new Error('Login did not reach home or 2FA prompt in time.');
}
return result;
}
async function clickRetryIfPresent(page) {
const retryBtn = page.getByRole('button', { name: /retry/i });
if (await retryBtn.isVisible().catch(() => false)) {
await retryBtn.click();
await page.waitForTimeout(2000);
}
}
async function waitForLoginInput(page) {
const usernameInput = page.locator('input[autocomplete="username"], input[name="text"]');
await usernameInput.waitFor({ state: 'visible', timeout: 20000 });
return usernameInput;
}
async function goToLogin(page) {
for (const url of LOGIN_URLS) {
try {
await page.goto(url, { waitUntil: 'domcontentloaded' });
await clickRetryIfPresent(page);
await page.waitForSelector(
'input[autocomplete="username"], input[name="text"], input[name="session[username_or_email]"]',
{ state: 'visible', timeout: 30000 }
);
return;
} catch {
// try next URL
}
}
throw new Error('Could not reach login form.');
}
async function navigateToPassword(page, username) {
const passwordSelector = 'input[type="password"], input[name="password"], input[autocomplete="current-password"]';
const identifierSelector = 'input[name="text"], input[autocomplete="username"], input[data-testid="ocfEnterTextTextInput"]';
const errorBanner = page.getByText(/could not log you in|try again later/i);
for (let attempt = 0; attempt < 3; attempt += 1) {
const passwordInput = page.locator(passwordSelector);
// Wait primarily for password; only fall back to identifier if nothing changes.
const result = await Promise.race([
passwordInput.waitFor({ state: 'visible', timeout: 15000 }).then(() => 'password').catch(() => null),
identifierSelector
? page.locator(identifierSelector).waitFor({ state: 'visible', timeout: 15000 }).then(() => 'identifier').catch(() => null)
: Promise.resolve(null)
]);
if (result === 'password') {
return passwordInput;
}
if (await errorBanner.isVisible().catch(() => false)) {
await page.waitForTimeout(2000);
}
const identifierInput = page.locator(identifierSelector);
if (await identifierInput.isVisible().catch(() => false)) {
await identifierInput.fill(username);
const nextBtn =
(await page.getByRole('button', { name: /next|continue|log in/i }).elementHandles())[0] ||
(await page.locator('[data-testid="ocfEnterTextNextButton"]').elementHandles())[0];
if (nextBtn) {
await nextBtn.click();
} else {
await page.keyboard.press('Enter');
}
await clickRetryIfPresent(page);
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {});
await page.waitForTimeout(1500);
}
}
// Final wait once more before failing.
const passwordInput = page.locator(passwordSelector);
await passwordInput.waitFor({ state: 'visible', timeout: 10000 });
return passwordInput;
}
function promptForTwoFactorCode() {
return new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter 2FA code from email/auth app: ', (answer) => {
rl.close();
resolve(answer.trim());
});
});
}
async function handleTwoFactor(page) {
const totpSecret = process.env.TWITTER_2FA_SECRET;
const oneTimeCode = process.env.TWITTER_2FA_CODE;
let code;
if (oneTimeCode) {
code = oneTimeCode;
} else if (totpSecret) {
code = authenticator.generate(totpSecret);
} else {
code = await promptForTwoFactorCode();
}
const codeInput = page.locator('input[name="text"]');
await codeInput.waitFor({ state: 'visible', timeout: 15000 });
await codeInput.fill(code);
const verifyButton = page.getByRole('button', { name: /next|verify|confirm|log in/i });
if (await verifyButton.isVisible().catch(() => false)) {
await verifyButton.click();
} else {
await page.keyboard.press('Enter');
}
await page.waitForSelector(HOME_SELECTOR, { timeout: 20000 });
}
async function saveState(context) {
await context.storageState({ path: STORAGE_PATH });
}
async function openComposer(page) {
const composeButtons = [
'[data-testid="SideNav_NewTweet_Button"]',
'[data-testid="DashButton_Profile_SidebarCompose"]',
'[data-testid="app-bar-new-tweet-button"]',
'[data-testid="AppTabBar_ComposeButton"]',
'[data-testid="toolBarComposeButton"]',
'[data-testid="compositionButton"]'
];
for (const selector of composeButtons) {
const btn = page.locator(selector);
if (await btn.isVisible().catch(() => false)) {
await btn.click();
return;
}
}
// Keyboard shortcut on desktop.
await page.keyboard.press('n').catch(() => {});
}
async function dismissOverlays(page) {
// Try common close buttons and cookie/consent overlays.
const closeSelectors = [
'[data-testid="app-bar-close"]',
'[aria-label="Close"]',
'[data-testid="close"]',
'[data-testid="confirmationSheetConfirm"]',
'[data-testid="confirmationSheetCancel"]',
'[data-testid="dialog"] button',
'[data-testid="sheetDialog"] button',
'[data-testid="twc-cc-mask"] + div [data-testid]'
];
for (const sel of closeSelectors) {
const btn = page.locator(sel);
if (await btn.isVisible().catch(() => false)) {
await btn.click().catch(() => {});
await page.waitForTimeout(300);
}
}
// Remove intercepting mask if still present.
await page.evaluate(() => {
document.querySelectorAll('[data-testid="twc-cc-mask"]').forEach((el) => el.remove());
document.querySelectorAll('#layers > div[role="presentation"], #layers [style*="pointer-events"]').forEach((el) => {
el.remove();
});
const layer = document.getElementById('layers');
if (layer) {
layer.style.pointerEvents = 'none';
}
}).catch(() => {});
}
async function writeTweet(page, composer, tweetText) {
await composer.focus().catch(() => {});
// Select all and insert text to avoid partial input.
const selectAllKey = process.platform === 'darwin' ? 'Meta+A' : 'Control+A';
await page.keyboard.press(selectAllKey).catch(() => {});
await page.keyboard.press('Backspace').catch(() => {});
await page.keyboard.insertText(tweetText);
await page.waitForTimeout(300);
}
async function sendViaShortcut(page) {
const shortcuts = process.platform === 'darwin' ? ['Meta+Enter', 'Control+Enter'] : ['Control+Enter'];
for (const keys of shortcuts) {
await page.keyboard.press(keys).catch(() => {});
await page.waitForTimeout(250);
}
}
async function clickSendButton(page, timeout = 10000) {
const sendSelector =
'[data-testid="tweetButtonInline"]:not([disabled]):not([aria-disabled="true"]), ' +
'[data-testid="tweetButtonInlineComposer"]:not([disabled]):not([aria-disabled="true"]), ' +
'[data-testid="tweetButton"]:not([disabled]):not([aria-disabled="true"])';
const sendButtons = page.locator(sendSelector);
if ((await sendButtons.count()) === 0) {
return;
}
const sendButton = sendButtons.first();
try {
await sendButton.waitFor({ state: 'visible', timeout });
await dismissOverlays(page);
await sendButton.evaluate((btn) => btn.click());
await page.waitForTimeout(300);
} catch {
// If we couldn't click (e.g., already sent or UI changed), ignore.
}
}
function normalizeText(text) {
return (text || '').replace(/\s+/g, ' ').trim();
}
async function waitForPostToComplete(page, composer, tweetText, timeoutMs = 20000) {
const normalizedTweet = normalizeText(tweetText);
const toast = page.locator('[data-testid="toast"], [role="alert"]');
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const composerVisible = await composer.isVisible().catch(() => false);
if (!composerVisible) {
return true;
}
const toastVisible = await toast.isVisible().catch(() => false);
if (toastVisible) {
const toastText = normalizeText(await toast.first().innerText().catch(() => ''));
if (/post (was )?sent|posted|sent/i.test(toastText)) {
return true;
}
}
const currentText = normalizeText(await composer.innerText().catch(() => ''));
if (!currentText) {
return true;
}
if (normalizedTweet && !currentText.includes(normalizedTweet)) {
return true;
}
await page.waitForTimeout(400);
}
return false;
}
async function discardDraftIfPrompted(page) {
const prompt = page.getByText(/save (post|tweet)|save to drafts|save draft/i);
if (!(await prompt.isVisible({ timeout: 800 }).catch(() => false))) {
return false;
}
const dontSave = page.getByRole('button', { name: /don't save|discard/i });
const cancel = page.getByRole('button', { name: /cancel/i });
if (await dontSave.isVisible().catch(() => false)) {
await dontSave.click().catch(() => {});
} else if (await cancel.isVisible().catch(() => false)) {
await cancel.click().catch(() => {});
} else {
await page.keyboard.press('Escape').catch(() => {});
}
await page.waitForTimeout(500);
return true;
}
async function postTweet(page, tweetText) {
await openComposer(page);
const composer = await getComposerTextbox(page);
await composer.waitFor({ state: 'visible' });
await dismissOverlays(page);
await writeTweet(page, composer, tweetText);
await dismissOverlays(page);
// Prefer the explicit Post button; keyboard shortcuts are flaky depending on focus/UI variant.
await clickSendButton(page, 15000);
if (await waitForPostToComplete(page, composer, tweetText)) {
return;
}
await sendViaShortcut(page);
await clickSendButton(page, 15000);
if (await waitForPostToComplete(page, composer, tweetText)) {
return;
}
// If X is trying to save an unsent post, explicitly discard so we don't leave drafts behind.
await discardDraftIfPrompted(page);
throw new Error('Tweet was not posted (composer did not close/clear).');
}
async function getComposerTextbox(page) {
const selectors = [
'div[data-testid="tweetTextarea_0"] div[role="textbox"]',
'div[role="textbox"][data-testid="tweetTextarea_0"]',
'div[data-testid="tweetTextarea_0"]',
'div[data-testid="tweetTextarea_1"]',
'div[role="textbox"][data-testid^="tweetTextarea_"]',
'div[role="textbox"][aria-label*="What"]',
'div[role="textbox"]'
];
for (const selector of selectors) {
const box = page.locator(selector);
if (await box.isVisible({ timeout: 1000 }).catch(() => false)) {
return box;
}
}
throw new Error('Could not find tweet composer textbox.');
}
async function ensureLogin(page, context, username, password) {
if (!username || !password) {
console.error('Set TWITTER_USERNAME and TWITTER_PASSWORD env vars before running the first time.');
process.exit(1);
}
await goToLogin(page);
// Mobile login form (m.twitter.com/login)
const mobileUserInput = page.locator('input[name="session[username_or_email]"]');
const mobilePassInput = page.locator('input[name="session[password]"]');
if (await mobileUserInput.isVisible({ timeout: 1000 }).catch(() => false)) {
await mobileUserInput.fill(username);
await mobilePassInput.fill(password);
const loginBtn =
(await page.getByRole('button', { name: /log in/i }).elementHandles())[0] ||
(await page.locator('div[data-testid="LoginForm_Login_Button"], [data-testid="LoginForm_Login_Button"]').elementHandles())[0];
if (loginBtn) {
await loginBtn.click();
} else {
await page.keyboard.press('Enter');
}
const postLoginState = await waitForHomeOr2FA(page);
if (postLoginState === '2fa') {
await handleTwoFactor(page);
}
await saveState(context);
return;
}
// Step 1: username/phone/email
const usernameInput = await waitForLoginInput(page);
await usernameInput.fill(username);
await page.getByRole('button', { name: 'Next' }).click();
// Handle extra identifier prompts and reach password step.
const passwordInput = await navigateToPassword(page, username);
await passwordInput.waitFor({ state: 'visible' });
await passwordInput.fill(password);
await page.getByRole('button', { name: 'Log in' }).click();
const postLoginState = await waitForHomeOr2FA(page);
if (postLoginState === '2fa') {
await handleTwoFactor(page);
}
// Persist the authenticated state for future runs.
await saveState(context);
}
function getDeviceAndUA() {
if (BROWSER === 'webkit') {
return {
device: DESKTOP_SAFARI,
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15'
};
}
return {
device: DESKTOP_CHROME,
userAgent:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
};
}
async function createContext(headless, storageState) {
const { device, userAgent } = getDeviceAndUA();
const isChromium = BROWSER === 'chromium';
const launchOpts = {
headless,
args: isChromium ? ['--disable-blink-features=AutomationControlled'] : undefined
};
const browser =
BROWSER === 'webkit' ? await webkit.launch(launchOpts) : await chromium.launch(launchOpts);
const context = await browser.newContext({
...device,
viewport: { width: 1280, height: 720 },
userAgent,
locale: 'en-US',
timezoneId: 'UTC',
storageState
});
await context.addInitScript(() => {
Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
});
const page = await context.newPage();
page.setDefaultTimeout(20000);
page.setDefaultNavigationTimeout(45000);
return { browser, context, page };
}
async function loginAndTweet() {
const username = process.env.TWITTER_USERNAME;
const password = process.env.TWITTER_PASSWORD;
const tweetText = process.env.TWEET_TEXT || 'Привет, X!';
const manualLogin = process.env.MANUAL_LOGIN === 'true';
const headless = manualLogin ? false : process.env.HEADLESS === 'true';
const hasCachedState = fs.existsSync(STORAGE_PATH);
const { browser, context, page } = await createContext(headless, hasCachedState ? STORAGE_PATH : undefined);
await page.goto('https://x.com/home', { waitUntil: 'domcontentloaded' });
if (!(await isLoggedIn(page))) {
if (manualLogin) {
console.log('Manual login mode: log in in the opened browser, then press Enter here.');
await goToLogin(page);
await new Promise((resolve) => {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question('Press Enter after you finish logging in...', () => {
rl.close();
resolve();
});
});
} else {
await ensureLogin(page, context, username, password);
}
}
if (!(await isLoggedIn(page))) {
console.error('Not logged in. Complete login manually (set MANUAL_LOGIN=true) or check credentials/2FA.');
process.exit(1);
}
// Refresh state and ensure home.
await saveState(context);
await page.goto('https://x.com/home', { waitUntil: 'domcontentloaded' });
await page.waitForTimeout(2000);
// Open composer and post tweet.
await postTweet(page, tweetText);
// Save state again in case X rotated tokens.
await context.storageState({ path: STORAGE_PATH });
await page.waitForTimeout(3000);
await browser.close();
}
loginAndTweet().catch((err) => {
console.error(err);
process.exit(1);
});