subzeroid / instagrapi

🔥 The fastest and powerful Python library for Instagram Private API 2024
https://hikerapi.com/p/bkXQlaVe
MIT License
4.32k stars 684 forks source link

Signup function gets interrupted by Instagram #1999

Open Altimis opened 2 months ago

Altimis commented 2 months ago

Hi Community. I was able to use the signup method to create new account using the following code :

   def signup(self, email, password, email_password, username, display_name, phone_number, proxy):
        self.email = email
        self.email_password = email_password
        self.number = phone_number
        self.reset_client()  # Reset the Client object before each login attempt

        proxy_str = f"http://{proxy['username']}:{proxy['password']}@{proxy['ip']}:{proxy['port']}"
        logging.info(f"Setting proxy: {proxy_str} for {username}")
        self.cl.set_proxy(proxy_str)
        self.cl.set_settings({})

        device_settings = self.generate_device_settings_signup()
        logging.info(f"generated device settings : {device_settings}")

        user_agent = self.generate_user_agent_signup(device_settings)
        logging.info(f"generated user agent {user_agent}")

        # Generate consistent device ID
        device_id = self.generate_device_id_signup(device_settings)
        logging.info(f"generated device ID : {device_id}")

        # Generate phone ID
        phone_id = self.generate_phone_id_signup(device_settings)
        logging.info(f"generated phone ID : {phone_id}")

        # Set device settings, including the device ID
        device_settings['device_id'] = device_id
        self.cl.device_id = device_id
        self.cl.phone_id = phone_id

        self.cl.set_device(device_settings)
        self.cl.set_user_agent(user_agent)

        user = self.cl.signup(
            username, password, email, phone_number, display_name,
            year=random.randint(1970, 2004),
            month=random.randint(1, 12),
            day=random.randint(1, 28)
        )

        return user

The code is able to do the first steps :

2024-08-09 11:34:30,856:https://i.instagram.com/api/v1/consent/get_signup_config/
2024-08-09 11:34:31,949:None [200] GET https://i.instagram.com/api/v1/consent/get_signup_config/?guid=760f13e6-6a01-4c00-9a82-6a047784477b&main_account_selected=False (269.0.0.18.75, OnePlus 6T Dev)
2024-08-09 11:35:24,116:https://i.instagram.com/api/v1/users/check_email/
2024-08-09 11:35:25,542:None [200] POST https://i.instagram.com/api/v1/users/check_email/ (269.0.0.18.75, OnePlus 6T Dev)
2024-08-09 11:36:18,368:https://i.instagram.com/api/v1/accounts/send_verify_email/
2024-08-09 11:36:19,712:None [200] POST https://i.instagram.com/api/v1/accounts/send_verify_email/ (269.0.0.18.75, OnePlus 6T Dev)
Enter code "125049" for mr_fox_elite (1 attempts, by 5 seconds)
2024-08-09 11:38:31,680:https://i.instagram.com/api/v1/accounts/check_confirmation_code/
2024-08-09 11:38:33,961:None [200] POST https://i.instagram.com/api/v1/accounts/check_confirmation_code/ (269.0.0.18.75, OnePlus 6T Dev)
2024-08-09 11:39:22,228:https://www.instagram.com/api/v1/accounts/create/
2024-08-09 11:39:35,403:None [200] POST https://www.instagram.com/api/v1/accounts/create/ (269.0.0.18.75, OnePlus 6T Dev)

But unfortunayly, it doesn't succeed to finishing the account creation as it returns an Instagram User for the username, which means that the account was banned once it was created duo to terms violation :

pk='68137002822' username='Instagram User' full_name='' profile_pic_url=Url('https://instagram.fsal14-1.fna.fbcdn.net/v/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?_nc_ht=instagram.fsal14-1.fna.fbcdn.net&_nc_cat=1&_nc_ohc=nOPs76iqbjsQ7kNvgFr6zCl&edm=AP7HCqgBAAAA&ccb=7-5&ig_cache_key=YW5vbnltb3VzX3Byb2ZpbGVfcGlj.2-ccb7-5&oh=00_AYCdwEtQrhfXGWGrvlchqm4qYBg5uusjeaWUYYM8SwzBjg&oe=66BC130F&_nc_sid=b09b61') profile_pic_url_hd=None is_private=True

I'm using strong ISP proxies from Rayobyte provider. The generation of device settings and user agent is required here to be used in the account forever after the creation. Here are the functions responsible for generating these settings :

    def generate_user_agent_signup(self, device_settings):
        user_agent_template = (
            "Instagram {app_version} Android ({android_version}/{android_release}; "
            "{dpi}; {resolution}; {manufacturer}; {model}; {device}; {cpu}; en_US; {version_code})"
        )
        user_agent = user_agent_template.format(**device_settings)
        return user_agent

    def generate_device_settings_signup(self):
        android_versions = [
            (26, "8.0.0"), (27, "8.1.0"), (28, "9"), (29, "10"), (30, "11"), (31, "12")
        ]
        devices = [
            ("OnePlus", "OnePlus", "6T Dev", "devitron"),
            ("Samsung", "Samsung", "Galaxy S10", "beyond1"),
            ("Google", "Google", "Pixel 4", "flame"),
            ("Xiaomi", "Xiaomi", "Mi 9", "cepheus"),
            ("Huawei", "Huawei", "P30 Pro", "vogue")
        ]
        cpu_types = ["qcom", "exynos", "kirin"]

        android_version, android_release = random.choice(android_versions)
        manufacturer, brand, model, device = random.choice(devices)
        cpu = random.choice(cpu_types)
        dpi = "480dpi"
        resolution = "1080x1920"
        app_version = "269.0.0.18.75"
        version_code = "314665256"

        device_settings = {
            "app_version": app_version,
            "android_version": android_version,
            "android_release": android_release,
            "dpi": dpi,
            "resolution": resolution,
            "manufacturer": manufacturer,
            "device": device,
            "model": model,
            "cpu": cpu,
            "version_code": version_code
        }

        return device_settings

    def generate_device_id_signup(self, device_settings):
        device_info = f"{device_settings['manufacturer']}_{device_settings['model']}_{device_settings['android_version']}"
        hash_object = hashlib.md5(device_info.encode())
        return f"android-{hash_object.hexdigest()[:16]}"

    def generate_phone_id_signup(self, device_settings):
        device_info = f"{device_settings['manufacturer']}_{device_settings['model']}_{device_settings['android_version']}"
        hash_object = hashlib.sha256(device_info.encode())
        return str(uuid.UUID(hash_object.hexdigest()[:32]))

I hope there is a solution to fix this. Thank you in advance.

Altimis commented 2 months ago

Now I got this error :

2024-08-09 13:51:14,141:https://i.instagram.com/api/v1/accounts/check_confirmation_code/
2024-08-09 13:51:16,733:None [200] POST https://i.instagram.com/api/v1/accounts/check_confirmation_code/ (269.0.0.18.75, Google Pixel 4)
2024-08-09 13:52:06,925:https://www.instagram.com/api/v1/accounts/create/
2024-08-09 13:52:08,642:None [200] POST https://www.instagram.com/api/v1/accounts/create/ (269.0.0.18.75, Google Pixel 4)
Traceback (most recent call last):
  File "/home/yassine/Documents/work/IgAccountUnblockingAPIs/signup.py", line 213, in <module>
    instabot.signup(email, password, password, username,
  File "/home/yassine/Documents/work/IgAccountUnblockingAPIs/utils.py", line 2261, in signup
    user = self.cl.signup(
  File "/home/yassine/anaconda3/envs/ig_bot/lib/python3.10/site-packages/instagrapi/mixins/signup.py", line 65, in signup
    return extract_user_short(data["created_user"])
KeyError: 'created_user'
sujay1599 commented 2 months ago

Try

The code your friend is using appears to be mostly correct, but there are a few areas where issues might arise, particularly regarding the signup process with Instagram’s API. Here are some suggestions to troubleshoot and potentially resolve the error:

  1. Device ID Generation

    • The device_id is being generated manually, but it’s important that this ID is consistent and realistic. Ensure that the format and content of the device_id match what Instagram expects. If it’s not correctly formed, Instagram might reject the request.

  2. Password Encryption

    • Although the password is provided in plain text, Instagram’s API typically requires an encrypted password during signup. The Client class should handle this automatically, but double-check that the password is being encrypted correctly.

If the signup method doesn’t handle password encryption internally, ensure that it’s encrypted using the password_encrypt method from the Client class before passing it to the signup method.

encrypted_password = client.password_encrypt(password)

  1. Proxy Issues

    • The use of a SOCKS5 proxy can sometimes cause issues, especially if Instagram flags the proxy IP as suspicious. Try running the code without the proxy to see if the issue persists.

  2. Ensure Required Headers and User-Agent

    • Instagram’s API expects certain headers, including a User-Agent that mimics a legitimate request from an Instagram app. Ensure that your Client class sets these headers correctly.

client.set_user_agent("Instagram 123.0.0.20.114 Android (28/9; 320dpi; 720x1280; Xiaomi; HM 1SW; armani; qcom; en_US)")

  1. Handle Two-Factor Authentication (2FA)

    • If the phone number is associated with an account that has 2FA enabled, Instagram might require additional steps, such as entering a verification code. Ensure that the code handles any such requests.

  2. Rate Limiting

    • Instagram enforces strict rate limits, especially for account creation. If your friend has been trying this multiple times in quick succession, it’s possible that Instagram has temporarily blocked further attempts from the current IP or account. Waiting for a while or switching to a different IP address might resolve this.

  3. Check for API Changes

    • Instagram frequently updates its API, which can sometimes lead to breaking changes. Make sure the instagrapi library is up-to-date and check if there are any recent changes in the way account creation requests should be made.

Suggested Changes to the Code:

import hashlib import time import random from instagrapi import Client

client = Client() client.delay_range = [1, 3]

Optional: Set User-Agent if not handled by Client

client.set_user_agent("Instagram 123.0.0.20.114 Android (28/9; 320dpi; 720x1280; Xiaomi; HM 1SW; armani; qcom; en_US)")

Set proxy if necessary

client.set_proxy('socks5://...')

Generate and set device_id

client.device_id = "android-%s" % hashlib.sha256(str(time.time()).encode()).hexdigest()[:16]

email = 'example@gmail.com' display_name = 'John Smith' username = 'jsmith123512' password = 'can389maw39mxruaj' phone_number = '+15559202020'

Encrypt the password if required

encrypted_password = client.password_encrypt(password)

try: user = client.signup( username, encrypted_password, email, phone_number, display_name, year=random.randint(1970, 2004), month=random.randint(1, 12), day=random.randint(1, 28) ) print("Account created successfully:", user) except Exception as e: print("Error creating account:", e)

If Problems Persist:

If the error continues even after these changes, it might be worth debugging further by inspecting the exact request and response being sent to Instagram’s API, potentially using a tool like Fiddler or Wireshark to capture the traffic and see what might be causing the 400 Bad Request error.

sujay1599 commented 2 months ago

Suggested Changes to the Code:

import hashlib import time import random from instagrapi import Client

client = Client() client.delay_range = [1, 3]

Optional: Set User-Agent if not handled by Client

client.set_user_agent("Instagram 123.0.0.20.114 Android (28/9; 320dpi; 720x1280; Xiaomi; HM 1SW; armani; qcom; en_US)")

Set proxy if necessary

client.set_proxy('socks5://...')

Generate and set device_id

client.device_id = "android-%s" % hashlib.sha256(str(time.time()).encode()).hexdigest()[:16]

email = 'example@gmail.com' display_name = 'John Smith' username = 'jsmith123512' password = 'can389maw39mxruaj' phone_number = '+15559202020'

Encrypt the password if required

encrypted_password = client.password_encrypt(password)

try: user = client.signup( username, encrypted_password, email, phone_number, display_name, year=random.randint(1970, 2004), month=random.randint(1, 12), day=random.randint(1, 28) ) print("Account created successfully:", user) except Exception as e: print("Error creating account:", e)

sujay1599 commented 2 months ago

But just know not detection is very good

The issue where the account is immediately banned upon creation, resulting in the username='Instagram User', is a common problem when creating accounts programmatically on platforms like Instagram. This typically happens due to Instagram's strict anti-bot and anti-spam measures. Here are a few strategies to troubleshoot and possibly avoid this issue:

1. Proxy Quality and IP Reputation

2. Human-like Behavior

3. Account Warm-up

4. Device and User-Agent Configuration

5. Session Management

6. Email and Phone Number Validation

7. Consider API Changes or Blockages

8. Advanced Techniques

Example Modifications:

Here’s how you might modify the code to improve its chances of success:

def signup(self, email, password, email_password, username, display_name, phone_number, proxy):
    self.email = email
    self.email_password = email_password
    self.number = phone_number
    self.reset_client()  # Reset the Client object before each login attempt

    proxy_str = f"http://{proxy['username']}:{proxy['password']}@{proxy['ip']}:{proxy['port']}"
    logging.info(f"Setting proxy: {proxy_str} for {username}")
    self.cl.set_proxy(proxy_str)
    self.cl.set_settings({})

    device_settings = self.generate_device_settings_signup()
    logging.info(f"generated device settings : {device_settings}")

    user_agent = self.generate_user_agent_signup(device_settings)
    logging.info(f"generated user agent {user_agent}")

    # Generate consistent device ID
    device_id = self.generate_device_id_signup(device_settings)
    logging.info(f"generated device ID : {device_id}")

    # Generate phone ID
    phone_id = self.generate_phone_id_signup(device_settings)
    logging.info(f"generated phone ID : {phone_id}")

    # Set device settings, including the device ID
    device_settings['device_id'] = device_id
    self.cl.device_id = device_id
    self.cl.phone_id = phone_id

    self.cl.set_device(device_settings)
    self.cl.set_user_agent(user_agent)

    # Introduce random delay to simulate human behavior
    time.sleep(random.uniform(5, 15))

    try:
        user = self.cl.signup(
            username, password, email, phone_number, display_name,
            year=random.randint(1970, 2004),
            month=random.randint(1, 12),
            day=random.randint(1, 28)
        )

        logging.info("Account created, initiating warm-up activities...")
        # Perform warm-up activities to reduce chances of ban
        self.cl.account_set_private(False)  # Set the account to public
        time.sleep(random.uniform(5, 15))
        self.cl.account_set_biography("New to Instagram, exploring the platform!")
        time.sleep(random.uniform(5, 15))
        self.cl.account_change_picture("path_to_profile_picture.jpg")
        time.sleep(random.uniform(5, 15))
        # Optional: Interact with the platform to warm up the account
        self.cl.media_like('some_media_id')

    except Exception as e:
        logging.error(f"Error creating account: {e}")
        return None

    return user

Conclusion:

By incorporating more randomness, engaging in warm-up activities, and ensuring realistic settings and behaviors, you can improve the chances of successfully creating an Instagram account without it being immediately banned. However, Instagram’s anti-bot measures are very sophisticated, so there's no guarantee, especially if many accounts are being created programmatically.

sujay1599 commented 2 months ago

Lastly update ur def to be more real something like:

Here’s a working version of the functions with added realism and variability:

import hashlib
import random
import uuid

class InstagramSignupHelper:
    def generate_user_agent_signup(self, device_settings):
        locales = ["en_US", "en_GB", "en_CA", "es_ES", "fr_FR"]  # Various locales
        locale = random.choice(locales)

        # Add a random build number or incremental version to the Android release
        build_number = f"{random.randint(100000, 999999)}"
        user_agent_template = (
            "Instagram {app_version} Android ({android_version}/{android_release}.{build_number}; "
            "{dpi}; {resolution}; {manufacturer}; {model}; {device}; {cpu}; {locale}; {version_code})"
        )
        user_agent = user_agent_template.format(
            build_number=build_number, 
            locale=locale, 
            **device_settings
        )
        return user_agent

    def generate_device_settings_signup(self):
        android_versions = [
            (26, "8.0.0"), (27, "8.1.0"), (28, "9.0.1"), (29, "10.0.1"), (30, "11.0.3"), (31, "12.1.2")
        ]
        devices = [
            ("OnePlus", "OnePlus", "6T Dev", "devitron", "1080x2280", "420dpi"),
            ("Samsung", "Samsung", "Galaxy S10", "beyond1", "1440x3040", "550dpi"),
            ("Google", "Google", "Pixel 4", "flame", "1080x2280", "443dpi"),
            ("Xiaomi", "Xiaomi", "Mi 9", "cepheus", "1080x2340", "403dpi"),
            ("Huawei", "Huawei", "P30 Pro", "vogue", "1080x2340", "398dpi"),
            # Add more devices with varied screen resolutions and DPIs
        ]
        cpu_types = ["qcom", "exynos", "kirin", "mtk"]  # Including Mediatek (mtk)

        android_version, android_release = random.choice(android_versions)
        manufacturer, brand, model, device, resolution, dpi = random.choice(devices)
        cpu = random.choice(cpu_types)
        app_version = "269.0.0.18.75"
        version_code = "314665256"

        device_settings = {
            "app_version": app_version,
            "android_version": android_version,
            "android_release": android_release,
            "dpi": dpi,
            "resolution": resolution,
            "manufacturer": manufacturer,
            "device": device,
            "model": model,
            "cpu": cpu,
            "version_code": version_code
        }

        return device_settings

    def generate_device_id_signup(self, device_settings):
        device_info = (
            f"{device_settings['manufacturer']}_{device_settings['model']}_"
            f"{device_settings['device']}_{device_settings['android_version']}_"
            f"{device_settings['android_release']}_{random.randint(1000, 9999)}"
        )
        hash_object = hashlib.md5(device_info.encode())
        return f"android-{hash_object.hexdigest()[:16]}"

    def generate_phone_id_signup(self, device_settings):
        device_info = (
            f"{device_settings['manufacturer']}_{device_settings['model']}_"
            f"{device_settings['device']}_{device_settings['android_version']}_"
            f"{device_settings['android_release']}_{random.randint(1000, 9999)}"
        )
        hash_object = hashlib.sha256(device_info.encode())
        return str(uuid.UUID(hash_object.hexdigest()[:32]))

# Example usage
helper = InstagramSignupHelper()

# Generate realistic device settings
device_settings = helper.generate_device_settings_signup()
print("Device Settings:", device_settings)

# Generate user agent based on device settings
user_agent = helper.generate_user_agent_signup(device_settings)
print("User Agent:", user_agent)

# Generate device ID
device_id = helper.generate_device_id_signup(device_settings)
print("Device ID:", device_id)

# Generate phone ID
phone_id = helper.generate_phone_id_signup(device_settings)
print("Phone ID:", phone_id)

Explanation:

This setup should create more varied and realistic device and user agent configurations, which could help in reducing the chances of being detected as automated when interacting with Instagram's API.

Altimis commented 2 months ago

Still getting the same issue after all these recommendations (I've already used an LLM to suggest such improvements). Maybe the issue is related to the email I'm creating ? because I'm using an API to create an email (MailTM), or the proxy quality (ISP proxies from Rayobyte) ?

sujay1599 commented 2 months ago

Use my outlook email creator.

That might be the issue.

sujay1599 commented 2 months ago

How are you defining email? Curious.

sujay1599 commented 2 months ago

Add me as a friend on Discord! Invite expires in 1 week: https://discord.gg/hPTX2k7r

Altimis commented 2 months ago

@sujay1599 using MailTM : https://github.com/rpwnage/MailTMClient/tree/main

Altimis commented 2 months ago

Use my outlook email creator.

That might be the issue.

Can you provide me with a link please ?

sujay1599 commented 2 months ago

Outlook-Email-Creator/SOURCE - microsoft-account-creator-main at main · sujay1599/Outlook-Email-Creatorgithub.comSent from my iPhoneOn Aug 10, 2024, at 3:31 PM, Yassine Ait Jeddi @.***> wrote:

Use my outlook email creator. That might be the issue.

Can you provide me with a link please ?

—Reply to this email directly, view it on GitHub, or unsubscribe.You are receiving this because you were mentioned.Message ID: @.***>

Altimis commented 2 months ago

I tried signup using a gmail email as well. I got the same issue. I think the issue might be the proxy or the headers (it could be that the default headers are outdated or something). I tried signing up using a browser with one of my proxies but I did not succeed. So maybe the proxies are the main issue here even though they are ISPs. Do you know a good proxy provider for this use case ?

sunmasters commented 2 weeks ago

Mostly IP is the is issue. Try mobile proxy

jinijihui commented 1 week ago

在 Discord 上添加我为好友!邀请将于 1 周后到期:https ://discord.gg/hPTX2k7r

bro, Can you send me the invitation link again? I have a question for you.