post instagram comment programmatically with js

Viewed 5184

I'm creating an instagram bot that posts a comment on a user's photo. I'm aware there are already solutions like InstaPy but it isn't working for me and I'm 99% complete with my own js solution.

Is there a way for me to post programmatically? I already set the textArea.value and I tried to submit the wrapping form (it just refreshes the page). I also tried to "click" the submit button but it isn't causing it to do anything. I also tried to "type" into the textarea but it seems that isn't possible without any actual user interaction on the screen as well as trying to submit the actual request (seems my headers don't match up and I'm getting a 403 error.) Below is a code snippet of what I'm currently doing.

var commentTextArea = document.getElementsByClassName('Ypffh')[0];
if (commentTextArea) {

    // Text area for posting comment
    commentTextArea.textContent = "This is my comment :)";

    setTimeout(function() {

        // Comment submit button
        var submitButton = document.getElementsByClassName('LCjcc')[0];
        submitButton.disabled = false;
        submitButton.click(); // doesn't fire anything. I can see in chrome dev tools there is no event event attached to this even when enabled which is odd

        // Comment form
        // Submitting form expectedly refreshes page
        // Tried add my own submit listener with return false && e.preventDefault and neither worked
        var form = document.querySelector('X7cDz');
        if (form) {

            form.submit();
        }
    }, 2000);
}
1 Answers

You are getting 403 error because you do not submit csrf token. You can read about it more here

In order to overcome this challenge, you can use libraries that provide a high-level API to control browsers like Puppeteer. This allows you to write a script which will run a browser and will act like a real user, surfing pages and leaving comments wherever you want.

Here is an example of code that signs into the Instagram and leaves a comment under a specific post:

const puppeteer = require('puppeteer');

(async () => {
  // Starting browser
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();

  // Login flow
  await page.goto('https://www.instagram.com/accounts/login/?source=auth_switcher');
  await page.waitForSelector('input[name="username"]');
  await page.type('input[name="username"]', 'username');
  await page.type('input[name="password"]', 'password');
  await page.click('button[type="submit"]');

  // Waiting for page to refresh
  await page.waitForNavigation();

  // Navigate to post and submitting the comment
  await page.goto('https://www.instagram.com/p/BVSCQI-FRaj/');
  await page.waitForSelector('textarea');
  await page.type('textarea', 'Test comment');

  await page.click('button[type="submit"]');

  await browser.close();
})();
Related