Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save braunglasrakete/837a136af79b43f1de8af41170849601 to your computer and use it in GitHub Desktop.

Select an option

Save braunglasrakete/837a136af79b43f1de8af41170849601 to your computer and use it in GitHub Desktop.
Instagram Comment Activity Deleter: Automate the deletion of all your Instagram comments from the 'Your Activity' section. Perfect for quick digital clean-up. Also works for story replies. For Likes, see my other project.
/**
* Instagram Comment Auto-Deletion Script
* original by sbolel, updated to work with current page layout as of April 2025
* keep batch size low to reduce risk of Instagram throwing the SOMETHING WENT WRONG error
* it waits a little before selecting comments on reload to not throw it out of loop
* it's still not perfect, it occasionally throws SOMETHING WENT WRONG, but better semi-automated than not working at all
* if you're getting the message that there are no comments to show and you didn't comment on anything,
* go back to Home, and comment on something, then come back
*
* important: UI language must be set to English for the script to work
*
* WARNING: This function directly manipulates the DOM and depends on the current HTML
* structure of Instagram's website to work. If Instagram implements changes to the
* activity page layout, structure, or functionality, this script may break or cause
* unexpected behavior. Use at your own risk and always review code before running it.
*
* How to use:
* 1. Navigate to the Instagram comments page by going to:
* https://www.instagram.com/your_activity/interactions/comments
* 2. Open the developer console in your web browser:
* - Chrome/Firefox: Press Ctrl+Shift+J (Windows/Linux) or Cmd+Option+J (Mac)
* - Safari: Enable the Develop menu in Safari's Advanced preferences, then press Cmd+Option+C
* 3. Copy and paste this entire script into the console and press Enter to run it.
*
*/
;(async function () {
const DELETION_BATCH_SIZE = 12
const DELAY_BETWEEN_ACTIONS_MS = 1500
const DELAY_BETWEEN_CHECKBOX_CLICKS_MS = 300
const DELAY_AFTER_SELECT_CLICK_MS = 8000 // NEW: Delay after clicking "Select"
const DELAY_AFTER_COMMENTS_VISIBLE_MS = 2000 // Wait before starting selection
const MAX_RETRIES = 60
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
const waitForElement = async (selector, timeout = 30000) => {
const startTime = Date.now()
while (Date.now() - startTime < timeout) {
const element = document.querySelector(selector)
if (element) return element
await delay(100)
}
throw new Error(`Element with selector "${selector}" not found within ${timeout}ms`)
}
const clickElement = async (element) => {
if (!element) throw new Error('Element not found')
element.scrollIntoView({ behavior: 'smooth', block: 'center' })
element.click()
}
const waitForSelectButton = async () => {
for (let i = 0; i < MAX_RETRIES; i++) {
const buttonCount = document.querySelectorAll('[role="button"]')?.length
if (buttonCount > 1) return
await delay(1000)
}
throw new Error('Select button not found after maximum retries')
}
const deleteSelectedComments = async () => {
try {
const deleteButton = [...document.querySelectorAll('span')]
.find(el => ['Delete', 'Löschen'].includes(el.textContent.trim()))
if (!deleteButton) throw new Error('Delete button not found')
await clickElement(deleteButton)
await delay(DELAY_BETWEEN_ACTIONS_MS)
const confirmButton = await waitForElement('button[tabindex="0"]')
await clickElement(confirmButton)
} catch (error) {
console.error('Error during comment deletion:', error.message)
}
}
const scrollAndWaitForMoreComments = async (previousCount) => {
window.scrollTo(0, document.body.scrollHeight)
for (let i = 0; i < 10; i++) {
await delay(1000)
const currentCount = document.querySelectorAll('[aria-label="Toggle checkbox"]').length
if (currentCount > previousCount) return true
}
return false
}
const deleteActivity = async () => {
try {
while (true) {
const [, selectButton] = document.querySelectorAll('[role="button"]')
if (!selectButton) throw new Error('Select button not found')
await clickElement(selectButton)
await delay(DELAY_AFTER_SELECT_CLICK_MS) // NEW: Wait for comments to load
let checkboxes = document.querySelectorAll('[aria-label="Toggle checkbox"]')
if (checkboxes.length === 0) {
const gotMore = await scrollAndWaitForMoreComments(0)
if (!gotMore) {
console.log('🚫 No more comments to delete.')
break
}
continue
}
await delay(DELAY_AFTER_COMMENTS_VISIBLE_MS) // Wait before starting selection
for (let i = 0; i < Math.min(DELETION_BATCH_SIZE, checkboxes.length); i++) {
await clickElement(checkboxes[i])
await delay(DELAY_BETWEEN_CHECKBOX_CLICKS_MS)
}
await delay(DELAY_BETWEEN_ACTIONS_MS)
await deleteSelectedComments()
await delay(DELAY_BETWEEN_ACTIONS_MS)
await waitForSelectButton()
await delay(DELAY_BETWEEN_ACTIONS_MS)
}
} catch (error) {
console.error('Error in deleteActivity:', error.message)
}
}
// Start script
try {
await deleteActivity()
console.log('✅ All comments deleted or none left to delete.')
} catch (error) {
console.error('Fatal error:', error.message)
}
})()
@alessandroamella

Copy link
Copy Markdown

Great job! Very useful

@fugitiveghost

Copy link
Copy Markdown

I keep getting the issue of it opening my dms at the bottom of the screen, as well as saying all comments are deleted. my interface is in english as thats a common issue so I'm not sure why I'm getting it now. any help?

@Spiderdoom1313

Copy link
Copy Markdown

same issue as @fugitiveghost

@SmugFest

Copy link
Copy Markdown

works but i have the dm opeing issue

@ctrl-alt-w

ctrl-alt-w commented Aug 29, 2025 •

Copy link
Copy Markdown

this works:
@fugitiveghost, @Spiderdoom1313, @SmugFest I just tested it now:
;(async function () {
const DELETION_BATCH_SIZE = 20
const DELAY_BETWEEN_ACTIONS_MS = 3000
const DELAY_BETWEEN_CHECKBOX_CLICKS_MS = 100
const MAX_RETRIES = 100

const delay = ms => new Promise(res => setTimeout(res, ms))

async function slowScrollDown(totalDurationMs = 6000, steps = 6) {
    const totalHeight = document.body.scrollHeight
    const stepHeight = totalHeight / steps
    const stepDelay = totalDurationMs / steps
    for (let i = 0; i < steps; i++) {
        window.scrollBy(0, stepHeight)
        await delay(stepDelay)
    }
}

async function clickElement(el) {
    if (!el) throw new Error("Element not found")
    el.click()
}

async function getSelectButton() {
    const elems = [...document.querySelectorAll('[role="button"], span, div')]
    return elems.find(el => el.innerText.trim() === "Select") || null
}

async function getDeleteButton() {
    // Try multiple approaches to find the delete button
    
    // Method 1: Try the specific CSS selector you provided
    let deleteBtn = document.querySelector('.wbloks_50 > div:nth-child(1) > div:nth-child(4) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1)')
    if (deleteBtn) {
        console.log("Found delete button using CSS selector")
        return deleteBtn
    }

    // Method 2: Try to find by XPath (converted to querySelector)
    deleteBtn = document.evaluate('/html/body/div[1]/div/div/div[2]/div/div/div[1]/div[1]/div[1]/section/main/div/article/div/div[2]/div/div/div[1]/div/div/div/div/div/div[4]/div/div/div[2]/div/div/div[2]/div/div/div/div/div/div[1]/div/span', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
    if (deleteBtn) {
        console.log("Found delete button using XPath")
        return deleteBtn
    }

    // Method 3: Look for elements containing "Delete" text (original method)
    const elems = [...document.querySelectorAll("span, div, button")]
    deleteBtn = elems.find(el => el.innerText && el.innerText.trim().toLowerCase().includes("delete"))
    if (deleteBtn) {
        console.log("Found delete button using text search")
        return deleteBtn
    }

    // Method 4: Look for clickable elements in the general area
    const clickableElems = [...document.querySelectorAll('[role="button"], button, .wbloks_50 span, .wbloks_50 div[role="button"]')]
    for (const elem of clickableElems) {
        if (elem.innerText && (elem.innerText.toLowerCase().includes('delete') || elem.getAttribute('aria-label')?.toLowerCase().includes('delete'))) {
            console.log("Found delete button using broader search")
            return elem
        }
    }

    console.log("Delete button not found with any method")
    return null
}

async function getConfirmButton() {
    // Try the specific selector you provided
    let confirmBtn = document.querySelector('button._a9--:nth-child(1)')
    if (confirmBtn) {
        console.log("Found confirm button using specific selector")
        return confirmBtn
    }

    // Fallback methods
    confirmBtn = document.querySelector('button[tabindex="0"]')
    if (confirmBtn) {
        console.log("Found confirm button using tabindex")
        return confirmBtn
    }

    // Look for buttons with confirm-related text
    const buttons = [...document.querySelectorAll('button')]
    confirmBtn = buttons.find(btn => {
        const text = btn.innerText?.toLowerCase() || ''
        return text.includes('delete') || text.includes('confirm') || text.includes('yes')
    })
    if (confirmBtn) {
        console.log("Found confirm button using text search")
        return confirmBtn
    }

    console.log("Confirm button not found")
    return null
}

async function handleWrongMessage() {
    const msgs = document.querySelectorAll("div, span, p")
    for (const msg of msgs) {
        if (msg.textContent.toLowerCase().includes("wrong")) {
            const buttons = document.querySelectorAll("button")
            for (const btn of buttons) {
                if (/^(ok)$/i.test(btn.textContent.trim())) {
                    await clickElement(btn)
                    await delay(500)
                    window.scrollTo(0, 0)
                    break
                }
            }
            break
        }
    }
}

async function waitForSelectButton() {
    for (let i = 0; i < MAX_RETRIES; i++) {
        const selectBtn = await getSelectButton()
        if (selectBtn) return selectBtn
        await delay(1000)
    }
    throw new Error("Select button not found after retries")
}

async function deleteSelectedComments() {
    try {
        console.log("Looking for delete button...")
        const deleteButton = await getDeleteButton()
        if (!deleteButton) throw new Error("Delete button not found")
        
        console.log("Clicking delete button...")
        await clickElement(deleteButton)
        await delay(DELAY_BETWEEN_ACTIONS_MS)

        console.log("Looking for confirmation button...")
        const confirmButton = await getConfirmButton()
        if (confirmButton) {
            console.log("Clicking confirm button...")
            await clickElement(confirmButton)
        } else {
            console.log("Warning: Confirmation button not found")
        }

        window.scrollTo(0, 0)
        await handleWrongMessage()
    } catch (err) {
        console.error("Error during comment deletion:", err.message)
    }
}

async function deleteActivity() {
    while (true) {
        const selectButton = await getSelectButton()
        if (!selectButton) throw new Error("Select button not found")

        await clickElement(selectButton)
        await delay(DELAY_BETWEEN_ACTIONS_MS)

        let checkboxes = document.querySelectorAll('[aria-label="Toggle checkbox"]')
        let retries = 0

        while (checkboxes.length < DELETION_BATCH_SIZE && retries < 10) {
            await slowScrollDown(2000, 4)
            await delay(2000)
            checkboxes = document.querySelectorAll('[aria-label="Toggle checkbox"]')
            retries++
        }

        if (checkboxes.length === 0) {
            console.log("✅ No more comments to delete")
            return
        }

        for (let i = 0; i < Math.min(DELETION_BATCH_SIZE, checkboxes.length); i++) {
            await clickElement(checkboxes[i])
            await delay(DELAY_BETWEEN_CHECKBOX_CLICKS_MS)
        }

        await delay(DELAY_BETWEEN_ACTIONS_MS)
        await deleteSelectedComments()
        await delay(DELAY_BETWEEN_ACTIONS_MS)
        await waitForSelectButton()
        await delay(DELAY_BETWEEN_ACTIONS_MS)
        await handleWrongMessage()
    }
}

try {
    await deleteActivity()
    console.log("🎉 Deletion finished")
} catch (err) {
    console.error("Fatal error:", err.message)
}

})()

@zackdarver-ctrl

Copy link
Copy Markdown

?

@zackdarver-ctrl

Copy link
Copy Markdown

?

@zackdarver-ctrl

Copy link
Copy Markdown

Ok

@zackdarver-ctrl

Copy link
Copy Markdown

What do I need to do

@braunglasrakete

Copy link
Copy Markdown
Author

Just FYI, I updated this to serve my purpose back then and I will not maintain or update this any further. It is here for reference, for people to fork and update if need be. Thanks for understanding.

@Umbra0x01

Umbra0x01 commented Nov 21, 2025 •

Copy link
Copy Markdown

I was having issues with the script failing after roughly 40-50 posts, so I copied @marcobucca 's implementation from the Like Activity Deleter, and had ChatGPT modify it to remove comments instead. This implementation uses Tampermonkey, and does the following, quoting from Marcos documentation:

_- Automatically clicks on ‘Sort & filter’ → ‘Oldest to newest’ to start with the oldest posts.

  • Selects up to 80 posts at a time, scrolling the page as it loads them.
  • Automatically handles delays or slow loading of Instagram servers after 5 failed attempts, reloading the page and starting over automatically.
  • Completely automatic after launch — no manual intervention required._

Also tried to get rid of the Permission Policy Violation related to the unload function, and I was able to reduce the amount of times it popped up, but was unable to get rid of it entirely. Here's what worked for me:
;(async function () {
'use strict';

const DELETION_BATCH_SIZE = 80;
const SCROLL_ATTEMPTS = 6;
const DELAY_BETWEEN_SCROLLS_MS = 1200;
const DELAY_BETWEEN_CHECKBOX_CLICKS_MS = 60;
const MAX_SELECT_ATTEMPTS = 5;
const DELAY_AFTER_ACTION_MS = 1200;

const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

const clickElement = async (el) => {
if (!el) return;
el.click();
await delay(250);
};

// Same container scroll logic as like script
const scrollCollectionContainer = async (maxScrolls = SCROLL_ATTEMPTS, delayMs = DELAY_BETWEEN_SCROLLS_MS) => {
const container = document.querySelector('[data-bloks-name="bk.components.Collection"]');
if (!container) return;
let prevHeight = 0;
for (let i = 0; i < maxScrolls; i++) {
container.scrollBy(0, container.scrollHeight);
await delay(delayMs);
const currentHeight = container.scrollHeight;
if (currentHeight === prevHeight) break;
prevHeight = currentHeight;
}
};

const waitForElement = async (text, timeout = 8000) => {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
const allElements = document.querySelectorAll('*');
const element = Array.from(allElements).find(el => el.textContent === text);
if (element) return element;
await delay(150);
}
return null;
};

// Optional: same sort & filter helper as like script
const applySortFilterOldest = async () => {
window.scrollTo(0, 0);
await delay(800);

const clickButtonBySpanText = async (text, retries = 10) => {
    for (let attempt = 1; attempt <= retries; attempt++) {
        const spans = Array.from(document.querySelectorAll('span')).filter(s =>
            s.textContent.trim() === text
        );

        if (spans.length > 0) {
            let clickable = spans[0];
            while (clickable && (!clickable.getAttribute('role') || clickable.getAttribute('role') !== 'button')) {
                clickable = clickable.parentElement;
            }
            if (clickable) {
                clickable.scrollIntoView({ behavior: 'smooth', block: 'center' });
                await delay(300);
                clickable.click();
                console.log(`"${text}" clicked`);
                return true;
            }
        }

        console.log(`Attempt ${attempt} for "${text}" failed, retrying...`);
        await delay(500);
    }
    console.log(`"${text}" not found after ${retries} attempts`);
    return false;
};

const clickApplyButton = async (retries = 10) => {
    for (let attempt = 1; attempt <= retries; attempt++) {
        const divs = Array.from(document.querySelectorAll('div[role="button"][tabindex="0"]'));
        const applyDiv = divs.find(d => d.textContent.trim() === 'Apply');
        if (applyDiv) {
            applyDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
            await delay(300);
            applyDiv.click();
            console.log('Apply clicked');
            return true;
        }
        console.log(`Attempt ${attempt} for "Apply" failed, retrying...`);
        await delay(500);
    }
    console.log('Apply not found after all attempts');
    return false;
};

if (await clickButtonBySpanText('Sort & filter')) {
    await delay(800);
    if (await clickButtonBySpanText('Oldest to newest')) {
        await delay(800);
        await clickApplyButton();
    }
}

};

// === Delete helpers ===
const getDeleteButton = async () => {
// Method 1: specific CSS selector
let deleteBtn = document.querySelector(
'.wbloks_50 > div:nth-child(1) > div:nth-child(4) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1)'
);
if (deleteBtn) {
console.log('Found delete button using CSS selector');
return deleteBtn;
}

// Method 2: XPath
deleteBtn = document.evaluate(
    '/html/body/div[1]/div/div/div[2]/div/div/div[1]/div[1]/div[1]/section/main/div/article/div/div[2]/div/div/div[1]/div/div/div/div/div/div[4]/div/div/div[2]/div/div/div[2]/div/div/div/div/div/div[1]/div/span',
    document,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null
).singleNodeValue;
if (deleteBtn) {
    console.log('Found delete button using XPath');
    return deleteBtn;
}

// Method 3: elements containing "Delete"
const elems = Array.from(document.querySelectorAll('span, div, button'));
deleteBtn = elems.find(el => el.innerText && el.innerText.trim().toLowerCase().includes('delete'));
if (deleteBtn) {
    console.log('Found delete button using text search');
    return deleteBtn;
}

// Method 4: broader clickable search
const clickableElems = Array.from(document.querySelectorAll('[role="button"], button, .wbloks_50 span, .wbloks_50 div[role="button"]'));
for (const elem of clickableElems) {
    const txt = elem.innerText?.toLowerCase() || '';
    const aria = elem.getAttribute('aria-label')?.toLowerCase() || '';
    if (txt.includes('delete') || aria.includes('delete')) {
        console.log('Found delete button using broader search');
        return elem;
    }
}

console.log('Delete button not found with any method');
return null;

};

const getConfirmButton = async () => {
let confirmBtn = document.querySelector('button._a9--:nth-child(1)');
if (confirmBtn) {
console.log('Found confirm button using specific selector');
return confirmBtn;
}

confirmBtn = document.querySelector('button[tabindex="0"]');
if (confirmBtn) {
    console.log('Found confirm button using tabindex');
    return confirmBtn;
}

const buttons = Array.from(document.querySelectorAll('button'));
confirmBtn = buttons.find(btn => {
    const text = btn.innerText?.toLowerCase() || '';
    return text.includes('delete') || text.includes('confirm') || text.includes('yes');
});
if (confirmBtn) {
    console.log('Found confirm button using text search');
    return confirmBtn;
}

console.log('Confirm button not found');
return null;

};

const handleWrongMessage = async () => {
const msgs = document.querySelectorAll('div, span, p');
for (const msg of msgs) {
if (msg.textContent.toLowerCase().includes('wrong')) {
const buttons = document.querySelectorAll('button');
for (const btn of buttons) {
if (/^(ok)$/i.test(btn.textContent.trim())) {
await clickElement(btn);
await delay(500);
window.scrollTo(0, 0);
break;
}
}
break;
}
}
};

const deleteSelectedComments = async () => {
try {
console.log('Looking for delete button...');
const deleteButton = await getDeleteButton();
if (!deleteButton) {
console.log('Delete button not found. Stopping delete bot; adjust the page and re-run if needed.');
return;
}

    console.log('Clicking delete button...');
    await clickElement(deleteButton);
    await delay(700);

    console.log('Looking for confirmation button...');
    const confirmButton = await getConfirmButton();
    if (confirmButton) {
        console.log('Clicking confirm button...');
        await clickElement(confirmButton);
    } else {
        console.log('Warning: confirmation button not found');
    }

    await delay(900);
    await handleWrongMessage();
} catch (err) {
    console.error('Error during comment deletion:', err);
}

};

const deleteActivity = async () => {
try {
// Optional: call once manually before starting, if you want sorting
// await applySortFilterOldest();

    let selectButton = null;
    let attempts = 0;

    while (!selectButton && attempts < MAX_SELECT_ATTEMPTS) {
        selectButton = await waitForElement('Select', 3000);
        attempts++;
        if (!selectButton) {
            console.log(`Select not found, attempt ${attempts}/${MAX_SELECT_ATTEMPTS}`);
        }
    }

    if (!selectButton) {
        console.log('❌ Select button not found. Stopping delete bot; reload or adjust the page and run again if needed.');
        return;
    }

    await clickElement(selectButton);
    await delay(600);
    await scrollCollectionContainer(SCROLL_ATTEMPTS, DELAY_BETWEEN_SCROLLS_MS);

    const checkboxes = document.querySelectorAll('[aria-label="Toggle checkbox"]');
    const countToSelect = Math.min(DELETION_BATCH_SIZE, checkboxes.length);

    if (countToSelect === 0) {
        console.log('✅ No more comments to delete');
        return;
    }

    for (let i = 0; i < countToSelect; i++) {
        checkboxes[i].click();
        await delay(DELAY_BETWEEN_CHECKBOX_CLICKS_MS);
    }

    await deleteSelectedComments();
    await delay(DELAY_AFTER_ACTION_MS);
    deleteActivity();  // recursive loop, like unlikeActivity

} catch (error) {
    console.error('Error in deleteActivity:', error);
    await delay(1800);
    deleteActivity();
}

};

deleteActivity();
})();

Hope this helps! Good luck to all!

@NooaJ

NooaJ commented Jan 25, 2026 •

Copy link
Copy Markdown

The following script worked reliably for me:
;(async function () {
'use strict';

const DELETION_BATCH_SIZE = 80;
const SCROLL_ATTEMPTS = 6;
const DELAY_BETWEEN_SCROLLS_MS = 1200;
const DELAY_BETWEEN_CHECKBOX_CLICKS_MS = 60;
const MAX_SELECT_ATTEMPTS = 5;
const DELAY_AFTER_ACTION_MS = 1200;
const POST_SCROLL_WAIT_MS = 5000; // Wait after scrolling for new comments to load

const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

const clickElement = async (el) => {
if (!el) return;
el.click();
await delay(250);
};

// === UPDATED SCROLL LOGIC ===
const scrollCollectionContainer = async (maxScrolls = SCROLL_ATTEMPTS, delayMs = DELAY_BETWEEN_SCROLLS_MS) => {
const container = document.querySelector('[data-bloks-name="bk.components.Collection"]');
if (!container) return;

let lastCount = 0;
let sameCountStreak = 0;

for (let i = 0; i < maxScrolls; i++) {
    container.scrollBy(0, container.scrollHeight);
    await delay(delayMs);

    const currentCount = document.querySelectorAll('[aria-label="Toggle checkbox"]').length;

    if (currentCount === lastCount) {
        sameCountStreak++;
    } else {
        sameCountStreak = 0;
    }

    lastCount = currentCount;

    // Stop scrolling if no new comments appeared for 2 consecutive scrolls
    if (sameCountStreak >= 2) break;
}

// Wait a bit after scrolling to allow any lazy-loaded comments to appear
await delay(POST_SCROLL_WAIT_MS);

};

// === ORIGINAL HELPER FUNCTIONS ===

const waitForElement = async (text, timeout = 8000) => {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
const allElements = document.querySelectorAll('*');
const element = Array.from(allElements).find(el => el.textContent === text);
if (element) return element;
await delay(150);
}
return null;
};

const getDeleteButton = async () => {
let deleteBtn = document.querySelector(
'.wbloks_50 > div:nth-child(1) > div:nth-child(4) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1)'
);
if (deleteBtn) return deleteBtn;

deleteBtn = document.evaluate(
    '/html/body/div[1]/div/div/div[2]/div/div/div[1]/div[1]/div[1]/section/main/div/article/div/div[2]/div/div/div[1]/div/div/div/div/div/div[4]/div/div/div[2]/div/div/div[2]/div/div/div/div/div/div[1]/div/span',
    document,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null
).singleNodeValue;
if (deleteBtn) return deleteBtn;

const elems = Array.from(document.querySelectorAll('span, div, button'));
deleteBtn = elems.find(el => el.innerText && el.innerText.trim().toLowerCase().includes('delete'));
if (deleteBtn) return deleteBtn;

const clickableElems = Array.from(document.querySelectorAll('[role="button"], button, .wbloks_50 span, .wbloks_50 div[role="button"]'));
for (const elem of clickableElems) {
    const txt = elem.innerText?.toLowerCase() || '';
    const aria = elem.getAttribute('aria-label')?.toLowerCase() || '';
    if (txt.includes('delete') || aria.includes('delete')) return elem;
}

return null;

};

const getConfirmButton = async () => {
let confirmBtn = document.querySelector('button._a9--:nth-child(1)');
if (confirmBtn) return confirmBtn;

confirmBtn = document.querySelector('button[tabindex="0"]');
if (confirmBtn) return confirmBtn;

const buttons = Array.from(document.querySelectorAll('button'));
confirmBtn = buttons.find(btn => {
    const text = btn.innerText?.toLowerCase() || '';
    return text.includes('delete') || text.includes('confirm') || text.includes('yes');
});
return confirmBtn || null;

};

const handleWrongMessage = async () => {
const msgs = document.querySelectorAll('div, span, p');
for (const msg of msgs) {
if (msg.textContent.toLowerCase().includes('wrong')) {
const buttons = document.querySelectorAll('button');
for (const btn of buttons) {
if (/^(ok)$/i.test(btn.textContent.trim())) {
await clickElement(btn);
await delay(500);
window.scrollTo(0, 0);
break;
}
}
break;
}
}
};

const deleteSelectedComments = async () => {
try {
const deleteButton = await getDeleteButton();
if (!deleteButton) return;

    await clickElement(deleteButton);
    await delay(700);

    const confirmButton = await getConfirmButton();
    if (confirmButton) await clickElement(confirmButton);

    await delay(900);
    await handleWrongMessage();
} catch (err) {
    console.error('Error during comment deletion:', err);
}

};

// === MAIN LOOP ===
const deleteActivity = async () => {
try {
let selectButton = null;
let attempts = 0;

    while (!selectButton && attempts < MAX_SELECT_ATTEMPTS) {
        selectButton = await waitForElement('Select', 3000);
        attempts++;
    }

    if (!selectButton) return;

    await clickElement(selectButton);
    await delay(600);

    // Scroll for more comments before selecting checkboxes
    await scrollCollectionContainer(SCROLL_ATTEMPTS, DELAY_BETWEEN_SCROLLS_MS);

    const checkboxes = document.querySelectorAll('[aria-label="Toggle checkbox"]');
    const countToSelect = Math.min(DELETION_BATCH_SIZE, checkboxes.length);

    if (countToSelect === 0) {
        console.log('✅ No more comments to delete');
        return;
    }

    for (let i = 0; i < countToSelect; i++) {
        checkboxes[i].click();
        await delay(DELAY_BETWEEN_CHECKBOX_CLICKS_MS);
    }

    await deleteSelectedComments();
    await delay(DELAY_AFTER_ACTION_MS);

    // Repeat recursively
    deleteActivity();

} catch (error) {
    console.error('Error in deleteActivity:', error);
    await delay(1800);
    deleteActivity();
}

};

deleteActivity();
})();

@PercyJohnHen

Copy link
Copy Markdown

The Latest Working Code as of August 3, 2026

;(async function () {
    'use strict';
    const BATCH_SIZE = 80;
    const SCROLL_ATTEMPTS = 6;
    const DELAY_BETWEEN_SCROLLS_MS = 1200;
    const DELAY_BETWEEN_CHECKBOX_CLICKS_MS = 60;
    const MAX_SELECT_ATTEMPTS = 5;
    const DELAY_AFTER_ACTION_MS = 1200;

    const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

    const clickElement = async (el) => {
        if (!el) return;
        el.scrollIntoView({ behavior: 'smooth', block: 'center' });
        await delay(100);
        el.click();
        await delay(250);
    };

    const scrollCollectionContainer = async (maxScrolls = SCROLL_ATTEMPTS, delayMs = DELAY_BETWEEN_SCROLLS_MS) => {
        const container = document.querySelector('[data-bloks-name="bk.components.Collection"]');
        if (!container) return;
        let prevHeight = 0;
        for (let i = 0; i < maxScrolls; i++) {
            container.scrollBy(0, container.scrollHeight);
            await delay(delayMs);
            const currentHeight = container.scrollHeight;
            if (currentHeight === prevHeight) break;
            prevHeight = currentHeight;
        }
    };

    const waitForElement = async (text, timeout = 8000) => {
        const startTime = Date.now();
        while (Date.now() - startTime < timeout) {
            const allElements = document.querySelectorAll('*');
            const element = Array.from(allElements).find(el => el.textContent === text);
            if (element) return element;
            await delay(150);
        }
        return null;
    };

    const getActionButton = async () => {
        const elems = Array.from(document.querySelectorAll('span, div, button'));
        let actionBtn = elems.find(el => {
            const txt = (el.innerText || el.textContent || '').trim().toLowerCase();
            return txt === 'unlike' || txt === 'delete';
        });
        
        if (actionBtn) { 
            console.log(`Found action button: ${actionBtn.textContent.trim()}`); 
            return actionBtn; 
        }

        const clickableElems = Array.from(document.querySelectorAll('[role="button"], button'));
        for (const elem of clickableElems) {
            const txt = (elem.innerText || elem.textContent || '').toLowerCase();
            if (txt === 'unlike' || txt === 'delete') {
                console.log('Found action button using broader search');
                return elem;
            }
        }
        console.log('Action button not found');
        return null;
    };

    const getConfirmButton = async (actionBtn) => {
        const activeDialog = document.querySelector('[role="dialog"]');
        if (activeDialog) {
            const dialogClickables = Array.from(activeDialog.querySelectorAll('[role="button"], button, div, span'));
            const confirmBtn = dialogClickables.find(el => {
                const text = (el.textContent || '').trim().toLowerCase();
                return text === 'unlike' || text === 'delete' || text === 'confirm' || text === 'yes';
            });
            if (confirmBtn) { console.log('Found confirm button inside dialog'); return confirmBtn; }
        }

        const allClickables = Array.from(document.querySelectorAll('[role="button"], button')).reverse();
        const confirmBtn = allClickables.find(btn => {
            if (btn === actionBtn) return false; 
            
            const text = (btn.innerText || btn.textContent || '').trim().toLowerCase();
            return text === 'unlike' || text === 'delete' || text === 'confirm' || text === 'yes';
        });
        
        if (confirmBtn) { console.log('Found confirm button via broad text match'); return confirmBtn; }
        console.log('Confirm button not found');
        return null;
    };

    const processSelectedItems = async () => {
        try {
            console.log('Looking for action button...');
            const actionButton = await getActionButton();
            if (!actionButton) {
                console.log('Action button not found. Stopping bot.');
                return;
            }
            
            console.log('Clicking action button...');
            await clickElement(actionButton);
            
            await delay(1500); 

            console.log('Looking for confirmation button...');
            const confirmButton = await getConfirmButton(actionButton);
            if (confirmButton) {
                console.log('Clicking confirm button...');
                await clickElement(confirmButton);
            } else {
                console.log('Warning: confirmation button not found');
            }
            await delay(900);
        } catch (err) {
            console.error('Error during action confirmation:', err);
        }
    };

    const runActivity = async () => {
        try {
            let inSelectMode = false;
            const cancelBtn = await waitForElement('Cancel', 1000); 
            if (cancelBtn) {
                console.log('Already in selection mode. Resuming...');
                inSelectMode = true;
            }

            if (!inSelectMode) {
                let selectButton = null;
                let attempts = 0;
                while (!selectButton && attempts < MAX_SELECT_ATTEMPTS) {
                    selectButton = await waitForElement('Select', 2000);
                    attempts++;
                    if (!selectButton) console.log(`Select not found, attempt ${attempts}/${MAX_SELECT_ATTEMPTS}`);
                }

                if (!selectButton) {
                    console.log('❌ Select button not found. Stopping bot.');
                    return;
                }
                await clickElement(selectButton);
                await delay(600);
            }

            await scrollCollectionContainer(SCROLL_ATTEMPTS, DELAY_BETWEEN_SCROLLS_MS);

            const checkboxes = document.querySelectorAll('[aria-label="Toggle checkbox"]');
            const countToSelect = Math.min(BATCH_SIZE, checkboxes.length);

            if (countToSelect === 0) {
                console.log('✅ No more items to process');
                return;
            }

            if (!inSelectMode) {
                for (let i = 0; i < countToSelect; i++) {
                    checkboxes[i].click();
                    await delay(DELAY_BETWEEN_CHECKBOX_CLICKS_MS);
                }
            }

            await processSelectedItems();
            await delay(DELAY_AFTER_ACTION_MS);
            
            runActivity(); 

        } catch (error) {
            console.error('Error in runActivity:', error);
            await delay(1800);
            runActivity();
        }
    };

    runActivity();
})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment