Instagram bot scripts for promotion and API python wrapper
—
Utility classes for managing user lists, bot state persistence, and file-based storage operations. The file management system provides essential functionality for maintaining blacklists, whitelists, followed users, and other bot state data.
Manage text files containing user lists and bot state data with support for reading, writing, and manipulating line-based content.
class file:
def __init__(self, fname, verbose=True):
"""
Initialize file utility for managing text-based user lists.
Parameters:
- fname: Filename or path to the file
- verbose: Enable verbose logging output
"""
def append(self, item, allow_duplicates=False):
"""
Add item to file with duplicate control.
Parameters:
- item: Item to add to file (converted to string)
- allow_duplicates: Allow duplicate entries if True
Returns:
bool: True if item was added, False if duplicate and not allowed
"""
def remove(self, x):
"""
Remove item from file.
Parameters:
- x: Item to remove from file
Returns:
bool: True if item was found and removed, False otherwise
"""
def random(self):
"""
Get random item from file.
Returns:
str: Random item from file, or None if file is empty
"""
def remove_duplicates(self):
"""
Remove duplicate entries from file.
Reads file, removes duplicates, and rewrites with unique entries.
Returns:
int: Number of duplicates removed
"""
def save_list(self, items):
"""
Save list of items to file, overwriting existing content.
Parameters:
- items: List of items to save to file
Returns:
bool: True if save successful
"""
def __iter__(self):
"""
Iterator protocol support for file contents.
Returns:
iterator: Iterator over file contents
"""
def __len__(self):
"""
Get number of lines in file.
Returns:
int: Number of lines in file
"""Access file contents as different data structures for flexible usage.
@property
def list(self):
"""
Get file contents as list.
Returns:
list: File contents with each line as a list item
"""
@property
def set(self):
"""
Get file contents as set for duplicate-free access.
Returns:
set: File contents as set with unique entries only
"""from instabot.utils import file
# Initialize file for managing followed users
followed_users = file("followed.txt", verbose=True)
# Add users to followed list
followed_users.append("user123")
followed_users.append("photographer_pro")
followed_users.append("travel_blogger")
# Check if user is in list
if "user123" in followed_users.set:
print("User is already followed")
# Remove user from list
followed_users.remove("user123")
# Get random user from list
random_user = followed_users.random()
print(f"Random followed user: {random_user}")
# Clean up duplicates
duplicates_removed = followed_users.remove_duplicates()
print(f"Removed {duplicates_removed} duplicate entries")from instabot.utils import file
# Initialize different bot state files
whitelist = file("whitelist.txt")
blacklist = file("blacklist.txt")
followed = file("followed.txt")
unfollowed = file("unfollowed.txt")
comments = file("comments.txt")
# Add trusted users to whitelist
trusted_users = ["friend1", "friend2", "business_partner"]
whitelist.save_list(trusted_users)
# Add problematic users to blacklist
blacklist.append("spam_account", allow_duplicates=False)
blacklist.append("fake_follower", allow_duplicates=False)
# Track follow/unfollow actions
def track_follow(user_id):
followed.append(user_id)
print(f"Added {user_id} to followed list")
def track_unfollow(user_id):
followed.remove(user_id)
unfollowed.append(user_id)
print(f"Moved {user_id} from followed to unfollowed")
# Use in bot workflow
track_follow("new_user123")
track_unfollow("old_user456")
# Analyze bot state
print(f"Total followed: {len(followed.list)}")
print(f"Total unfollowed: {len(unfollowed.list)}")
print(f"Blacklisted users: {len(blacklist.list)}")
print(f"Whitelisted users: {len(whitelist.list)}")from instabot.utils import file
import random
# Manage comment templates
comments_file = file("comments.txt")
# Add variety of comments
comment_templates = [
"Great photo! 📸",
"Amazing content! 👍",
"Love this! ❤️",
"Awesome post! 🔥",
"Beautiful shot! ✨",
"Incredible! 😍",
"So inspiring! 💫",
"Perfect! 👌"
]
comments_file.save_list(comment_templates)
# Get random comment for bot usage
def get_random_comment():
return comments_file.random()
# Use in automation
for i in range(5):
comment = get_random_comment()
print(f"Bot comment {i+1}: {comment}")
# Clean up and maintain comments
print(f"Total comments available: {len(comments_file.list)}")
comments_file.remove_duplicates()from instabot.utils import file
import os
from datetime import datetime
class BotStateManager:
def __init__(self, base_path="./bot_data/"):
self.base_path = base_path
os.makedirs(base_path, exist_ok=True)
# Initialize all state files
self.followed = file(os.path.join(base_path, "followed.txt"))
self.unfollowed = file(os.path.join(base_path, "unfollowed.txt"))
self.whitelist = file(os.path.join(base_path, "whitelist.txt"))
self.blacklist = file(os.path.join(base_path, "blacklist.txt"))
self.liked_posts = file(os.path.join(base_path, "liked_posts.txt"))
self.skipped_users = file(os.path.join(base_path, "skipped_users.txt"))
def backup_state(self):
"""Create backup of all state files"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_path = os.path.join(self.base_path, f"backup_{timestamp}/")
os.makedirs(backup_path, exist_ok=True)
state_files = [
("followed.txt", self.followed.list),
("unfollowed.txt", self.unfollowed.list),
("whitelist.txt", self.whitelist.list),
("blacklist.txt", self.blacklist.list),
("liked_posts.txt", self.liked_posts.list),
("skipped_users.txt", self.skipped_users.list)
]
for filename, data in state_files:
backup_file = file(os.path.join(backup_path, filename))
backup_file.save_list(data)
print(f"State backed up to {backup_path}")
def clean_all_files(self):
"""Remove duplicates from all state files"""
files_to_clean = [
self.followed, self.unfollowed, self.whitelist,
self.blacklist, self.liked_posts, self.skipped_users
]
total_duplicates = 0
for state_file in files_to_clean:
duplicates = state_file.remove_duplicates()
total_duplicates += duplicates
print(f"Cleaned {total_duplicates} total duplicates")
def get_state_summary(self):
"""Get summary of all bot state"""
return {
"followed_count": len(self.followed.list),
"unfollowed_count": len(self.unfollowed.list),
"whitelist_count": len(self.whitelist.list),
"blacklist_count": len(self.blacklist.list),
"liked_posts_count": len(self.liked_posts.list),
"skipped_users_count": len(self.skipped_users.list)
}
# Usage
state_manager = BotStateManager("./my_bot_state/")
# Track bot actions
state_manager.followed.append("new_follower_123")
state_manager.liked_posts.append("media_456789")
# Maintain state
state_manager.clean_all_files()
state_manager.backup_state()
# Monitor state
summary = state_manager.get_state_summary()
for key, value in summary.items():
print(f"{key}: {value}")from instabot import Bot
from instabot.utils import file
# Custom bot with enhanced file management
class EnhancedBot(Bot):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Initialize custom tracking files
self.successful_follows = file("successful_follows.txt")
self.failed_actions = file("failed_actions.txt")
self.high_engagement_users = file("high_engagement_users.txt")
def enhanced_follow(self, user_id):
"""Follow user with enhanced tracking"""
result = self.follow(user_id)
if result:
self.successful_follows.append(user_id)
print(f"Successfully followed {user_id}")
else:
self.failed_actions.append(f"follow_{user_id}")
print(f"Failed to follow {user_id}")
return result
def track_high_engagement(self, user_id, engagement_score):
"""Track users with high engagement"""
if engagement_score > 0.8: # 80% engagement threshold
self.high_engagement_users.append(user_id)
def get_follow_success_rate(self):
"""Calculate follow success rate"""
successful = len(self.successful_follows.list)
failed_follows = len([action for action in self.failed_actions.list
if action.startswith("follow_")])
total = successful + failed_follows
if total == 0:
return 0
return (successful / total) * 100
# Usage
enhanced_bot = EnhancedBot()
enhanced_bot.login(username="user", password="pass")
# Use enhanced tracking
target_users = ["user1", "user2", "user3"]
for user in target_users:
enhanced_bot.enhanced_follow(user)
# Analyze performance
success_rate = enhanced_bot.get_follow_success_rate()
print(f"Follow success rate: {success_rate:.1f}%")
enhanced_bot.logout()Install with Tessl CLI
npx tessl i tessl/pypi-instabot