from instagrapi import Client
from instagrapi.exceptions import ChallengeRequired, ClientError
import time
import random
import os
from pathlib import Path
Kylie Jenner (@kyliejenner) - شخصية إعلامية ورائدة أعمال أمريكية.
تأكد من أن هذه الأرقام والمعلومات قد تتغير بمرور الوقت، لذا من الجيد التحقق منها بشكل دوري.
def load_session(self):
if Path(self.SESSION_FILE).exists():
try:
self.cl.load_settings(self.SESSION_FILE)
self.cl.get_timeline_feed()
self.username = self.cl.account_info().username
print("✅ تم استعادة الجلسة بنجاح!")
self.show_daily_stats()
return True
except Exception as e:
print(f"❌ الجلسة منتهية: {e}")
os.remove(self.SESSION_FILE)
return False
def save_session(self):
self.cl.dump_settings(self.SESSION_FILE)
print("🔒 تم حفظ الجلسة!")
def safe_login(self):
if self.load_session():
return
print("\n" + "="*30)
print("🎭 تسجيل الدخول إلى إنستجرام")
self.username = input("أدخل اسم المستخدم: ").strip()
password = input("أدخل كلمة المرور: ").strip()
try:
self.cl.login(self.username, password)
print(f"\n✅ تم تسجيل الدخول كـ {self.username} بنجاح!")
self.save_session()
self.show_daily_stats()
except ChallengeRequired:
self.handle_challenge()
except ClientError as e:
print(f"\n❌ خطأ في التسجيل: {e}")
exit()
def handle_challenge(self):
print("\n⚠️ يلزم تأكيد الهوية (تم إرسال رمز إلى بريدك أو رقم الهاتف)")
code = input("أدخل الرمز المكون من 6 أرقام: ").strip()
try:
self.cl.challenge_resolve(self.cl.last_json, code)
print("✅ تم تأكيد الهوية بنجاح!")
self.save_session()
self.show_daily_stats()
except Exception as e:
print(f"❌ فشل التأكيد: {e}")
exit()
def show_daily_stats(self):
print("\n" + "="*30)
print(f"📊 إحصائيات اليوم ({time.strftime('%Y-%m-%d')}):")
print(f"- الإجراءات المتبقية: {self.MAX_ACTIONS - self.actions_today}")
print(f"- الإجراءات المستخدمة: {self.actions_today}")
if self.actions_today >= self.MAX_ACTIONS * 0.8:
print("\n⚠️ اقتربت من الحد اليومي!")
def human_delay(self):
delay = random.uniform(*self.DELAY_RANGE)
print(f"\n⏳ انتظر {delay:.1f} ثانية...", end="", flush=True)
time.sleep(delay)
print("\r" + " "*30 + "\r", end="")
def interactive_menu(self):
while True:
print("\n" + "="*30)
print("📱 قائمة التحكم الرئيسية:")
print("1. التفاعل مع المنشورات")
print("2. متابعة الحسابات")
print("3. نشر محتوى")
print("4. الإحصائيات")
print("5. الخروج")
choice = input("\nاختر إجراء (1-5): ").strip()
if choice == "1":
self.run_interaction_flow()
elif choice == "2":
self.run_follow_flow()
elif choice == "3":
self.run_post_flow()
elif choice == "4":
self.show_daily_stats()
elif choice == "5":
self.cl.logout()
print("\n✅ تم تسجيل الخروج!")
exit()
else:
print("\n❌ خيار غير صحيح!")
def run_interaction_flow(self):
print("\n" + "="*30)
print("💬 تفاعل مع المنشورات")
hashtags = self.select_hashtags()
amount = self.get_number_input("عدد المنشورات (10-50): ", 10, 50)
self.engage_with_content(hashtags, amount)
def run_follow_flow(self):
print("\n" + "="*30)
print("👥 متابعة الحسابات")
hashtags = self.select_hashtags()
amount = self.get_number_input("عدد المتابعات (5-30): ", 5, 30)
self.smart_follow(hashtags, amount)
def run_post_flow(self):
print("\n" + "="*30)
print("📤 نشر محتوى جديد")
image_path = input("مسار الصورة: ").strip()
if not os.path.exists(image_path):
print("\n❌ الملف غير موجود!")
return
caption = input("وصف المنشور: ").strip()
hashtags = self.select_hashtags()
self.post_content(image_path, caption, hashtags)
def select_hashtags(self):
print("\n" + "-"*20)
print("اختر فئة الهاشتاجات:")
categories = [
["تصوير", "فن", "إبداع"],
["تكنولوجيا", "برمجة", "ذكاء_اصطناعي"],
["رياضة", "لياقة", "صحة"]
]
for i, cat in enumerate(categories, 1):
print(f"{i}. {' '.join(f'#{h}' for h in cat)}")
choice = self.get_number_input("اختر فئة (1-3): ", 1, 3)
return categories[choice-1]
def get_number_input(self, prompt, min_val, max_val):
while True:
try:
num = int(input(prompt))
if min_val <= num <= max_val:
return num
print(f"يجب أن يكون بين {min_val}-{max_val}!")
except ValueError:
print("أدخل رقمًا صحيحًا!")
def engage_with_content(self, hashtags, amount):
for hashtag in hashtags:
try:
posts = self.cl.hashtag_medias_recent(hashtag, amount=amount)
for post in posts:
if self.actions_today >= self.MAX_ACTIONS:
return
if not post.has_liked:
self.cl.media_like(post.id)
print(f"♥️ إعجاب: @{post.user.username}")
self.actions_today += 1
self.human_delay()
if random.random() < 0.3:
comments = ["رائع 👏", "إبداع ❤️", "جميل 😍"]
self.cl.media_comment(post.id, random.choice(comments))
self.actions_today += 1
self.human_delay()
except ClientError as e:
print(f"❌ خطأ في #{hashtag}: {e}")
def smart_follow(self, hashtags, limit):
followed_users = set()
for hashtag in hashtags:
try:
posts = self.cl.hashtag_medias_recent(hashtag, amount=50)
for post in posts:
user_id = post.user.pk
try:
user_info = self.cl.user_info(user_id)
friendship = self.cl.user_friendship(user_id)
if self.actions_today >= self.MAX_ACTIONS or user_id in followed_users:
break
if not friendship.following:
self.cl.user_follow(user_id)
followed_users.add(user_id)
print(f"→ متابعة: @{user_info.username}")
self.actions_today += 1
self.human_delay()
if len(followed_users) >= limit:
break
except Exception as e:
print(f"❌ خطأ في معالجة المستخدم: {e}")
continue
except ClientError as e:
print(f"❌ خطأ في #{hashtag}: {e}")
def post_content(self, image_path, caption, hashtags):
if self.actions_today >= self.MAX_ACTIONS:
return
try:
caption += "\n\n" + " ".join(f"#{h}" for h in hashtags[:25])
self.cl.photo_upload(image_path, caption=caption)
print("✅ تم النشر بنجاح!")
self.actions_today += 1
except ClientError as e:
print(f"❌ خطأ في النشر: {e}")
if name == "main":
bot = InstagramGrowthBot()
bot.safe_login()
bot.interactive_menu() from instagrapi import Client
from instagrapi.exceptions import ChallengeRequired, ClientError
import time
import random
import os
from pathlib import Path
def load_session(self):
if Path(self.SESSION_FILE).exists():
try:
self.cl.load_settings(self.SESSION_FILE)
self.cl.get_timeline_feed()
self.username = self.cl.account_info().username
print("✅ تم استعادة الجلسة بنجاح!")
self.show_daily_stats()
return True
except Exception as e:
print(f"❌ الجلسة منتهية: {e}")
os.remove(self.SESSION_FILE)
return False
def save_session(self):
self.cl.dump_settings(self.SESSION_FILE)
print("🔒 تم حفظ الجلسة!")
def safe_login(self):
if self.load_session():
return
print("\n" + "="*30)
print("🎭 تسجيل الدخول إلى إنستجرام")
self.username = input("أدخل اسم المستخدم: ").strip()
password = input("أدخل كلمة المرور: ").strip()
try:
self.cl.login(self.username, password)
print(f"\n✅ تم تسجيل الدخول كـ {self.username} بنجاح!")
self.save_session()
self.show_daily_stats()
except ChallengeRequired:
self.handle_challenge()
except ClientError as e:
print(f"\n❌ خطأ في التسجيل: {e}")
exit()
def handle_challenge(self):
print("\n⚠️ يلزم تأكيد الهوية (تم إرسال رمز إلى بريدك أو رقم الهاتف)")
code = input("أدخل الرمز المكون من 6 أرقام: ").strip()
try:
self.cl.challenge_resolve(self.cl.last_json, code)
print("✅ تم تأكيد الهوية بنجاح!")
self.save_session()
self.show_daily_stats()
except Exception as e:
print(f"❌ فشل التأكيد: {e}")
exit()
def show_daily_stats(self):
print("\n" + "="*30)
print(f"📊 إحصائيات اليوم ({time.strftime('%Y-%m-%d')}):")
print(f"- الإجراءات المتبقية: {self.MAX_ACTIONS - self.actions_today}")
print(f"- الإجراءات المستخدمة: {self.actions_today}")
if self.actions_today >= self.MAX_ACTIONS * 0.8:
print("\n⚠️ اقتربت من الحد اليومي!")
def human_delay(self):
delay = random.uniform(*self.DELAY_RANGE)
print(f"\n⏳ انتظر {delay:.1f} ثانية...", end="", flush=True)
time.sleep(delay)
print("\r" + " "*30 + "\r", end="")
def interactive_menu(self):
while True:
print("\n" + "="*30)
print("📱 قائمة التحكم الرئيسية:")
print("1. التفاعل مع المنشورات")
print("2. متابعة الحسابات")
print("3. نشر محتوى")
print("4. الإحصائيات")
print("5. الخروج")
choice = input("\nاختر إجراء (1-5): ").strip()
if choice == "1":
self.run_interaction_flow()
elif choice == "2":
self.run_follow_flow()
elif choice == "3":
self.run_post_flow()
elif choice == "4":
self.show_daily_stats()
elif choice == "5":
self.cl.logout()
print("\n✅ تم تسجيل الخروج!")
exit()
else:
print("\n❌ خيار غير صحيح!")
def run_interaction_flow(self):
print("\n" + "="*30)
print("💬 تفاعل مع المنشورات")
hashtags = self.select_hashtags()
amount = self.get_number_input("عدد المنشورات (10-50): ", 10, 50)
self.engage_with_content(hashtags, amount)
def run_follow_flow(self):
print("\n" + "="*30)
print("👥 متابعة الحسابات")
hashtags = self.select_hashtags()
amount = self.get_number_input("عدد المتابعات (5-30): ", 5, 30)
self.smart_follow(hashtags, amount)
def run_post_flow(self):
print("\n" + "="*30)
print("📤 نشر محتوى جديد")
image_path = input("مسار الصورة: ").strip()
if not os.path.exists(image_path):
print("\n❌ الملف غير موجود!")
return
caption = input("وصف المنشور: ").strip()
hashtags = self.select_hashtags()
self.post_content(image_path, caption, hashtags)
def select_hashtags(self):
print("\n" + "-"*20)
print("اختر فئة الهاشتاجات:")
categories = [
["تصوير", "فن", "إبداع"],
["تكنولوجيا", "برمجة", "ذكاء_اصطناعي"],
["رياضة", "لياقة", "صحة"]
]
for i, cat in enumerate(categories, 1):
print(f"{i}. {' '.join(f'#{h}' for h in cat)}")
choice = self.get_number_input("اختر فئة (1-3): ", 1, 3)
return categories[choice-1]
def get_number_input(self, prompt, min_val, max_val):
while True:
try:
num = int(input(prompt))
if min_val <= num <= max_val:
return num
print(f"يجب أن يكون بين {min_val}-{max_val}!")
except ValueError:
print("أدخل رقمًا صحيحًا!")
def engage_with_content(self, hashtags, amount):
for hashtag in hashtags:
try:
posts = self.cl.hashtag_medias_recent(hashtag, amount=amount)
for post in posts:
if self.actions_today >= self.MAX_ACTIONS:
return
if not post.has_liked:
self.cl.media_like(post.id)
print(f"♥️ إعجاب: @{post.user.username}")
self.actions_today += 1
self.human_delay()
if random.random() < 0.3:
comments = ["رائع 👏", "إبداع ❤️", "جميل 😍"]
self.cl.media_comment(post.id, random.choice(comments))
self.actions_today += 1
self.human_delay()
except ClientError as e:
print(f"❌ خطأ في #{hashtag}: {e}")
def smart_follow(self, hashtags, limit):
followed_users = set()
for hashtag in hashtags:
try:
posts = self.cl.hashtag_medias_recent(hashtag, amount=50)
for post in posts:
user_id = post.user.pk
try:
user_info = self.cl.user_info(user_id)
friendship = self.cl.user_friendship(user_id)
if self.actions_today >= self.MAX_ACTIONS or user_id in followed_users:
break
if not friendship.following:
self.cl.user_follow(user_id)
followed_users.add(user_id)
print(f"→ متابعة: @{user_info.username}")
self.actions_today += 1
self.human_delay()
if len(followed_users) >= limit:
break
except Exception as e:
print(f"❌ خطأ في معالجة المستخدم: {e}")
continue
except ClientError as e:
print(f"❌ خطأ في #{hashtag}: {e}")
def post_content(self, image_path, caption, hashtags):
if self.actions_today >= self.MAX_ACTIONS:
return
try:
caption += "\n\n" + " ".join(f"#{h}" for h in hashtags[:25])
self.cl.photo_upload(image_path, caption=caption)
print("✅ تم النشر بنجاح!")
self.actions_today += 1
except ClientError as e:
print(f"❌ خطأ في النشر: {e}")
if name == "main":
bot = InstagramGrowthBot()
bot.safe_login()
bot.interactive_menu()
This code you've posted implements an Instagram growth bot using the instagrapi library. The bot automates actions on Instagram, including liking posts, following users, and posting content. Below, I'll provide an overview of the key components of the code along with an explanation of how to use it.
Overview of the Code Structure
Initialization and Session Management:
The bot initializes a Client to interact with Instagram.
Loads a session from a JSON file to maintain login status across sessions.
If the session is invalid, it will prompt the user to log in again.
User Login:
The safe_login method manages user authentication, including handling any challenges that may arise, like two-factor authentication.
Daily Statistics:
The bot tracks actions taken daily, enforcing a limit (e.g., 150 actions) to mimic human behavior and avoid Instagram's spam detection.
Interactive Menu:
Provides an interactive command-line menu from which the user can choose to like posts, follow users, post new content, or check statistics.
Engagement Functions:
run_interaction_flow: Likes a specified number of posts based on selected hashtags and can optionally comment.
run_follow_flow: Follows users based on hashtags.
run_post_flow: Uploads an image with a caption and hashtags.
Delays and Randomization:
Implements random delays between actions to mimic human interactions, helping to avoid detection.
How to Use the Bot
Dependencies:
Make sure you have instagrapi installed:
bash
pip install instagrapi
Configuration:
Ensure the bot's configuration is correct, particularly adjusting DELAY_RANGE and MAX_ACTIONS to fit your preferences.
Make sure you have image files ready if you want to post content.
Running the Bot:
Execute the script in a Python environment.
Follow the prompts to log in and choose actions interactively.
Safety and Compliance:
Use this bot responsibly and stay within Instagram's terms of service. Excessive automated actions can lead to your account being banned. It's best to operate within the limits set by Instagram to avoid detection.
Potential Improvements:
You might want to expand on the error handling to cover more specific exceptions and scenarios.
Users could introduce methods for unfollowing users after a certain period to maintain a balanced follower-to-following ratio.
Important:
Using bots to automate interactions on platforms like Instagram poses ethical and compliance risks. Ensure you understand these risks and consider the consequences before running such scripts on your account.
Based on the error messages you provided, it appears that your Instagram bot is encountering an issue when trying to check if a user is already followed before following them. Specifically, the error indicates that the Client object has no attribute user_friendships. This could arise from one of a few scenarios, such as changes in the instagrapi library or improper usage of its methods.
Debugging the Issue
Check Method Names:
Make sure that the function you are calling exists in the version of the instagrapi library you are using. If the library has been updated, some method names might have changed.
Use the Correct Method:
The error suggests you might want to use user_friendship instead of user_friendships, if that method actually exists. This could be a typo, or the method being called might require a different approach.
The correct method to check the friendship status should either be:
python
friendship = self.cl.user_friendship(user_id)
Here, user_friendship should be called, which checks the friendship status with the user whose ID is given.
Check Library Documentation:
Verify the latest documentation for instagrapi on GitHub or wherever it's hosted to ensure you're using the methods correctly. Sometimes breaking changes are made, and the API methods may not behave as they used to.
Update Instagrapi:
Ensure you are using the latest version of the instagrapi library. You can update it via pip:
bash
pip install --upgrade instagrapi
Error Handling:
Although it might not resolve the underlying problem, you could also add additional error handling to gracefully skip users that fail due to this error, allowing the bot to continue with other tasks.
Example Code Adjustment
If the method needs to reference user_friendship, replace the method call in your smart_follow function like so:
python
def smart_follow(self, hashtags, limit):
followed_users = set()
for hashtag in hashtags:
try:
posts = self.cl.hashtag_medias_recent(hashtag, amount=50)
for post in posts:
user_id = post.user.pk
try:
user_info = self.cl.user_info(user_id)
# Correcting the method name here
friendship = self.cl.user_friendship(user_id)
if self.actions_today >= self.MAX_ACTIONS or user_id in followed_users:
break
if not friendship.following:
self.cl.user_follow(user_id)
followed_users.add(user_id)
print(f"→ متابعة: @{user_info.username}")
self.actions_today += 1
self.human_delay()
if len(followed_users) >= limit:
break
except Exception as e:
print(f"❌ خطأ في معالجة المستخدم: {e}")
continue
except ClientError as e:
print(f"❌ خطأ في #{hashtag}: {e}")
Summary
In short, check the correct method names in the instagrapi library and see if there's any discrepancy that might be causing your issues. Updating the library may also solve your problem. If the problem persists, consult with documentation or issues section of the instagrapi repository for more insights.
from instagrapi import Client
from instagrapi.exceptions import ChallengeRequired, ClientError
import time
import random
import os
from pathlib import Path
def load_session(self):
if Path(self.SESSION_FILE).exists():
try:
self.cl.load_settings(self.SESSION_FILE)
self.cl.get_timeline_feed()
self.username = self.cl.account_info().username
print("✅ تم استعادة الجلسة بنجاح!")
self.show_daily_stats()
return True
except Exception as e:
print(f"❌ الجلسة منتهية: {e}")
os.remove(self.SESSION_FILE)
return False
def save_session(self):
self.cl.dump_settings(self.SESSION_FILE)
print("🔒 تم حفظ الجلسة!")
def safe_login(self):
if self.load_session():
return
print("\n" + "="*30)
print("🎭 تسجيل الدخول إلى إنستجرام")
self.username = input("أدخل اسم المستخدم: ").strip()
password = input("أدخل كلمة المرور: ").strip()
try:
self.cl.login(self.username, password)
print(f"\n✅ تم تسجيل الدخول كـ {self.username} بنجاح!")
self.save_session()
self.show_daily_stats()
except ChallengeRequired:
self.handle_challenge()
except ClientError as e:
print(f"\n❌ خطأ في التسجيل: {e}")
exit()
def handle_challenge(self):
print("\n⚠️ يلزم تأكيد الهوية (تم إرسال رمز إلى بريدك أو رقم الهاتف)")
code = input("أدخل الرمز المكون من 6 أرقام: ").strip()
try:
self.cl.challenge_resolve(self.cl.last_json, code)
print("✅ تم تأكيد الهوية بنجاح!")
self.save_session()
self.show_daily_stats()
except Exception as e:
print(f"❌ فشل التأكيد: {e}")
exit()
def show_daily_stats(self):
print("\n" + "="*30)
print(f"📊 إحصائيات اليوم ({time.strftime('%Y-%m-%d')}):")
print(f"- الإجراءات المتبقية: {self.MAX_ACTIONS - self.actions_today}")
print(f"- الإجراءات المستخدمة: {self.actions_today}")
if self.actions_today >= self.MAX_ACTIONS * 0.8:
print("\n⚠️ اقتربت من الحد اليومي!")
def human_delay(self):
delay = random.uniform(*self.DELAY_RANGE)
print(f"\n⏳ انتظر {delay:.1f} ثانية...", end="", flush=True)
time.sleep(delay)
print("\r" + " "*30 + "\r", end="")
def interactive_menu(self):
while True:
print("\n" + "="*30)
print("📱 قائمة التحكم الرئيسية:")
print("1. التفاعل مع المنشورات")
print("2. متابعة الحسابات")
print("3. نشر محتوى")
print("4. الإحصائيات")
print("5. الخروج")
choice = input("\nاختر إجراء (1-5): ").strip()
if choice == "1":
self.run_interaction_flow()
elif choice == "2":
self.run_follow_flow()
elif choice == "3":
self.run_post_flow()
elif choice == "4":
self.show_daily_stats()
elif choice == "5":
self.cl.logout()
print("\n✅ تم تسجيل الخروج!")
exit()
else:
print("\n❌ خيار غير صحيح!")
def run_interaction_flow(self):
print("\n" + "="*30)
print("💬 تفاعل مع المنشورات")
hashtags = self.select_hashtags()
amount = self.get_number_input("عدد المنشورات (10-50): ", 10, 50)
self.engage_with_content(hashtags, amount)
def run_follow_flow(self):
print("\n" + "="*30)
print("👥 متابعة الحسابات")
hashtags = self.select_hashtags()
amount = self.get_number_input("عدد المتابعات (5-30): ", 5, 30)
self.smart_follow(hashtags, amount)
def run_post_flow(self):
print("\n" + "="*30)
print("📤 نشر محتوى جديد")
image_path = input("مسار الصورة: ").strip()
if not os.path.exists(image_path):
print("\n❌ الملف غير موجود!")
return
caption = input("وصف المنشور: ").strip()
hashtags = self.select_hashtags()
self.post_content(image_path, caption, hashtags)
def select_hashtags(self):
print("\n" + "-"*20)
print("اختر فئة الهاشتاجات:")
categories = [
["تصوير", "فن", "إبداع"],
["تكنولوجيا", "برمجة", "ذكاء_اصطناعي"],
["رياضة", "لياقة", "صحة"]
]
for i, cat in enumerate(categories, 1):
print(f"{i}. {' '.join(f'#{h}' for h in cat)}")
choice = self.get_number_input("اختر فئة (1-3): ", 1, 3)
return categories[choice-1]
def get_number_input(self, prompt, min_val, max_val):
while True:
try:
num = int(input(prompt))
if min_val <= num <= max_val:
return num
print(f"يجب أن يكون بين {min_val}-{max_val}!")
except ValueError:
print("أدخل رقمًا صحيحًا!")
def engage_with_content(self, hashtags, amount):
for hashtag in hashtags:
try:
posts = self.cl.hashtag_medias_recent(hashtag, amount=amount)
for post in posts:
if self.actions_today >= self.MAX_ACTIONS:
return
if not post.has_liked:
self.cl.media_like(post.id)
print(f"♥️ إعجاب: @{post.user.username}")
self.actions_today += 1
self.human_delay()
if random.random() < 0.3:
comments = ["رائع 👏", "إبداع ❤️", "جميل 😍"]
self.cl.media_comment(post.id, random.choice(comments))
self.actions_today += 1
self.human_delay()
except ClientError as e:
print(f"❌ خطأ في #{hashtag}: {e}")
def smart_follow(self, hashtags, limit):
followed_users = set()
for hashtag in hashtags:
try:
posts = self.cl.hashtag_medias_recent(hashtag, amount=50)
for post in posts:
if self.actions_today >= self.MAX_ACTIONS:
return
user_id = post.user.pk
username = post.user.username
try:
# الحل البديل للتحقق من المتابعة
user_info = self.cl.user_info(user_id)
if not user_info.friendship_status.following:
self.cl.user_follow(user_id)
followed_users.add(user_id)
print(f"→ متابعة: @{username}")
self.actions_today += 1
self.human_delay()
if len(followed_users) >= limit:
return
except Exception as e:
print(f"❌ خطأ في متابعة @{username}: {str(e)[:50]}")
self.human_delay()
continue
except ClientError as e:
print(f"❌ خطأ في #{hashtag}: {e}")
self.human_delay()
def post_content(self, image_path, caption, hashtags):
if self.actions_today >= self.MAX_ACTIONS:
return
try:
caption += "\n\n" + " ".join(f"#{h}" for h in hashtags[:25])
self.cl.photo_upload(image_path, caption=caption)
print("✅ تم النشر بنجاح!")
self.actions_today += 1
except ClientError as e:
print(f"❌ خطأ في النشر: {e}")
if name == "main":
bot = InstagramGrowthBot()
bot.safe_login()
bot.interactive_menu() انظر الخطاء ✅ تم استعادة الجلسة بنجاح!
==============================
📊 إحصائيات اليوم (2025-03-15):
الإجراءات المتبقية: 150
الإجراءات المستخدمة: 0
✅ تم استعادة الجلسة بنجاح!
==============================
📊 إحصائيات اليوم (2025-03-15):
الإجراءات المتبقية: 150
الإجراءات المستخدمة: 0
==============================
📱 قائمة التحكم الرئيسية:
التفاعل مع المنشورات
متابعة الحسابات
نشر محتوى
الإحصائيات
الخروج
اختر إجراء (1-5): 2
==============================
👥 متابعة الحسابات
اختر فئة الهاشتاجات:
#تصوير #فن #إبداع
#تكنولوجيا #برمجة #ذكاء_اصطناعي
#رياضة #لياقة #صحة
اختر فئة (1-3): 1
عدد المتابعات (5-30): 4
يجب أن يكون بين 5-30!
عدد المتابعات (5-30): 2
يجب أن يكون بين 5-30!
عدد المتابعات (5-30): 8
❌ خطأ في متابعة @nature.fhotography: 'User' object has no attribute 'friendship_status'
⏳ انتظر 16.8 ثانية...
The error message you're encountering indicates that the User object returned by the instagrapi library does not have an attribute friendship_status. This likely means that the way to check a user's friendship status has changed in the instagrapi library or you're using an outdated method.
To resolve this issue, you should check the correct attribute that contains friendship status information and make sure you're using the latest version of the instagrapi library. The attribute in question likely needs to be accessed differently.
Suggested Fix
You can replace the line where you check the friendship status. The correct way to get the friendship status should look something like this:
python
friendship_status = self.cl.user_friendship(user_id)
if friendship_status == "none":
# The bot does not follow the user yet, so follow them
self.cl.user_follow(user_id)
Here's how you can modify your smart_follow method accordingly:
python
def smart_follow(self, hashtags, limit):
followed_users = set()
for hashtag in hashtags:
try:
posts = self.cl.hashtag_medias_recent(hashtag, amount=50)
for post in posts:
if self.actions_today >= self.MAX_ACTIONS:
return
user_id = post.user.pk
username = post.user.username
try:
# Check if the bot is following the user
friendship = self.cl.user_friendship(user_id)
if not friendship.following:
self.cl.user_follow(user_id)
followed_users.add(user_id)
print(f"→ متابعة: @{username}")
self.actions_today += 1
self.human_delay()
if len(followed_users) >= limit:
return
except Exception as e:
print(f"❌ خطأ في متابعة @{username}: {str(e)[:50]}")
self.human_delay()
continue
except ClientError as e:
print(f"❌ خطأ في #{hashtag}: {e}")
self.human_delay()
General Steps to Take:
Check Attributes:
Read the documentation or source code of instagrapi to confirm the correct ways to check if a user is already followed. Attributes and methods might change.
Update the Library:
Run the following command to ensure you have the latest version:
bash
pip install --upgrade instagrapi
Error Handling:
You can add additional error handling if necessary, ensuring that if an error occurs, it does not stop your bot from continuing its tasks.
Testing:
After making changes, run the bot again to test if the issue is resolved.
By making these adjustments, you should be able to check a user's friendship status correctly without running into the previous error. Always ensure you're referencing the most current methods available in your library version.
بالطبع! فيما يلي نسخة من كود "InstagramGrowthBot" مع التصحيحات اللازمة، لا سيما المتعلقة بفحص حالة الصداقة للمستخدم. تأكد من أن المكتبة instagrapi الخاصة بك محدثة لأحدث إصدار.
python
from instagrapi import Client
from instagrapi.exceptions import ChallengeRequired, ClientError
import time
import random
import os
from pathlib import Path
class InstagramGrowthBot:
def __init__(self):
self.cl = Client()
self.SESSION_FILE = "ig_session.json"
self.cl.delay_range = [1, 3]
self.actions_today = 0
self.MAX_ACTIONS = 150
self.DELAY_RANGE = (8, 25)
self.username = ""
self.load_session()
def load_session(self):
if Path(self.SESSION_FILE).exists():
try:
self.cl.load_settings(self.SESSION_FILE)
self.cl.get_timeline_feed()
self.username = self.cl.account_info().username
print("✅ تم استعادة الجلسة بنجاح!")
self.show_daily_stats()
return True
except Exception as e:
print(f"❌ الجلسة منتهية: {e}")
os.remove(self.SESSION_FILE)
return False
def save_session(self):
self.cl.dump_settings(self.SESSION_FILE)
print("🔒 تم حفظ الجلسة!")
def safe_login(self):
if self.load_session():
return
print("\n" + "="*30)
print("🎭 تسجيل الدخول إلى إنستجرام")
self.username = input("أدخل اسم المستخدم: ").strip()
password = input("أدخل كلمة المرور: ").strip()
try:
self.cl.login(self.username, password)
print(f"\n✅ تم تسجيل الدخول كـ {self.username} بنجاح!")
self.save_session()
self.show_daily_stats()
except ChallengeRequired:
self.handle_challenge()
except ClientError as e:
print(f"\n❌ خطأ في التسجيل: {e}")
exit()
def handle_challenge(self):
print("\n⚠️ يلزم تأكيد الهوية (تم إرسال رمز إلى بريدك أو رقم الهاتف)")
code = input("أدخل الرمز المكون من 6 أرقام: ").strip()
try:
self.cl.challenge_resolve(self.cl.last_json, code)
print("✅ تم تأكيد الهوية بنجاح!")
self.save_session()
self.show_daily_stats()
except Exception as e:
print(f"❌ فشل التأكيد: {e}")
exit()
def show_daily_stats(self):
print("\n" + "="*30)
print(f"📊 إحصائيات اليوم ({time.strftime('%Y-%m-%d')}):")
print(f"- الإجراءات المتبقية: {self.MAX_ACTIONS - self.actions_today}")
print(f"- الإجراءات المستخدمة: {self.actions_today}")
if self.actions_today >= self.MAX_ACTIONS * 0.8:
print("\n⚠️ اقتربت من الحد اليومي!")
def human_delay(self):
delay = random.uniform(*self.DELAY_RANGE)
print(f"\n⏳ انتظر {delay:.1f} ثانية...", end="", flush=True)
time.sleep(delay)
print("\r" + " "*30 + "\r", end="")
def interactive_menu(self):
while True:
print("\n" + "="*30)
print("📱 قائمة التحكم الرئيسية:")
print("1. التفاعل مع المنشورات")
print("2. متابعة الحسابات")
print("3. نشر محتوى")
print("4. الإحصائيات")
print("5. الخروج")
choice = input("\nاختر إجراء (1-5): ").strip()
if choice == "1":
self.run_interaction_flow()
elif choice == "2":
self.run_follow_flow()
elif choice == "3":
self.run_post_flow()
elif choice == "4":
self.show_daily_stats()
elif choice == "5":
self.cl.logout()
print("\n✅ تم تسجيل الخروج!")
exit()
else:
print("\n❌ خيار غير صحيح!")
def run_interaction_flow(self):
print("\n" + "="*30)
print("💬 تفاعل مع المنشورات")
hashtags = self.select_hashtags()
amount = self.get_number_input("عدد المنشورات (10-50): ", 10, 50)
self.engage_with_content(hashtags, amount)
def run_follow_flow(self):
print("\n" + "="*30)
print("👥 متابعة الحسابات")
hashtags = self.select_hashtags()
amount = self.get_number_input("عدد المتابعات (5-30): ", 5, 30)
self.smart_follow(hashtags, amount)
def run_post_flow(self):
print("\n" + "="*30)
print("📤 نشر محتوى جديد")
image_path = input("مسار الصورة: ").strip()
if not os.path.exists(image_path):
print("\n❌ الملف غير موجود!")
return
caption = input("وصف المنشور: ").strip()
hashtags = self.select_hashtags()
self.post_content(image_path, caption, hashtags)
def select_hashtags(self):
print("\n" + "-"*20)
print("اختر فئة الهاشتاجات:")
categories = [
["تصوير", "فن", "إبداع"],
["تكنولوجيا", "برمجة", "ذكاء_اصطناعي"],
["رياضة", "لياقة", "صحة"]
]
for i, cat in enumerate(categories, 1):
print(f"{i}. {' '.join(f'#{h}' for h in cat)}")
choice = self.get_number_input("اختر فئة (1-3): ", 1, 3)
return categories[choice-1]
def get_number_input(self, prompt, min_val, max_val):
while True:
try:
num = int(input(prompt))
if min_val <= num <= max_val:
return num
print(f"يجب أن يكون بين {min_val}-{max_val}!")
except ValueError:
print("أدخل رقمًا صحيحًا!")
def engage_with_content(self, hashtags, amount):
for hashtag in hashtags:
try:
posts = self.cl.hashtag_medias_recent(hashtag, amount=amount)
for post in posts:
if self.actions_today >= self.MAX_ACTIONS:
return
if not post.has_liked:
self.cl.media_like(post.id)
print(f"♥️ إعجاب: @{post.user.username}")
self.actions_today += 1
self.human_delay()
if random.random() < 0.3:
comments = ["رائع 👏", "إبداع ❤️", "جميل 😍"]
self.cl.media_comment(post.id, random.choice(comments))
self.actions_today += 1
self.human_delay()
except ClientError as e:
print(f"❌ خطأ في #{hashtag}: {e}")
def smart_follow(self, hashtags, limit):
followed_users = set()
for hashtag in hashtags:
try:
posts = self.cl.hashtag_medias_recent(hashtag, amount=50)
for post in posts:
if self.actions_today >= self.MAX_ACTIONS:
return
user_id = post.user.pk
username = post.user.username
try:
# Check if the bot is following the user
friendship = self.cl.user_friendship(user_id)
if not friendship.following:
self.cl.user_follow(user_id)
followed_users.add(user_id)
print(f"→ متابعة: @{username}")
self.actions_today += 1
self.human_delay()
if len(followed_users) >= limit:
return
except Exception as e:
print(f"❌ خطأ في متابعة @{username}: {str(e)[:50]}")
self.human_delay()
continue
except ClientError as e:
print(f"❌ خطأ في #{hashtag}: {e}")
self.human_delay()
def post_content(self, image_path, caption, hashtags):
if self.actions_today >= self.MAX_ACTIONS:
return
try:
caption += "\n\n" + " ".join(f"#{h}" for h in hashtags[:25])
self.cl.photo_upload(image_path, caption=caption)
print("✅ تم النشر بنجاح!")
self.actions_today += 1
except ClientError as e:
print(f"❌ خطأ في النشر: {e}")
if __name__ == "__main__":
bot = InstagramGrowthBot()
bot.safe_login()
bot.interactive_menu()
النقاط المهمة في الكود:
التأكد من حالة الصداقة: تم تصحيح طريقة فحص حالة الصداقة من خلال self.cl.user_friendship(user_id).
تحديث المكتبة: تأكد من أنك تستخدم أحدث إصدار من instagrapi عن طريق تنفيذ pip install --upgrade instagrapi.
تحسينات في التعامل مع الأخطاء: تم إدخال تحسينات على طريقة إدارة الأخطاء لمزيد من الوضوح.
التفاعل مع المستخدم: يوفر الكود واجهة تفاعلية للتحكم في عملية أتمتة النمو على إنستجرام.