JS
.
Jahid
.
Eu
.
Org
Facebook
YouTube
More Tools
Facebook Script
Tampermonkey Extensions
// ==UserScript== // @name Facebook All-in-One Feed & Messenger Gemini AI Automation // @namespace https://jahid.eu.org/ // @version 9.7 // @description All-in-one Facebook automation with Strict Outgoing Message Protection, Universal Feed Auto-Like, AI Auto-Comment, and Context-Aware Messenger Responder // @author Jahid Hasan // @homepage https://jahid.eu.org // @match https://www.facebook.com/* // @match https://www.messenger.com/* // @grant GM_xmlhttpRequest // @grant GM_setValue // @grant GM_getValue // @connect generativelanguage.googleapis.com // ==/UserScript== (function() { 'use strict'; let likedCount = 0; let commentedCount = 0; let repliedCount = 0; let isRunning = false; let isLikeEnabled = true; let isCommentEnabled = true; let isMsgResponderEnabled = true; let timeoutId = null; let delayMs = 10000; let lastProcessedMsgId = null; const defaultApiKey = ''; let savedKeysRaw = GM_getValue('fb_gemini_api_keys', defaultApiKey); const defaultFallbackComments = '(y)\n:)\nB-)\nধন্যবাদ!'; let savedCommentsRaw = GM_getValue('fb_ai_custom_fallback', defaultFallbackComments); function getApiKeys() { const raw = GM_getValue('fb_gemini_api_keys', ''); return raw.split('\n').map(k => k.trim()).filter(k => k.length > 0); } function getFallbackComment() { const raw = GM_getValue('fb_ai_custom_fallback', defaultFallbackComments); const lines = raw.split('\n').map(c => c.trim()).filter(c => c.length > 0); if (lines.length > 0) { return lines[Math.floor(Math.random() * lines.length)]; } return '(y)'; } const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); function isElementInViewport(el) { if (!el) return false; const rect = el.getBoundingClientRect(); const windowHeight = window.innerHeight || document.documentElement.clientHeight; return rect.top < windowHeight && rect.bottom > 0 && rect.height > 0; } function showToast(message, duration = 3500, type = 'info') { let toastContainer = document.getElementById('ai-auto-toast-container'); if (!toastContainer) { toastContainer = document.createElement('div'); toastContainer.id = 'ai-auto-toast-container'; toastContainer.style.position = 'fixed'; toastContainer.style.top = '20px'; toastContainer.style.right = '20px'; toastContainer.style.zIndex = '9999999'; toastContainer.style.display = 'flex'; toastContainer.style.flexDirection = 'column'; toastContainer.style.gap = '8px'; toastContainer.style.pointerEvents = 'none'; document.body.appendChild(toastContainer); } const toast = document.createElement('div'); let bgColor = 'rgba(24, 119, 242, 0.95)'; if (type === 'success') bgColor = 'rgba(40, 167, 69, 0.95)'; if (type === 'warn') bgColor = 'rgba(255, 193, 7, 0.95)'; if (type === 'error') bgColor = 'rgba(220, 53, 69, 0.95)'; toast.style.backgroundColor = bgColor; toast.style.color = type === 'warn' ? '#000000' : '#ffffff'; toast.style.padding = '10px 16px'; toast.style.borderRadius = '8px'; toast.style.boxShadow = '0 4px 12px rgba(0,0,0,0.25)'; toast.style.fontFamily = 'Arial, sans-serif'; toast.style.fontSize = '13px'; toast.style.fontWeight = '500'; toast.style.maxWidth = '320px'; toast.style.wordBreak = 'break-word'; toast.style.opacity = '0'; toast.style.transform = 'translateY(-10px)'; toast.style.transition = 'all 0.3s ease'; toast.innerText = message; toastContainer.appendChild(toast); setTimeout(() => { toast.style.opacity = '1'; toast.style.transform = 'translateY(0)'; }, 50); setTimeout(() => { toast.style.opacity = '0'; toast.style.transform = 'translateY(-10px)'; setTimeout(() => { toast.remove(); }, 300); }, duration); } function cleanRepeatedText(text) { if (!text) return getFallbackComment(); text = text.trim(); for (let len = 5; len <= Math.floor(text.length / 2); len++) { const chunk = text.slice(0, len); const parts = text.split(chunk); if (parts.every(p => p === '')) { return chunk.trim(); } } const sentences = text.split(/(?<=[.!?।])\s*/); const uniqueSentences = []; for (const sentence of sentences) { const cleanSentence = sentence.trim(); if (cleanSentence && !uniqueSentences.includes(cleanSentence)) { uniqueSentences.push(cleanSentence); } } return uniqueSentences.join(' '); } function isOutgoingMessage(node) { if (!node) return true; const ariaLabel = node.getAttribute('aria-label') || ''; if (/You:|by You:|\bআপনি:|\bদ্বারা আপনি:/i.test(ariaLabel)) { return true; } const parentFlex = node.closest('div.x15zctf7, div.x13a6bvl'); if (parentFlex && parentFlex.classList.contains('x15zctf7')) { return true; } return false; } function extractConversationHistory(maxMessages = 10) { const allMessageNodes = Array.from(document.querySelectorAll('div[aria-roledescription="message"]')); if (allMessageNodes.length === 0) return null; const visibleMessageNodes = allMessageNodes.filter(node => isElementInViewport(node)); const targetNodes = visibleMessageNodes.length > 0 ? visibleMessageNodes : allMessageNodes.slice(-maxMessages); const historyList = []; let lastMessageId = ''; let validNodes = []; for (const node of targetNodes) { const ariaLabel = node.getAttribute('aria-label') || ''; const msgId = node.getAttribute('data-message-id') || ''; if (/deleted a message|unsent a message|started a|call|mentioned you|created this group/i.test(ariaLabel)) { continue; } let textElem = node.querySelector('div[dir="auto"]'); let text = textElem ? textElem.innerText.trim() : ''; text = text.replace(/Message will disappear in:.*$/gi, '') .replace(/Replied to.*$/gi, '') .trim(); if (!text || /^\d+:\d+$/.test(text)) { continue; } const isMe = isOutgoingMessage(node); let sender = isMe ? 'You' : 'Friend'; if (!isMe && ariaLabel.includes(':')) { const parts = ariaLabel.split(':'); const metaPart = parts[0]; const commaParts = metaPart.split(','); if (commaParts.length > 1) { sender = commaParts[1].trim(); } } historyList.push(`${sender}: ${text}`); lastMessageId = msgId; validNodes.push(node); } if (historyList.length === 0) return null; const recentHistory = historyList.slice(-maxMessages); const lastValidNode = validNodes[validNodes.length - 1]; return { historyText: recentHistory.join('\n'), lastMsgId: lastMessageId, lastMsgNode: lastValidNode }; } function getUnhandledPostCards() { const cards = new Set(); document.querySelectorAll('div[role="article"]:not([data-processed="true"]), div[data-pagelet^="FeedUnit"]:not([data-processed="true"])') .forEach(el => cards.add(el)); document.querySelectorAll('div[data-ad-rendering-role="story_message"]') .forEach(msg => { const card = msg.closest('div[role="article"]') || msg.closest('div[data-pagelet^="FeedUnit"]') || msg.closest('div.x1y1aw1k') || msg.parentElement?.parentElement?.parentElement; if (card && !card.hasAttribute('data-processed')) { cards.add(card); } }); return Array.from(cards); } const overlay = document.createElement('div'); overlay.id = 'auto-extract-comment-overlay'; overlay.style.position = 'fixed'; overlay.style.bottom = '20px'; overlay.style.right = '20px'; overlay.style.zIndex = '999999'; overlay.style.padding = '14px 18px'; overlay.style.backgroundColor = '#1877f2'; overlay.style.color = '#ffffff'; overlay.style.borderRadius = '10px'; overlay.style.boxShadow = '0 4px 16px rgba(0, 0, 0, 0.3)'; overlay.style.fontFamily = 'Arial, sans-serif'; overlay.style.fontSize = '12px'; overlay.style.display = 'flex'; overlay.style.flexDirection = 'column'; overlay.style.gap = '10px'; overlay.style.cursor = 'move'; let isDragging = false; let startX, startY, initialLeft, initialTop; overlay.addEventListener('mousedown', (e) => { if (['BUTTON', 'INPUT', 'TEXTAREA', 'LABEL', 'A'].includes(e.target.tagName)) return; isDragging = true; startX = e.clientX; startY = e.clientY; const rect = overlay.getBoundingClientRect(); initialLeft = rect.left; initialTop = rect.top; overlay.style.bottom = 'auto'; overlay.style.right = 'auto'; overlay.style.left = `${initialLeft}px`; overlay.style.top = `${initialTop}px`; e.preventDefault(); }); document.addEventListener('mousemove', (e) => { if (!isDragging) return; const dx = e.clientX - startX; const dy = e.clientY - startY; overlay.style.left = `${initialLeft + dx}px`; overlay.style.top = `${initialTop + dy}px`; }); document.addEventListener('mouseup', () => { isDragging = false; }); const topRow = document.createElement('div'); topRow.style.display = 'flex'; topRow.style.alignItems = 'center'; topRow.style.justifyContent = 'space-between'; topRow.style.gap = '10px'; const statusText = document.createElement('span'); function updateStatusText() { statusText.innerText = `L: ${likedCount} | C: ${commentedCount} | R: ${repliedCount}`; } updateStatusText(); statusText.style.fontWeight = 'bold'; const headerBtns = document.createElement('div'); headerBtns.style.display = 'flex'; headerBtns.style.gap = '6px'; const apiConfigBtn = document.createElement('button'); apiConfigBtn.innerText = '⚙️ Config'; apiConfigBtn.style.padding = '4px 8px'; apiConfigBtn.style.border = 'none'; apiConfigBtn.style.backgroundColor = 'rgba(255, 255, 255, 0.2)'; apiConfigBtn.style.color = '#ffffff'; apiConfigBtn.style.borderRadius = '4px'; apiConfigBtn.style.cursor = 'pointer'; apiConfigBtn.style.fontSize = '11px'; const startStopButton = document.createElement('button'); startStopButton.innerText = 'Start'; startStopButton.style.padding = '5px 12px'; startStopButton.style.border = 'none'; startStopButton.style.backgroundColor = '#28a745'; startStopButton.style.color = '#ffffff'; startStopButton.style.borderRadius = '5px'; startStopButton.style.cursor = 'pointer'; startStopButton.style.fontWeight = 'bold'; headerBtns.appendChild(apiConfigBtn); headerBtns.appendChild(startStopButton); topRow.appendChild(statusText); topRow.appendChild(headerBtns); const keyConfigSection = document.createElement('div'); keyConfigSection.style.display = 'none'; keyConfigSection.style.flexDirection = 'column'; keyConfigSection.style.gap = '6px'; // Gemini API Header Row with Label & "Get API" Button const keyHeaderRow = document.createElement('div'); keyHeaderRow.style.display = 'flex'; keyHeaderRow.style.justifyContent = 'space-between'; keyHeaderRow.style.alignItems = 'center'; const keyConfigLabel = document.createElement('span'); keyConfigLabel.innerText = 'Gemini API Keys:'; keyConfigLabel.style.fontSize = '11px'; keyConfigLabel.style.color = '#e4e6eb'; const getApiBtn = document.createElement('button'); getApiBtn.innerText = '🔑 Get API'; getApiBtn.style.padding = '2px 6px'; getApiBtn.style.border = 'none'; getApiBtn.style.backgroundColor = '#28a745'; getApiBtn.style.color = '#ffffff'; getApiBtn.style.borderRadius = '4px'; getApiBtn.style.cursor = 'pointer'; getApiBtn.style.fontSize = '10px'; getApiBtn.style.fontWeight = 'bold'; getApiBtn.addEventListener('click', (e) => { e.preventDefault(); window.open('https://aistudio.google.com/api-keys', '_blank'); }); keyHeaderRow.appendChild(keyConfigLabel); keyHeaderRow.appendChild(getApiBtn); const keyTextarea = document.createElement('textarea'); keyTextarea.rows = 3; keyTextarea.value = savedKeysRaw; keyTextarea.placeholder = 'Paste Gemini API Keys here (1 Key per line)'; keyTextarea.style.width = '100%'; keyTextarea.style.borderRadius = '4px'; keyTextarea.style.border = '1px solid #ffffff'; keyTextarea.style.padding = '6px'; keyTextarea.style.fontSize = '11px'; keyTextarea.style.fontFamily = 'monospace'; const customCommentsLabel = document.createElement('span'); customCommentsLabel.innerText = 'Custom Fallback Replies (1 Per Line):'; customCommentsLabel.style.fontSize = '11px'; customCommentsLabel.style.color = '#e4e6eb'; const customCommentsTextarea = document.createElement('textarea'); customCommentsTextarea.rows = 3; customCommentsTextarea.value = savedCommentsRaw; customCommentsTextarea.style.width = '100%'; customCommentsTextarea.style.borderRadius = '4px'; customCommentsTextarea.style.border = '1px solid #ffffff'; customCommentsTextarea.style.padding = '6px'; customCommentsTextarea.style.fontSize = '11px'; customCommentsTextarea.style.fontFamily = 'monospace'; // Developer Info Credit Link const creditLabel = document.createElement('a'); creditLabel.innerText = 'Dev: Jahid Hasan'; creditLabel.href = 'https://jahid.eu.org'; creditLabel.target = '_blank'; creditLabel.style.fontSize = '10px'; creditLabel.style.color = '#e4e6eb'; creditLabel.style.textDecoration = 'underline'; creditLabel.style.textAlign = 'right'; creditLabel.style.marginTop = '2px'; keyConfigSection.appendChild(keyHeaderRow); keyConfigSection.appendChild(keyTextarea); keyConfigSection.appendChild(customCommentsLabel); keyConfigSection.appendChild(customCommentsTextarea); keyConfigSection.appendChild(creditLabel); const toggleRow = document.createElement('div'); toggleRow.style.display = 'flex'; toggleRow.style.alignItems = 'center'; toggleRow.style.justifyContent = 'space-between'; toggleRow.style.gap = '8px'; const likeLabel = document.createElement('label'); likeLabel.style.display = 'flex'; likeLabel.style.alignItems = 'center'; likeLabel.style.gap = '4px'; likeLabel.style.color = '#ffffff'; likeLabel.style.fontWeight = 'bold'; likeLabel.style.cursor = 'pointer'; const likeCheckbox = document.createElement('input'); likeCheckbox.type = 'checkbox'; likeCheckbox.checked = true; likeLabel.appendChild(likeCheckbox); likeLabel.appendChild(document.createTextNode('Like')); const commentLabel = document.createElement('label'); commentLabel.style.display = 'flex'; commentLabel.style.alignItems = 'center'; commentLabel.style.gap = '4px'; commentLabel.style.color = '#ffffff'; commentLabel.style.fontWeight = 'bold'; commentLabel.style.cursor = 'pointer'; const commentCheckbox = document.createElement('input'); commentCheckbox.type = 'checkbox'; commentCheckbox.checked = true; commentLabel.appendChild(commentCheckbox); commentLabel.appendChild(document.createTextNode('Comment')); const msgLabel = document.createElement('label'); msgLabel.style.display = 'flex'; msgLabel.style.alignItems = 'center'; msgLabel.style.gap = '4px'; msgLabel.style.color = '#ffffff'; msgLabel.style.fontWeight = 'bold'; msgLabel.style.cursor = 'pointer'; const msgCheckbox = document.createElement('input'); msgCheckbox.type = 'checkbox'; msgCheckbox.checked = true; msgLabel.appendChild(msgCheckbox); msgLabel.appendChild(document.createTextNode('Reply Msg')); toggleRow.appendChild(likeLabel); toggleRow.appendChild(commentLabel); toggleRow.appendChild(msgLabel); const speedRow = document.createElement('div'); speedRow.style.display = 'flex'; speedRow.style.alignItems = 'center'; speedRow.style.gap = '8px'; const speedLabel = document.createElement('span'); speedLabel.innerText = 'Delay: 10s'; speedLabel.style.fontSize = '12px'; speedLabel.style.minWidth = '55px'; const speedInput = document.createElement('input'); speedInput.type = 'range'; speedInput.min = '3'; speedInput.max = '30'; speedInput.value = '10'; speedInput.step = '1'; speedInput.style.cursor = 'pointer'; speedInput.style.flex = '1'; speedRow.appendChild(speedLabel); speedRow.appendChild(speedInput); overlay.appendChild(topRow); overlay.appendChild(keyConfigSection); overlay.appendChild(toggleRow); overlay.appendChild(speedRow); document.body.appendChild(overlay); showToast('Ready! Click Start to begin.', 3000, 'info'); apiConfigBtn.addEventListener('click', () => { if (keyConfigSection.style.display === 'none') { keyConfigSection.style.display = 'flex'; } else { keyConfigSection.style.display = 'none'; } }); keyTextarea.addEventListener('input', (e) => { GM_setValue('fb_gemini_api_keys', e.target.value); }); customCommentsTextarea.addEventListener('input', (e) => { GM_setValue('fb_ai_custom_fallback', e.target.value); }); likeCheckbox.addEventListener('change', (e) => { isLikeEnabled = e.target.checked; showToast(isLikeEnabled ? '👍 Auto Like Activated' : '⏸️ Auto Like Paused', 2000, 'info'); }); commentCheckbox.addEventListener('change', (e) => { isCommentEnabled = e.target.checked; showToast(isCommentEnabled ? '💬 Auto Comment Activated' : '⏸️ Auto Comment Paused', 2000, 'info'); }); msgCheckbox.addEventListener('change', (e) => { isMsgResponderEnabled = e.target.checked; showToast(isMsgResponderEnabled ? '📩 Auto Reply Activated' : '⏸️ Auto Reply Paused', 2000, 'info'); }); speedInput.addEventListener('input', (e) => { const selectedSec = e.target.value; delayMs = selectedSec * 1000; speedLabel.innerText = `Delay: ${selectedSec}s`; }); function waitForElement(queryFn, maxWaitMs = 6000, intervalMs = 200) { return new Promise((resolve) => { const startTime = Date.now(); const timer = setInterval(() => { const element = queryFn(); if (element) { clearInterval(timer); resolve(element); } else if (Date.now() - startTime >= maxWaitMs) { clearInterval(timer); resolve(null); } }, intervalMs); }); } function generateAiReply(inputText, contextType = 'post') { let prompt = ''; if (contextType === 'chat') { prompt = `You are replying in a Messenger chat as 'You' to a person. Here is the visible chat history: ${inputText} STRICT RESPECT & PRONOUN RULES: 1. Analyze how the person addresses 'You' (e.g. Apni, Apne, Tumi, Tui) AND check if they asked to be called a specific way. 2. If the person addresses 'You' respectfully using "Apni", "Apne", "Valo asen", "Bolen" OR explicitly requested to be called "Apni", you MUST strictly use respectful pronouns ("Apni", "Apnar", "Apne") in your reply. NEVER use "tui", "tor", or "tumi" in this case! 3. Match the exact tone and respect level of the person. Always be well-mannered, polite, and humble. 4. Reply ONLY to the VERY LATEST message from the person. 5. Write ONLY ONE short, natural, polite 1-sentence reply as 'You'. 6. Do NOT use quotes, hashtags, bot-like clichés, or sender names in the output.`; } else { prompt = `Write ONLY ONE single, short, and friendly 1-sentence comment for this social media post. Match the language of the text (Bangla or English). DO NOT repeat sentences or duplicate phrases. Do not use quotes or hashtags. Input text: "${inputText}"`; } let keys = getApiKeys(); if (keys.length === 0) { showToast('⚠️ No Gemini API Keys found! Using fallback.', 3000, 'warn'); return Promise.resolve(getFallbackComment()); } keys = keys.sort(() => Math.random() - 0.5); return new Promise((resolve) => { let attempt = 0; function tryNextKey() { if (attempt >= keys.length) { showToast('⚠️ All Gemini API Keys failed! Using fallback.', 3000, 'warn'); resolve(getFallbackComment()); return; } const currentKey = keys[attempt]; attempt++; showToast(`🤖 Generating AI via Gemini (${attempt}/${keys.length})...`, 2500, 'info'); const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash-lite:generateContent?key=${currentKey}`; GM_xmlhttpRequest({ method: "POST", url: apiUrl, headers: { "Content-Type": "application/json" }, data: JSON.stringify({ contents: [ { role: "user", parts: [ { text: prompt } ] } ] }), onload: function(response) { try { const data = JSON.parse(response.responseText); if (data && data.candidates && data.candidates[0] && data.candidates[0].content && data.candidates[0].content.parts && data.candidates[0].content.parts[0]) { let generatedText = data.candidates[0].content.parts[0].text.trim(); generatedText = cleanRepeatedText(generatedText); resolve(generatedText); return; } } catch (err) { console.error('[Gemini Error] Response Parse Error:', err); } showToast(`⚠️ Gemini Key #${attempt} failed! Trying next...`, 2000, 'warn'); tryNextKey(); }, onerror: function(err) { console.error('[Gemini Error] Network Error:', err); showToast(`⚠️ Gemini Key #${attempt} failed! Trying next...`, 2000, 'warn'); tryNextKey(); } }); } tryNextKey(); }); } async function processNextAutomation() { if (!isRunning) return; const isMessengerPage = window.location.href.includes('messenger.com') || window.location.pathname.includes('/messages/'); if (isMsgResponderEnabled) { const allMessageNodes = Array.from(document.querySelectorAll('div[aria-roledescription="message"]')); if (allMessageNodes.length > 0) { const visibleNodes = allMessageNodes.filter(node => isElementInViewport(node)); const lastMsgNode = visibleNodes.length > 0 ? visibleNodes[visibleNodes.length - 1] : allMessageNodes[allMessageNodes.length - 1]; const isLastMsgSentByMe = isOutgoingMessage(lastMsgNode); if (!isLastMsgSentByMe) { const convData = extractConversationHistory(10); if (convData && convData.historyText) { const msgId = convData.lastMsgId; if (msgId && msgId !== lastProcessedMsgId) { lastProcessedMsgId = msgId; showToast(`📩 New Msg received from Friend!`, 3000, 'info'); const aiReply = await generateAiReply(convData.historyText, 'chat'); showToast(`💬 AI Context Reply: "${aiReply}"`, 4000, 'success'); await sleep(800); if (!isRunning) return; const inputBox = document.querySelector('div[contenteditable="true"][role="textbox"]'); if (inputBox) { inputBox.click(); await sleep(300); inputBox.focus(); await sleep(400); document.execCommand('selectAll', false, null); document.execCommand('insertText', false, aiReply); inputBox.dispatchEvent(new InputEvent('input', { bubbles: true, cancelable: true })); await sleep(1000); if (!isRunning) return; const enterEvent = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: 'Enter', code: 'Enter', keyCode: 13, which: 13 }); inputBox.dispatchEvent(enterEvent); repliedCount++; updateStatusText(); showToast('✅ Humanized Reply sent to chat!', 2500, 'success'); await sleep(2000); scheduleNextRun(); return; } } } } } } if (!isMessengerPage && (isLikeEnabled || isCommentEnabled)) { const unhandledPostCards = getUnhandledPostCards(); if (unhandledPostCards.length > 0) { const postCard = unhandledPostCards[0]; postCard.setAttribute('data-processed', 'true'); postCard.scrollIntoView({ behavior: 'smooth', block: 'center' }); await sleep(1500); if (!isRunning) return; if (isLikeEnabled && isRunning) { const likeBtn = Array.from(postCard.querySelectorAll('div[role="button"]')) .find(b => /^like$/i.test((b.getAttribute('aria-label') || '').trim()) || /^লাইক$/i.test((b.getAttribute('aria-label') || '').trim())) || postCard.querySelector('div[aria-label="Like"], div[aria-label="লাইক"]'); if (likeBtn) { await sleep(400); likeBtn.click(); likedCount++; updateStatusText(); showToast(`👍 Liked Post (Total: ${likedCount})`, 2500, 'success'); await sleep(1000); } } if (isCommentEnabled && isRunning) { const seeMoreBtn = Array.from(postCard.querySelectorAll('div[role="button"], span[role="button"]')) .find(b => /^(see more|আরও দেখুন)$/i.test(b.innerText.trim())); if (seeMoreBtn) { await sleep(400); seeMoreBtn.click(); showToast('📖 Expanding full post text for AI...', 1500, 'info'); await sleep(800); } let messageElem = postCard.querySelector('div[data-ad-rendering-role="story_message"]') || postCard.querySelector('div[data-ad-comet-preview="message"]'); let text = messageElem ? messageElem.innerText.trim() : ''; if (!text) { const titleElem = postCard.querySelector('span[data-ad-rendering-role="title"]'); text = titleElem ? titleElem.innerText.trim() : ''; } if (!text) { const imgElem = postCard.querySelector('img[data-imgperflogname="feedImage"]'); text = imgElem ? (imgElem.getAttribute('alt') || '').trim() : ''; } text = text.replace(/(See less|See more|আরও কম|আরও দেখুন)$/i, '').trim(); if (text) { const previewText = text.length > 35 ? text.substring(0, 35) + '...' : text; showToast(`📌 Post Text: "${previewText}"`, 3000, 'info'); const aiComment = await generateAiReply(text, 'post'); showToast(`💬 AI Comment: "${aiComment}"`, 4000, 'success'); await sleep(1000); if (!isRunning) return; const commentBtn = postCard.querySelector('div[aria-label="Leave a comment"], div[aria-label="Write a comment"], div[data-ad-rendering-role="comment_button"]'); if (commentBtn) { await sleep(400); commentBtn.click(); } await sleep(1500); if (!isRunning) return; const commentBox = await waitForElement(() => { return document.querySelector('div[role="dialog"] div[contenteditable="true"][role="textbox"]') || postCard.querySelector('div[contenteditable="true"][role="textbox"]') || document.querySelector('div[contenteditable="true"][role="textbox"]'); }, 5000); if (commentBox && isRunning) { commentBox.scrollIntoView({ behavior: 'smooth', block: 'center' }); await sleep(400); commentBox.click(); await sleep(300); commentBox.focus(); await sleep(400); document.execCommand('selectAll', false, null); document.execCommand('insertText', false, aiComment); commentBox.dispatchEvent(new InputEvent('input', { bubbles: true, cancelable: true })); await sleep(1200); if (!isRunning) return; const enterEvent = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: 'Enter', code: 'Enter', keyCode: 13, which: 13 }); commentBox.dispatchEvent(enterEvent); await sleep(800); const submitContainer = document.querySelector('#focused-state-composer-submit') || postCard.querySelector('div[aria-label="Post comment"], div[aria-label="Post"], div[aria-label="Comment"]') || document.querySelector('div[aria-label="Post comment"], div[aria-label="Post"]'); if (submitContainer) { const submitBtn = submitContainer.querySelector('div[role="button"]') || submitContainer; if (submitBtn && submitBtn.getAttribute('aria-disabled') !== 'true') { submitBtn.click(); } } commentedCount++; updateStatusText(); showToast('✅ Comment submitted successfully!', 3000, 'success'); await sleep(4000); if (!isRunning) return; const closeButton = await waitForElement(() => { return document.querySelector('div[aria-label="Close"][role="button"]') || document.querySelector('div[aria-label="Close"]'); }, 2500); if (closeButton && isRunning) { closeButton.click(); showToast('✖️ Pop-up closed.', 2000, 'info'); await sleep(3000); } } else if (isRunning) { showToast('⚠️ Comment box not found!', 3000, 'warn'); } } } scheduleNextRun(); return; } else if (!isMessengerPage) { window.scrollBy({ top: 500, behavior: 'smooth' }); showToast('🔍 Searching for new posts...', 2000, 'info'); scheduleNextRun(); return; } } scheduleNextRun(); } function scheduleNextRun() { if (!isRunning) return; const randomJitter = Math.floor(Math.random() * 600) - 300; const finalDelay = Math.max(1500, delayMs + randomJitter); timeoutId = setTimeout(processNextAutomation, finalDelay); } startStopButton.addEventListener('click', () => { if (!isRunning) { isRunning = true; startStopButton.innerText = 'Pause'; startStopButton.style.backgroundColor = '#ffc107'; startStopButton.style.color = '#000000'; showToast('▶️ All-in-One Automation Started!', 2500, 'success'); processNextAutomation(); } else { isRunning = false; if (timeoutId) clearTimeout(timeoutId); startStopButton.innerText = 'Start'; startStopButton.style.backgroundColor = '#28a745'; startStopButton.style.color = '#ffffff'; showToast('⏸️ All-in-One Automation Paused.', 2500, 'warn'); } }); })();
Cut