instagrapi
instagrapi copied to clipboard
Signup function gets interrupted by Instagram
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.
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'
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:
-
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.
-
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)
-
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.
-
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)")
-
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.
-
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.
-
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 = '[email protected]' 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.
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 = '[email protected]' 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)
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
- Proxy Quality: Ensure that the SOCKS5 proxy being used has a good reputation and is not flagged by Instagram. Low-quality proxies or those associated with suspicious activities are often banned quickly by Instagram.
- Residential Proxies: Consider using residential proxies instead of datacenter proxies, as they are less likely to be flagged as bot-related.
- IP Rotation: If possible, rotate proxies/IPs to avoid being flagged for multiple requests from the same IP address.
2. Human-like Behavior
- Delays and Randomization: While your friend's code already includes a delay range, it might be beneficial to introduce more randomness in timing and behavior to better mimic human activity.
- Intermediate Actions: Between API calls, add actions that a typical user might perform, like viewing a few profiles, liking posts, or searching for hashtags. This can make the account creation process appear more natural.
- Time between Requests: Increase the time between requests, especially the final account creation step, to avoid triggering Instagram's spam detection systems.
3. Account Warm-up
- Initial Interaction: After account creation, engage in human-like activities such as following a few users, liking posts, or posting a story before the account is put to any significant use.
- Profile Completion: Immediately after account creation, update the profile with a bio, profile picture, and other details to make the account seem more legitimate.
4. Device and User-Agent Configuration
- Realistic User-Agent: Ensure that the user-agent string generated is realistic and matches the device settings. Any inconsistencies between the device information and user-agent can raise red flags.
- Realistic Device Settings: Ensure that the device settings generated (like the Android version, manufacturer, model, etc.) are consistent with real-world devices that Instagram expects to see.
5. Session Management
- Persistent Sessions: Ensure that the session is properly maintained across multiple actions. Resetting the session or changing device IDs during the process can lead to inconsistencies that might cause Instagram to ban the account.
6. Email and Phone Number Validation
- Email Quality: Ensure that the email used for registration is from a reputable provider and hasn't been used for suspicious activities. Disposable emails are often flagged and can lead to an account ban.
- Phone Number Validation: Ensure the phone number is valid, and consider using a real phone number service to receive verification codes.
7. Consider API Changes or Blockages
- Instagram often updates its API, and some endpoints might be blocked for bot-like activities. Check if there have been any recent updates to the Instagram API or the
instagrapilibrary that could impact account creation.
8. Advanced Techniques
- Machine Learning for Detection Avoidance: If you are creating many accounts, consider using machine learning to simulate more human-like behavior patterns, making it harder for Instagram's detection algorithms to flag your actions.
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.
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:
-
generate_user_agent_signup: This method now generates a user agent with a random locale and a build number appended to the Android release version, making the user agent more varied and realistic. -
generate_device_settings_signup: This method picks from a list of realistic device profiles, each with its own specific screen resolution and DPI. This adds more realism to the device settings. -
generate_device_id_signupandgenerate_phone_id_signup: These methods now generate device and phone IDs using a more complex combination of device attributes, making them more unique and harder to detect as fake.
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.
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) ?
Use my outlook email creator.
That might be the issue.
How are you defining email? Curious.
Add me as a friend on Discord! Invite expires in 1 week: https://discord.gg/hPTX2k7r
@sujay1599 using MailTM : https://github.com/rpwnage/MailTMClient/tree/main
Use my outlook email creator.
That might be the issue.
Can you provide me with a link please ?
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: @.***>
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 ?
Mostly IP is the is issue. Try mobile proxy
åØ Discord äøę·»å ę为儽åļ¼é请å°äŗ 1 åØåå°ęļ¼https ://discord.gg/hPTX2k7r
broļ¼ Can you send me the invitation link again? I have a question for you.
Add me as a friend on Discord! Invite expires in 1 week: https://discord.gg/hPTX2k7r
hi are you there