dilame / instagram-private-api

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

Cookie login doesn't works #1743

Open BilalTaner opened 9 months ago

BilalTaner commented 9 months ago

General Question

Read the Notes and fill out the form.

Even though I log in with a cookies, my login function works every time I use any command. That's why I'm constantly blocked by Instagram. What should I do?

const sessionPath = "session.json";
// Save the session data to a JSON file
function saveSession(sessionData) {
    fs.writeFileSync(sessionPath, JSON.stringify(sessionData));
    console.log('Session saved successfully! ');
}

// Log in and save session
async function loginInstagram() {
    try {
        ig.state.generateDevice(IG_USERNAME);
        ig.state.language = "tr_TR"
        ig.request.end$.subscribe(async () => {
            const serialized = await ig.state.serialize();
            delete serialized.constants;
            saveSession(serialized);
        });

        if (fs.existsSync(sessionPath)) {
            const sessionData = fs.readFileSync(sessionPath, 'utf8');
            await ig.state.deserialize(JSON.parse(sessionData)).then(() => console.log('Session loaded successfully!'));
        } else {
            await ig.account.login(IG_USERNAME, IG_PASSWORD).then(() => console.log('Logged in successfully!'));
        }

        return ig;
    } catch (error) {
        console.error('Failed to log in:', error);
        return null;
    }
};

(async () => {
    await loginInstagram();
})().then(() => console.log("Sucesss."))
IgCheckpointError: GET /api/v1/users/search/?timezone_offset=10800&q=xxx&count=30 - 400 Bad Request; challenge_required,
IgResponseError: GET /api/v1/friendships/1904779401/followers/?max_id=125&order=default&query=&enable_groups=true - 401 Unauthorized;

image ERROR-1 (I made a counter for find requests.)

g5fighter commented 6 months ago

Any solution? I'm having the same error

sercanersoy commented 6 months ago

This works for me:

const ig = new IgApiClient();

const statePath = 'state';
let userId: string;

if (fs.existsSync(statePath)) {
  const state = fs.readFileSync(statePath).toString();
  ig.state.deserialize(state);
  userId = ig.state.extractUserId();
} else {
  ig.state.generateDevice(process.env.IG_USERNAME);

  const loggedInUser = await ig.account.login(
    process.env.IG_USERNAME,
    process.env.IG_PASSWORD,
  );
  userId = loggedInUser.pk.toString();

  const state = await ig.state.serialize();
  fs.writeFileSync(statePath, JSON.stringify(state));
}

const userInfo = await ig.user.info(userId);
const follower_count = userInfo.follower_count;

console.log(`User id: ${userId}`);
console.log(`Follower count: ${follower_count}`);
bhr commented 6 months ago

@sercanersoy Thank you!

We used to have ig.state.generateDevice before deserializing the cookie. After upgrading the library, this results in the login not working anymore if the session cookie cannot be deserialized.

The solution is to move ig.state.generateDevice(…) just before the login and not call it when deserializing from cookie

sabbaticaldev commented 4 months ago

This works for me:

const ig = new IgApiClient();

const statePath = 'state';
let userId: string;

if (fs.existsSync(statePath)) {
  const state = fs.readFileSync(statePath).toString();
  ig.state.deserialize(state);
  userId = ig.state.extractUserId();
} else {
  ig.state.generateDevice(process.env.IG_USERNAME);

  const loggedInUser = await ig.account.login(
    process.env.IG_USERNAME,
    process.env.IG_PASSWORD,
  );
  userId = loggedInUser.pk.toString();

  const state = await ig.state.serialize();
  fs.writeFileSync(statePath, JSON.stringify(state));
}

const userInfo = await ig.user.info(userId);
const follower_count = userInfo.follower_count;

console.log(`User id: ${userId}`);
console.log(`Follower count: ${follower_count}`);

To use this solution I needed to add a "await" before ig.state.deserialize(state)