dilame / instagram-private-api

NodeJS Instagram private API SDK. Written in TypeScript.
MIT License
5.93k stars 1.14k forks source link

IgNetworkError [RequestError] when trying to connect to instagram #1344

Open tupizz opened 3 years ago

tupizz commented 3 years ago

Bug Report

Requirements

Description

A specific description of your bug, so it's understandable to anyone. If you have pictures or videos to upload, please add a link like this: [title](url).

YOUR DESCRIPTION HERE I am getting a IgNetworkError [RequestError]: Error: connect ETIMEDOUT 31.13.85.52:443 when trying to connect to the Instagram, I already checked my credentials and they are all correct, but I am getting this error, and this is printed when I subscribe to the error observable of request. Does anyone had this problem?

Code

Add a meaningful section of your code here. If you are using TypeScript replace js with typescript.

import inquirer from 'inquirer';
import { IgApiClient, IgCheckpointError, IgLoginTwoFactorRequiredError } from 'instagram-private-api';

import { UserData } from '../types/user-data';
import { log } from '../utils/logger';
import { HandleSession } from './handle-session';

const connect = async (ig: IgApiClient, userData: UserData) => {
  await ig.simulate.preLoginFlow();

  return ig.account
    .login(userData.username, userData.password)
    .catch(async (err: IgLoginTwoFactorRequiredError) => {
      const { username, totp_two_factor_on, two_factor_identifier } = err.response.body.two_factor_info;

      // decide which method to use
      const verificationMethod = totp_two_factor_on ? '0' : '1'; // default to 1 for SMS

      const { code } = await inquirer.prompt([
        {
          type: 'input',
          name: 'code',
          message: `Enter code received via ${verificationMethod === '1' ? 'SMS' : 'TOTP'}`,
        },
      ]);

      // Use the code to finish the login process
      return ig.account.twoFactorLogin({
        username,
        verificationCode: code,
        twoFactorIdentifier: two_factor_identifier,
        verificationMethod, // '1' = SMS (default), '0' = TOTP (google auth for example)
      });
    })
    .catch(async (err: IgCheckpointError) => {
      console.log('IgCheckpointError', err);
      console.log(ig.state.checkpoint); // Checkpoint info here
      await ig.challenge.selectVerifyMethod('1', false); //1. Email 0. SMS  send code OTP
      console.log(ig.state.checkpoint); // Challenge info here
      log('[+++] Check SMS');
      const { code } = await inquirer.prompt([
        {
          type: 'input',
          name: 'code',
          message: 'Enter code',
        },
      ]);
      console.log(await ig.challenge.sendSecurityCode(code));
    });
};

export const connectToInstagram = async ({
  clientIg,
  sessionHandlerInstance,
  userData,
}: {
  clientIg: IgApiClient;
  sessionHandlerInstance: HandleSession;
  userData: UserData;
}) => {
  // This function executes after every request
  clientIg.request.end$.subscribe(async () => {
    const serialized = await clientIg.state.serialize();
    delete serialized.constants;
    sessionHandlerInstance.persistSession(serialized);
  });

  clientIg.request.error$.subscribe(async (err) => {
    console.log(err);
  });

  // Se existir um arquivo de sessão, então carregamos a partir dele
  if (sessionHandlerInstance.existSessionFile()) {
    await clientIg.state.deserialize(sessionHandlerInstance.loadSessionFile());
  } else {
    await connect(clientIg, userData);
  }
};

export const igConnect = async () => {
  const USER_OBJECT = {
    username: process.env.username ,
    password: process.env.password ,
  };

  const ig = new IgApiClient();
  const sessionHandler = new HandleSession();
  ig.state.generateDevice(USER_OBJECT.username);

  // Cria nova conexão baseado na sessão salva no temp
  await connectToInstagram({
    clientIg: ig,
    sessionHandlerInstance: sessionHandler,
    userData: USER_OBJECT,
  });

  return {
    ig,
  };
};

Error and Output

If you've got an error put it here. You can get the stacktrace in the most environments using Error.stack (MDN Docs).

IgNetworkError [RequestError]: Error: connect ETIMEDOUT 31.13.85.52:443
    at Request.faultTolerantRequest (/home/tupizz/Desktop/sparkbox/instagram-bot/node_modules/instagram-private-api/dist/core/request.js:132:19) {
  cause: Error: connect ETIMEDOUT 31.13.85.52:443
      at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16) {
    errno: 'ETIMEDOUT',
    code: 'ETIMEDOUT',
    syscall: 'connect',
    address: '31.13.85.52',
    port: 443
  },
  error: Error: connect ETIMEDOUT 31.13.85.52:443
      at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16) {
    errno: 'ETIMEDOUT',
    code: 'ETIMEDOUT',
    syscall: 'connect',
    address: '31.13.85.52',
    port: 443
  },
  options: {
    method: 'POST',
    url: '/api/v1/accounts/contact_point_prefill/',
    form: {
      ig_sig_key_version: '4',
      signed_body: 'e52986d4c6e40ac562fd36d5358f42f902ac994458600e9a60537def7a9f0107.{"mobile_subno_usage":"prefill","device_id":"b5538460-66c6-5d89-8d9a-eefb9b052797"}'
    },
    baseUrl: 'https://i.instagram.com/',
    resolveWithFullResponse: true,
    simple: false,
    transform: [Function: requestTransform],
    jar: RequestJar { _jar: [CookieJar] },
    strictSSL: false,
    gzip: true,
    headers: {
      'User-Agent': 'Instagram 121.0.0.29.119 Android (25/7.1.1; 440dpi; 1080x1920; Xiaomi; MI MAX 2; oxygen; qcom; en_US; 185203708)',
      'X-Ads-Opt-Out': '0',
      'X-CM-Bandwidth-KBPS': '-1.000',
      'X-CM-Latency': '-1.000',
      'X-IG-App-Locale': 'en_US',
      'X-IG-Device-Locale': 'en_US',
      'X-Pigeon-Session-Id': 'e20ab8d5-ff50-56ec-9106-5b0cc51e7a4f',
      'X-Pigeon-Rawclienttime': '1608853415.593',
      'X-IG-Connection-Speed': '2605kbps',
      'X-IG-Bandwidth-Speed-KBPS': '-1.000',
      'X-IG-Bandwidth-TotalBytes-B': '0',
      'X-IG-Bandwidth-TotalTime-MS': '0',
      'X-IG-EU-DC-ENABLED': undefined,
      'X-IG-Extended-CDN-Thumbnail-Cache-Busting-Value': '1000',
      'X-Bloks-Version-Id': '1b030ce63a06c25f3e4de6aaaf6802fe1e76401bc5ab6e5fb85ed6c2d333e0c7',
      'X-MID': 'X-UnpwABAAFQU5INmIUSsDuRTQmC',
      'X-IG-WWW-Claim': '0',
      'X-Bloks-Is-Layout-RTL': 'false',
      'X-IG-Connection-Type': 'WIFI',
      'X-IG-Capabilities': '3brTvwE=',
      'X-IG-App-ID': '567067343352427',
      'X-IG-Device-ID': 'b5538460-66c6-5d89-8d9a-eefb9b052797',
      'X-IG-Android-ID': 'android-7e4e71609b5d656d',
      'Accept-Language': 'en-US',
      'X-FB-HTTP-Engine': 'Liger',
      Authorization: undefined,
      Host: 'i.instagram.com',
      'Accept-Encoding': 'gzip',
      Connection: 'close'
    },
    callback: [Function: RP$callback],
    transform2xxOnly: false
  },
  response: undefined
}
Nerixyz commented 3 years ago

Have you tried doing a simple request to the server? If not the try this without the library:

import httpClient from 'anyHttpLibrary';

console.log(await httpClient ('https://31.13.85.52/'));
console.log(await httpClient ('https://i.instagram.com'));

This should return the same response. The status should be in the 3xx range as it will redirect to www.instagram.com.

tupizz commented 3 years ago

@Nerixyz I will try it then.

So, maybe it could be my connection, or perhaps Instagram is blocking during some seconds the requests from my IP address?

tupizz commented 3 years ago

@Nerixyz Using a pool of proxies should solve this problem?

junaidatique commented 3 years ago

any update on this issue as I am facing the same problem.

tupizz commented 3 years ago

Not from me 😢

seanconrad1 commented 3 years ago

@tupizz what's the best way of to go about using a pool of proxies?

usamaejaz commented 3 years ago

@Nerixyz the response for the POST request to /api/v1/accounts/get_prefill_candidates/ is (HTML) Instagram.com's login page. This only happens on production server. Local is fine.

Nerixyz commented 3 years ago

@Nerixyz the response for the POST request to /api/v1/accounts/get_prefill_candidates/ is (HTML) Instagram.com's login page. This only happens on production server. Local is fine.

Instagram redirects the user by default to the login page. Not sure why.

kashirin-dm commented 3 years ago

@Nerixyz the response for the POST request to /api/v1/accounts/get_prefill_candidates/ is (HTML) Instagram.com's login page. This only happens on production server. Local is fine.

The same (((

kashirin-dm commented 3 years ago

I tried to go to Instagram using a browser and my proxy. It was suspiciously for Instagram. I needed an SMS code to enter. This is two-factor authentication and this needed a 302 redirect.

Also, I found this: https://stackoverflow.com/questions/39251999/instagram-app-authentication-without-redirect But this information about the official API.

kashirin-dm commented 3 years ago

This pull request https://github.com/dilame/instagram-private-api/pull/1412 solves the problem. Fixes available now in the latest 1.44.1 version.

But I use Androz2091/insta.js. There @Androz2091 using an old version of instagram-private-api.

Androz2091 commented 3 years ago

I could bump the version of my package

sreza78 commented 3 years ago

same here any fixes!?

tupizz commented 3 years ago

afaik no