Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Max Besties Exceeded Error While Adding Followers to Close Friends List #1800

Open
hamza08003 opened this issue Oct 10, 2024 · 42 comments
Open
Labels
bug unconfirmed This issue hasn't been read/confirmed/accepted by an admin

Comments

@hamza08003
Copy link

hamza08003 commented Oct 10, 2024

Max besties exceeded Error While Adding Followers to Close Friends List

Description

While adding followers to the close friends list, I encountered a 400 Bad Request error with the message "max besties exceeded" after adding 9,999 followers. There were no issues during the process of adding followers in batches up to this point, but once the close friends list reached 9,999 users, the error consistently appeared. The error occurred after attempting to add more followers using the setBesties endpoint.

The error encountered:

Retry failed: IgResponseError: POST /api/v1/friendships/set_besties/ - 400 Bad Request; max besties exceeded
    at Request.handleResponseError (C:\Users\hamza\Desktop\instagram-close-friends-automation-ts\node_modules\instagram-private-api\src\core\request.ts:172:12)
    at Request.send (C:\Users\hamza\Desktop\instagram-close-friends-automation-ts\node_modules\instagram-private-api\src\core\request.ts:83:24)
    at async FriendshipRepository.setBesties (C:\Users\hamza\Desktop\instagram-close-friends-automation-ts\node_modules\instagram-private-api\src\repositories\friendship.repository.ts:76:22)

image

Relevant code section:

await ig.friendship.setBesties({ add: batch, remove: [] });
// Function to add followers to the close friends list
async function addToCloseFriends(ig: IgApiClient, followerIds: string[], batchSize: number, requestDelay: number, batchDelay: number) {
    let totalAdded = 0;
    console.log(`Adding ${followerIds.length} followers to close friends list...`);
    for (let i = 0; i < followerIds.length; i += batchSize) {
        const batch = followerIds.slice(i, i + batchSize);
        try {
            await ig.friendship.setBesties({ add: batch, remove: [] });
            totalAdded += batch.length;
            console.log(`Added batch ${Math.floor(i / batchSize) + 1} to close friends. Total added: ${totalAdded}`);
            await new Promise(resolve => setTimeout(resolve, requestDelay))
        } catch (error) {
            if (error instanceof IgNotFoundError) {
                console.error('An API endpoint was not found:', error.message);
            } else {
                console.error('An error occurred while adding to close friends:', error);
            }
            break;
        }
    
        await new Promise(resolve => setTimeout(resolve, batchDelay));
    }
    console.log('All followers have been added to the close friends list.');

Key Details

  • No issues occurred while adding followers up to 9,999.
  • The error consistently appears when attempting to exceed the 9,999 follower limit.
@hamza08003 hamza08003 added bug unconfirmed This issue hasn't been read/confirmed/accepted by an admin labels Oct 10, 2024
@keroo43o423
Copy link

any updates on this? im also limited

@hamza08003
Copy link
Author

any updates on this? im also limited

Unfortunately, I haven't found a workaround yet, but I'm still looking into possible solutions. If you come across any idea or updates on this, the do share!

@keroo43o423
Copy link

i think we should sniff traffic on mobile app (when in close friends section) to learn the new endpoint and request.

@keroo43o423
Copy link

i know there are people who can add more than 1m followers to close friends.
you can't add more than 10k close friends when mimicking a desktop device using this endpoint: https://i.instagram.com/api/v1/friendships/set_besties/

@keroo43o423
Copy link

you're getting this error: max besties exceeded , right

@hamza08003
Copy link
Author

i think we should sniff traffic on mobile app (when in close friends section) to learn the new endpoint and request.

Yes I'm getting the problem Ater 9999 followers, I also know people who added around 50k+ followers to the close friends list.

And I saw on one forum, someone was saying that on desktop, the close friends list starts glitching after 9999 followers so you can't add more.

So Sniffing traffic on the mobile app sounds like a good idea to explore any different endpoints or requests.

@sunmasters
Copy link

I am able to do without problems. You are using old API, that has limit.

@hamza08003
Copy link
Author

I am able to do without problems. You are using old API, that has limit.

Could you share how you managed to do it without any issues? Which API did you use ?

@sunmasters
Copy link

It is hidden API. Can't share
jumpshare. com/s/Ltn8lXtMoIX0daNrmVAC

@DoubleTroubleOf
Copy link

any updates here?
Could someone share the API without this limit ?

@marcelocardozo
Copy link

any updates here? Could someone share the API without this limit ?

I managed to solve

@caioalmeidan
Copy link

Como resolver @marcelocardozo ? Me ajude estou precisando implementar. Como vc implementou ?

@lhermoso
Copy link

lhermoso commented Jan 23, 2025

hello, btw any of you have heard about this?

https://i.instagram.com/api/v1/stories/private stories/bulk update members/.

I got this from a paid service that is succefully adding more than 9999.

It was not possible to add users to the Close Friends list at this time. We will try again. Instagram server response: Network: CURL error 28: Operation timed out after 60001 milliseconds with 0 bytes received (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://i.instagram.com/api/v1/stories/private stories/bulk update_members/.

It halted for while and restarted, I have 52k followers and it added 10k until now. Once is completed I will post here. Looks like he is using a different approach, like emulating via website, not api.

Image

@lhermoso
Copy link

I’m Brazilian, and I have to say I’m ashamed of how some Brazilian developers operate.

They join an open-source community only to try and sell an API endpoint they found.

For example, Waldir, one of the devs asking here (@lhermoso any news on that?), sent me a message on Instagram. Meanwhile, another, marcelocardozo, seemed desperate to push this by messaging me, saying, "please email me."

Shame on you, guys! I have no issue with people selling things, but if you want to do that, build a small website, promote it on Instagram, or whatever—I don’t care. But this is definitely not the place for it.


I found a way to bypass the "max besties exceeded" restriction!

The key is to add besties through an endpoint that appears when creating a story.

Right after creating a story, tap the right arrow, then select Best Friends. This opens a new screen where you can edit the besties list. The endpoint used here seems to have no restrictions.

I’ll dive deeper into this over the weekend.

@marcelocardozo
Copy link

I’m Brazilian, and I have to say I’m ashamed of how some Brazilian developers operate.

They join an open-source community only to try and sell an API endpoint they found.

For example, Waldir, one of the devs asking here (@lhermoso any news on that?), sent me a message on Instagram. Meanwhile, another, marcelocardozo, seemed desperate to push this by messaging me, saying, "please email me."

Shame on you, guys! I have no issue with people selling things, but if you want to do that, build a small website, promote it on Instagram, or whatever—I don’t care. But this is definitely not the place for it.

I found a way to bypass the "max besties exceeded" restriction!

The key is to add besties through an endpoint that appears when creating a story.

Right after creating a story, tap the right arrow, then select Best Friends. This opens a new screen where you can edit the besties list. The endpoint used here seems to have no restrictions.

I’ll dive deeper into this over the weekend.

Be quiet. You sell courses promising wealth, and your opinion on the bypass is wrong; that’s not the right path.

@hamza08003
Copy link
Author

hamza08003 commented Jan 29, 2025

I’m Brazilian, and I have to say I’m ashamed of how some Brazilian developers operate.

They join an open-source community only to try and sell an API endpoint they found.

For example, Waldir, one of the devs asking here (@lhermoso any news on that?), sent me a message on Instagram. Meanwhile, another, marcelocardozo, seemed desperate to push this by messaging me, saying, "please email me."

Shame on you, guys! I have no issue with people selling things, but if you want to do that, build a small website, promote it on Instagram, or whatever—I don’t care. But this is definitely not the place for it.

I found a way to bypass the "max besties exceeded" restriction!

The key is to add besties through an endpoint that appears when creating a story.

Right after creating a story, tap the right arrow, then select Best Friends. This opens a new screen where you can edit the besties list. The endpoint used here seems to have no restrictions.

I’ll dive deeper into this over the weekend.

Absolutely agree with you on this. It's frustrating when people come into these open-source communities just to try and sell their stuff.

I've also seen guys in the discussins claiming they have API endpoints, but when you ask about them, they say they’re private and can’t be accessed unless you DM them. And when you do, they tell you to purchase them even though you dont know if they work or not —lol, it's so ridiculous!

There is this one guy everywhere in the
comments doing such thing I don't wanna mention him 😬

Anyway, what you discovered seems really cool. I’m gonna also check it 🫠

@guilhermecugler
Copy link

@lhermoso @hamza08003 @DoubleTroubleOf

I'm doing some research and found some endpoints from both the app and the web.

Web Endpoint

data = {
    'variables': f'{{"add":[],"remove":"[12345678, 987654321]","source":"profile"}}',
    'server_timestamps': 'true',
    'doc_id': '7489805084467496',
}

response = requests.post(
    'https://www.instagram.com/graphql/query', 
    cookies=cookies, 
    headers=headers, 
    data=data
)

App Endpoint

data = {
    'module': 'audience_selection',
    'source': 'story_share_shortcut',
    'user_id': user_id,
    '_uuid': '8c1bcc90-1663-436a-a4c4-5d8d39c6ce2c',
}

response = requests.post(
    'https://i.instagram.com/api/v1/stories/private_stories/add_member/', 
    headers=headers, 
    data=data
)

@cavepro98
Copy link

I’m Brazilian, and I have to say I’m ashamed of how some Brazilian developers operate.

They join an open-source community only to try and sell an API endpoint they found.

For example, Waldir, one of the devs asking here (@lhermoso any news on that?), sent me a message on Instagram. Meanwhile, another, marcelocardozo, seemed desperate to push this by messaging me, saying, "please email me."

Shame on you, guys! I have no issue with people selling things, but if you want to do that, build a small website, promote it on Instagram, or whatever—I don’t care. But this is definitely not the place for it.

I found a way to bypass the "max besties exceeded" restriction!

The key is to add besties through an endpoint that appears when creating a story.

Right after creating a story, tap the right arrow, then select Best Friends. This opens a new screen where you can edit the besties list. The endpoint used here seems to have no restrictions.

I’ll dive deeper into this over the weekend.

I believe that these types of guys go hungry at home trying to sell something that is free

@cavepro98
Copy link

cavepro98 commented Feb 8, 2025

Did you manage to find a solution? @hamza08003

@pedro123456789-wq
Copy link

@guilhermecugler can you share the headers structure and how do you sniff the requests on mobile?

@guilhermecugler
Copy link

@guilhermecugler can you share the headers structure and how do you sniff the requests on mobile?

You can use something like that:

     headers = {
                      'accept': '*/*',
                      'cookie': f'ds_user_id={self.loaded_session["user_id"]}; '
                       f'csrftoken={self.loaded_session["cookies"]["csrftoken"]}; '
                       f'sessionid={self.loaded_session["cookies"]["sessionid"]}',
                      'x-csrftoken': self.loaded_session["cookies"]["csrftoken"],
                      'x-ig-app-id': '936619743392459',
                }

The cookies can be from instagram web.

@pedro123456789-wq
Copy link

@guilhermecugler Muito obrigado 🙏

@pedro123456789-wq
Copy link

pedro123456789-wq commented Feb 12, 2025

@guilhermecugler

To extract the follower ids, I am getting blocked after like 12,000

Here is the code:

import requests
import time
import random
import logging

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("instagram_followers.log"),
        logging.StreamHandler()
    ]
)

BASE_URL = "https://www.instagram.com/api/v1/friendships"
USERNAME = ""
COOKIES = ""

# Extract necessary values from cookies
try:
    MAIN_USER_ID = next((item.split('=')[1] for item in COOKIES.split('; ') if item.startswith('ds_user_id=')), None)
    X_CSRFTOKEN = next((item.split('=')[1] for item in COOKIES.split('; ') if item.startswith('csrftoken=')), None)
    SESSION_ID = next((item.split('=')[1] for item in COOKIES.split('; ') if item.startswith('sessionid=')), None)
except Exception as e:
    logging.error(f"Error extracting authentication details: {e}")
    exit(1)

if not MAIN_USER_ID or not X_CSRFTOKEN or not SESSION_ID:
    logging.error("Missing required authentication cookies. Check COOKIES value.")
    exit(1)

url = f"https://i.instagram.com/api/v1/friendships/{MAIN_USER_ID}/followers/"
headers = {
    "User-Agent": "Instagram 261.0.0.21.111 Android",
    "Content-Type": "application/x-www-form-urlencoded",
    "Cookie": f"sessionid={SESSION_ID}; csrftoken={X_CSRFTOKEN}",
}
params = {
    "search_surface": "follow_list_page",
    "_csrftoken": X_CSRFTOKEN,
    "count": "50",
}
max_id = None

total_followers_fetched = 0

logging.info("Starting follower retrieval...")
while True:
    if max_id:
        params["max_id"] = max_id
    
    try:
        response = requests.get(url, headers=headers, params=params, timeout=10)
        response.raise_for_status()
    except requests.RequestException as e:
        logging.error(f"Request failed: {e}")
        break
    
    json_data = response.json()
    followers = json_data.get("users", [])
    next_max_id = json_data.get("next_max_id")  # For pagination
    
    if not followers:
        logging.info("No more followers found.")
        break
    
    follower_ids = [f['id'] for f in followers]
    total_followers_fetched += len(follower_ids)
    
    logging.info(f"Retrieved {len(follower_ids)} new followers. Total so far: {total_followers_fetched}")
    logging.info(f"Next max_id: {next_max_id}")
    
    with open(f"followers_{USERNAME}.txt", "a") as f:
        for fid in follower_ids:
            f.write(fid + '\n')
    
    if next_max_id:
        max_id = next_max_id
        time.sleep(random.uniform(3, 4))
    else:
        logging.info("Finished retrieving all followers.")
        break

Do you have any ideas on how to avoid getting blocked?

@guilhermecugler
Copy link

@guilhermecugler

To extract the follower ids, I am getting blocked after like 12,000

Here is the code:

import requests
import time
import random
import logging

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("instagram_followers.log"),
        logging.StreamHandler()
    ]
)

BASE_URL = "https://www.instagram.com/api/v1/friendships"
USERNAME = ""
COOKIES = ""

# Extract necessary values from cookies
try:
    MAIN_USER_ID = next((item.split('=')[1] for item in COOKIES.split('; ') if item.startswith('ds_user_id=')), None)
    X_CSRFTOKEN = next((item.split('=')[1] for item in COOKIES.split('; ') if item.startswith('csrftoken=')), None)
    SESSION_ID = next((item.split('=')[1] for item in COOKIES.split('; ') if item.startswith('sessionid=')), None)
except Exception as e:
    logging.error(f"Error extracting authentication details: {e}")
    exit(1)

if not MAIN_USER_ID or not X_CSRFTOKEN or not SESSION_ID:
    logging.error("Missing required authentication cookies. Check COOKIES value.")
    exit(1)

url = f"https://i.instagram.com/api/v1/friendships/{MAIN_USER_ID}/followers/"
headers = {
    "User-Agent": "Instagram 261.0.0.21.111 Android",
    "Content-Type": "application/x-www-form-urlencoded",
    "Cookie": f"sessionid={SESSION_ID}; csrftoken={X_CSRFTOKEN}",
}
params = {
    "search_surface": "follow_list_page",
    "_csrftoken": X_CSRFTOKEN,
    "count": "50",
}
max_id = None

total_followers_fetched = 0

logging.info("Starting follower retrieval...")
while True:
    if max_id:
        params["max_id"] = max_id
    
    try:
        response = requests.get(url, headers=headers, params=params, timeout=10)
        response.raise_for_status()
    except requests.RequestException as e:
        logging.error(f"Request failed: {e}")
        break
    
    json_data = response.json()
    followers = json_data.get("users", [])
    next_max_id = json_data.get("next_max_id")  # For pagination
    
    if not followers:
        logging.info("No more followers found.")
        break
    
    follower_ids = [f['id'] for f in followers]
    total_followers_fetched += len(follower_ids)
    
    logging.info(f"Retrieved {len(follower_ids)} new followers. Total so far: {total_followers_fetched}")
    logging.info(f"Next max_id: {next_max_id}")
    
    with open(f"followers_{USERNAME}.txt", "a") as f:
        for fid in follower_ids:
            f.write(fid + '\n')
    
    if next_max_id:
        max_id = next_max_id
        time.sleep(random.uniform(3, 4))
    else:
        logging.info("Finished retrieving all followers.")
        break

Do you have any ideas on how to avoid getting blocked?

You can try using this api bellow, im still researching but have no time lately, so i didnt test the limits, but with only 1 request you can have 500+ ids:

    def get_id_list(self, sessionid, csrftoken, user_id):
        headers = {
            'cookie': f'ds_user_id={user_id}; csrftoken={csrftoken}; sessionid={sessionid}',
            'x-csrftoken': csrftoken,
            'x-ig-app-id': '936619743392459',
            'x-requested-with': 'XMLHttpRequest',
        }
        data = {
            'locale': 'pt_BR',
            'vc_policy': 'ADS',
            'signed_body': 'SIGNATURE.',
            'variables': '{"views":["BFF"]}',
            'strip_nulls': 'true',
            'client_doc_id': '385348296418235549120349460364',
            'strip_defaults': 'true',
        }
        response = requests.post('https://i.instagram.com/api/v1/wwwgraphql/ig/query/', headers=headers, data=data, verify=False)
        user_ids = response.json().get("data", {}).get("get_ig_banyan_ranking_query", {}).get("entities", {}).get("ig_users", [])
        user_ids = [user["instagram_user_id"] for user in user_ids]
        
        with open(self.id_list_file, "w") as file:
            json.dump(user_ids, file, indent=4)

        return user_ids

@pedro123456789-wq
Copy link

@guilhermecugler WOW, thanks

What do you use for the research if you don't mind me asking

@guilhermecugler
Copy link

@

Its kinda complex but basically, i use and android emulator + burp suite to intercept requests from an ssl bypassed instagram modified app with the proxy from burp, then I make actions on tha app and analyze the requests...

@pedro123456789-wq
Copy link

@guilhermecugler How did you get the signature? Do you have instagram's private key?

@cavepro98
Copy link

@guilhermecugler
If it's not a problem, can you tell me how I can get the number of followers they are adding to close friends? I tried monitoring requests from the Instagram app but without success.
Image

@guilhermecugler
Copy link

@guilhermecugler How did you get the signature? Do you have instagram's private key?

No need, you leave just: 'signed_body': 'SIGNATURE.'

@pedro123456789-wq
Copy link

@guilhermecugler Ok, but I'm getting this error: {"errors":[{"message":"Unauthorized logged out query.","severity":"CRITICAL","code":1675002}],"extensions":{"is_final":true}}

@pedro123456789-wq
Copy link

Do you have a solution?

@pedro123456789-wq
Copy link

@guilhermecugler I used your method to sniff mobile packets and found a solution. Thanks a lot.
Just a final question, have you found the rate limit for this endpoint: https://i.instagram.com/api/v1/stories/private_stories/add_member/

@guilhermecugler
Copy link

@guilhermecugler Ok, but I'm getting this error: {"errors":[{"message":"Unauthorized logged out query.","severity":"CRITICAL","code":1675002}],"extensions":{"is_final":true}}

you need user_id, csrftoken and sessionid correctly in the headers, you can use cookies from instagram web

@marcelocardozo
Copy link

Image

Running here without any problems.

@guilhermecugler
Copy link

I will publish a new open-source repository with the best API for bulk adding/removing close friends with the best possible performance.

@guilhermecugler
Copy link

I am providing an open-source repository with software to add/remove close friends. Here is the link: InstagramCloseFriendsManagerPython

@cavepro98
Copy link

@guilhermecugler You did the right thing, but anyone who wants to pass on your project and profit from it will be huge 😅

@guilhermecugler
Copy link

@guilhermecugler You did the right thing, but anyone who wants to pass on your project and profit from it will be huge 😅

Yeah... but I don't care. I only did it for my studies.

@cavepro98
Copy link

@guilhermecugler
I took a look at your version in Python, I'm trying to do it in Node Js, but for some reason the error

my node version

const axios = require('axios');

async function bulkUpdateMembers(session, userIds, operation) {
    const headers = {
        'accept': '*/*',
        'cookie': `ds_user_id=${session.user_id}; csrftoken=${session.cookies.csrftoken}; sessionid=${session.cookies.sessionid}`,
        'x-csrftoken': session.cookies.csrftoken,
        'x-ig-app-id': '936619743392459',
    };

    const data = {
        module: 'audience_selection',
    };
    data[operation === 'add' ? 'added_user_ids' : 'removed_user_ids'] = JSON.stringify(userIds);

    console.log('Headers:', headers);
    console.log('Data:', data);

    try {
        const response = await axios.post(
            'https://i.instagram.com/api/v1/stories/private_stories/bulk_update_members/',
            data,
            { headers }
        );
        console.log(`Status code: ${response.status}`);
        if (response.status === 200) {
            console.log('Batch processed successfully');
        } else {
            console.log(`Error: ${response.data}`);
        }
    } catch (error) {
        console.error(`Critical error: ${error.message}`);
        if (error.response) {
            console.error('Response data:', error.response.data);
            console.error('Response status:', error.response.status);
            console.error('Response headers:', error.response.headers);
        }
    }
}

// Exemplo de uso
const session = {
    user_id: '******',
    cookies: {
        csrftoken: '******',
        sessionid: '******',
    },
};

const userIds = ['68281086668']; // IDs dos usuários a serem adicionados ou removidos
const operation = 'add'; // ou 'remove'

bulkUpdateMembers(session, userIds, operation);

response

Critical error: Request failed with status code 500
Response data: Oops, an error occurred.

Response status: 500

@guilhermecugler
Copy link

@guilhermecugler I took a look at your version in Python, I'm trying to do it in Node Js, but for some reason the error

my node version

const axios = require('axios');

async function bulkUpdateMembers(session, userIds, operation) {
    const headers = {
        'accept': '*/*',
        'cookie': `ds_user_id=${session.user_id}; csrftoken=${session.cookies.csrftoken}; sessionid=${session.cookies.sessionid}`,
        'x-csrftoken': session.cookies.csrftoken,
        'x-ig-app-id': '936619743392459',
    };

    const data = {
        module: 'audience_selection',
    };
    data[operation === 'add' ? 'added_user_ids' : 'removed_user_ids'] = JSON.stringify(userIds);

    console.log('Headers:', headers);
    console.log('Data:', data);

    try {
        const response = await axios.post(
            'https://i.instagram.com/api/v1/stories/private_stories/bulk_update_members/',
            data,
            { headers }
        );
        console.log(`Status code: ${response.status}`);
        if (response.status === 200) {
            console.log('Batch processed successfully');
        } else {
            console.log(`Error: ${response.data}`);
        }
    } catch (error) {
        console.error(`Critical error: ${error.message}`);
        if (error.response) {
            console.error('Response data:', error.response.data);
            console.error('Response status:', error.response.status);
            console.error('Response headers:', error.response.headers);
        }
    }
}

// Exemplo de uso
const session = {
    user_id: '******',
    cookies: {
        csrftoken: '******',
        sessionid: '******',
    },
};

const userIds = ['68281086668']; // IDs dos usuários a serem adicionados ou removidos
const operation = 'add'; // ou 'remove'

bulkUpdateMembers(session, userIds, operation);

response

Critical error: Request failed with status code 500
Response data: Oops, an error occurred.

Response status: 500

change from "{ headers }" to "headers" in line 23:

        const response = await axios.post(
            'https://i.instagram.com/api/v1/stories/private_stories/bulk_update_members/',
            data,
            headers //Mude de { headers } para headers
        );

@cavepro98
Copy link

@guilhermecugler thank you friend

@cavepro98
Copy link

cavepro98 commented Feb 17, 2025

@guilhermecugler
unfortunately, even with this api that you kept appearing, the Max besties exceeded it after a while : (

more generally this limit is very random here I am testing on an account with 8750 followers the problem starts when it reaches more or less when 7500 were added

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug unconfirmed This issue hasn't been read/confirmed/accepted by an admin
Projects
None yet
Development

No branches or pull requests

10 participants