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();

Related Posts

U.S. Army captures a boat in Ve… See more

Developing Maritime Security Incident Highlights Global Tensions and Strategic Surveillance A developing security incident involving the United States Armed Forces has begun drawing attention across defense, intelligence, and international affairs…

Read more

Bill Clinton ’s daughter has broken her silence: ‘My dad used to…

Bill Clinton’s message, recorded after several days in a California hospital, carried the gravity of someone who had come face to face with a serious health scare. Speaking calmly but…

Read more

Senate Confirms New SMDC Commanding General

Maj. Gen. John L. Rafferty Jr. has been confirmed by the U.S. Senate for promotion to lieutenant general and will assume command of the U.S. Army Space and Missile Defense…

Read more

How to Clean Jewelry at Home Using Everyday Household Items

Keeping jewelry clean and bright does not always require expensive products or professional cleaning services. Over time, many types of jewelry—especially silver—can lose their shine as they react with air,…

Read more

Understanding Premature Birth: Challenges, Medical Care, and the Importance of Community Support

Understanding Premature Birth: Challenges, Medical Care, and the Importance of Community Support Posted onMarch 16, 2026 ByadminNo Commentson Understanding Premature Birth: Challenges, Medical Care, and the Importance of Community Support…

Read more

Police Find Girl Missing Since 2022, Family Finally Reunited

The news that a girl missing since 2022 had been found alive spread through the community like wildfire. For years, her name had been whispered in prayers and posted on…

Read more