const puppeteer = require(‘puppeteer’);
const fs = require(‘fs’);
const CONFIG = {
fanpageUrl: ‘https://www.facebook.com/profile.php?id=100077409334032’,
comment: ‘You are always fantastic with your posts, thank you 👍’,
cookiesFile: ‘./fb-cookies.json’
};
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
function convertCookies(cookies) {
if (Array.isArray(cookies) && cookies[0]?.name) {
return cookies.map(cookie => ({
name: cookie.name,
value: cookie.value,
domain: cookie.domain || ‘.facebook.com’,
path: cookie.path || ‘/’,
expires: cookie.expires || cookie.expirationDate || -1,
httpOnly: cookie.httpOnly || false,
secure: cookie.secure !== false,
sameSite: cookie.sameSite === ‘no_restriction’ ? ‘None’ :
cookie.sameSite === ‘unspecified’ ? ‘Lax’ :
cookie.sameSite || ‘Lax’
}));
}
return cookies;
}
async function commentOnLatestPost() {
if (!fs.existsSync(CONFIG.cookiesFile)) {
console.log(‘❌ Cookies not found’);
return;
}
console.log(‘🚀 Start\n’);
const browser = await puppeteer.launch({
headless: false,
args: [‘–no-sandbox’, ‘–start-maximized’]
});
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on(‘request’, (req) => {
const url = req.url();
if (url.includes(‘/gaming/’) || url.includes(‘gaming_tab’)) {
req.abort();
} else {
req.continue();
}
});
await page.setUserAgent(‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36’);
try {
console.log(‘🍪 Loading cookies’);
const rawCookies = JSON.parse(fs.readFileSync(CONFIG.cookiesFile, ‘utf8’));
const cookies = convertCookies(rawCookies);
await page.setCookie(…cookies);
console.log(‘🔍 Login’);
await page.goto(‘https://www.facebook.com/’, { waitUntil: ‘networkidle2’, timeout: 60000 });
await delay(2000);
const isLoggedIn = await page.evaluate(() => !document.body.innerText.includes(‘Log in’));
if (!isLoggedIn) {
console.log(‘❌ Not logged in’);
return;
}
console.log(‘✅ Logged in\n’);
await page.keyboard.press(‘Escape’);
await delay(500);
console.log(‘📄 Opening page’);
await page.goto(CONFIG.fanpageUrl, { waitUntil: ‘networkidle2’, timeout: 60000 });
await delay(5000);
const currentUrl = page.url();
console.log(‘Current URL:’, currentUrl);
if (currentUrl.includes(‘/gaming/’)) {
console.log(‘❌ Redirected to gaming!’);
return;
}
console.log(‘📜 Loading posts’);
await page.evaluate(() => window.scrollBy(0, 400));
await delay(3000);
console.log(‘💬 Looking for Comment button in first post…\n’);
// PLAN I RI: Gjej dhe kliko comment button
const commentClicked = await page.evaluate(() => {
const articles = document.querySelectorAll(‘div[role=”article”]’);
console.log(‘Articles found:’, articles.length);
if (articles.length === 0) return { success: false, reason: ‘no articles’ };
const firstArticle = articles[0];
// Gjej Comment button/link
const allElements = firstArticle.querySelectorAll(‘div[role=”button”], span, a’);
for (let el of allElements) {
const text = (el.textContent || ”).trim();
const ariaLabel = el.getAttribute(‘aria-label’) || ”;
if (text.toLowerCase() === ‘comment’ ||
text.toLowerCase() === ‘koment’ ||
ariaLabel.toLowerCase().includes(‘comment’)) {
console.log(‘Found Comment button, clicking…’);
el.click();
return { success: true, reason: ‘comment button clicked’ };
}
}
return { success: false, reason: ‘no comment button found’ };
});
console.log(‘Comment button result:’, commentClicked);
if (!commentClicked.success) {
console.log(‘⚠️ No comment button, trying direct comment box…’);
} else {
console.log(‘✅ Comment button clicked’);
await delay(2000); // Prit për comment box të shfaqet
}
console.log(‘🔍 Finding comment box…\n’);
const result = await page.evaluate((commentText) => {
const selectors = [
‘div[aria-label=”Write a comment”]’,
‘div[aria-label=”Shkruaj një koment”]’,
‘div[contenteditable=”true”][role=”textbox”]’,
‘div[data-lexical-editor=”true”]’,
‘div[contenteditable=”true”]’
];
let commentBox = null;
for (let sel of selectors) {
const boxes = document.querySelectorAll(sel);
for (let box of boxes) {
if (box.offsetParent !== null) {
commentBox = box;
console.log(‘Found:’, sel);
break;
}
}
if (commentBox) break;
}
if (!commentBox) {
return { success: false, step: ‘no comment box’ };
}
commentBox.click();
commentBox.focus();
commentBox.textContent = ”;
commentBox.textContent = commentText;
commentBox.innerHTML = commentText;
commentBox.dispatchEvent(new Event(‘focus’, { bubbles: true }));
commentBox.dispatchEvent(new Event(‘input’, { bubbles: true }));
commentBox.dispatchEvent(new InputEvent(‘input’, {
bubbles: true,
inputType: ‘insertText’,
data: commentText
}));
return { success: true, step: ‘written’ };
}, CONFIG.comment);
console.log(‘Result:’, result);
if (!result.success) {
console.log(‘❌ Failed:’, result.step);
await page.screenshot({ path: ‘failed.png’, fullPage: true });
return;
}
console.log(‘✅ Text written’);
await delay(2000);
await page.screenshot({ path: ‘before-submit.png’, fullPage: true });
console.log(‘📤 Submitting…’);
await page.keyboard.press(‘Enter’);
await delay(5000);
await page.screenshot({ path: ‘after-submit.png’, fullPage: true });
console.log(‘\n🎉 SUCCESS!\n’);
} catch (error) {
console.error(‘❌ ERROR:’, error.message);
await page.screenshot({ path: ‘error.png’, fullPage: true });
} finally {
console.log(‘Closing in 8 seconds…’);
await delay(8000);
await browser.close();
console.log(‘🏁 Done’);
}
}
commentOnLatestPost();