I'm new so still learning about puppeteer. I've created a simple auto responder for my business. It works but sometimes it breaks when a different selector pops up, for example, a different type of message pops up in my inbox and I need to deal with it in a completely different way. For example I need to do different steps than in the code below and then I need to restart the loop over from the beginning without have it continue to run. It usually breaks at because an error message pops up:
await page.waitForSelector('[aria-label="Message"]').then(selector => selector.click());
How can I add on different steps to this and then restart the loop from the beginning?
const browser = await puppeteer.launch({
headless: false,
executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
ignoreDefaultArgs: true,
args: [
'--remote-debugging-port=9444',
'--user-data-dir=D:/chrome-profiles/toys',
'--no-first-run',
'--no-default-browser-check',
`--window-size=1920,1080`
]
});
await new Promise(r => setTimeout(r, 2000));
const pages = await browser.pages();
const page = pages[0];
const line1 = 'Hello,'
const line2 = "This product will be available again in 2 days. There will be a notification on our page when it's back in stock."
await page.goto('https://www.facebook.com/messages/t/');
await new Promise(r => setTimeout(r, 2000));
const messages = await page.$$('[data-testid="mwthreadlist-item-open"]');
for (i = 0; i < messages.length; i++) {
const message = messages[i];
await message.click();
//type message
await page.waitForSelector('[aria-label="Message"]').then(selector => selector.click());
await new Promise(r => setTimeout(r, 1000));
await page.type('[aria-label="Message"]', line1, { delay: 5 });
await page.keyboard.down("ShiftRight")
await page.keyboard.down("Enter")
await page.keyboard.down("Enter")
await page.type('[aria-label="Message"]', line2, { delay: 5 });
await page.keyboard.down("ShiftRight")
await page.keyboard.down("Enter")
await page.keyboard.down("Enter")
//Send Message
await page.waitForSelector('.c7y9u1f0 > .db0glzta').then(selector => selector.click());
await new Promise(r => setTimeout(r, 2000));
//delete chat
await page.waitForSelector('.qtx5e3l4 > .b6ax4al1').then(selector => selector.click());
await new Promise(r => setTimeout(r, 2000));
}
})();