0
# File Management
1
2
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.
3
4
## Capabilities
5
6
### File Utility Class
7
8
Manage text files containing user lists and bot state data with support for reading, writing, and manipulating line-based content.
9
10
```python { .api }
11
class file:
12
def __init__(self, fname, verbose=True):
13
"""
14
Initialize file utility for managing text-based user lists.
15
16
Parameters:
17
- fname: Filename or path to the file
18
- verbose: Enable verbose logging output
19
"""
20
21
def append(self, item, allow_duplicates=False):
22
"""
23
Add item to file with duplicate control.
24
25
Parameters:
26
- item: Item to add to file (converted to string)
27
- allow_duplicates: Allow duplicate entries if True
28
29
Returns:
30
bool: True if item was added, False if duplicate and not allowed
31
"""
32
33
def remove(self, x):
34
"""
35
Remove item from file.
36
37
Parameters:
38
- x: Item to remove from file
39
40
Returns:
41
bool: True if item was found and removed, False otherwise
42
"""
43
44
def random(self):
45
"""
46
Get random item from file.
47
48
Returns:
49
str: Random item from file, or None if file is empty
50
"""
51
52
def remove_duplicates(self):
53
"""
54
Remove duplicate entries from file.
55
56
Reads file, removes duplicates, and rewrites with unique entries.
57
58
Returns:
59
int: Number of duplicates removed
60
"""
61
62
def save_list(self, items):
63
"""
64
Save list of items to file, overwriting existing content.
65
66
Parameters:
67
- items: List of items to save to file
68
69
Returns:
70
bool: True if save successful
71
"""
72
73
def __iter__(self):
74
"""
75
Iterator protocol support for file contents.
76
77
Returns:
78
iterator: Iterator over file contents
79
"""
80
81
def __len__(self):
82
"""
83
Get number of lines in file.
84
85
Returns:
86
int: Number of lines in file
87
"""
88
```
89
90
### File Properties
91
92
Access file contents as different data structures for flexible usage.
93
94
```python { .api }
95
@property
96
def list(self):
97
"""
98
Get file contents as list.
99
100
Returns:
101
list: File contents with each line as a list item
102
"""
103
104
@property
105
def set(self):
106
"""
107
Get file contents as set for duplicate-free access.
108
109
Returns:
110
set: File contents as set with unique entries only
111
"""
112
```
113
114
## Usage Examples
115
116
### Basic File Operations
117
118
```python
119
from instabot.utils import file
120
121
# Initialize file for managing followed users
122
followed_users = file("followed.txt", verbose=True)
123
124
# Add users to followed list
125
followed_users.append("user123")
126
followed_users.append("photographer_pro")
127
followed_users.append("travel_blogger")
128
129
# Check if user is in list
130
if "user123" in followed_users.set:
131
print("User is already followed")
132
133
# Remove user from list
134
followed_users.remove("user123")
135
136
# Get random user from list
137
random_user = followed_users.random()
138
print(f"Random followed user: {random_user}")
139
140
# Clean up duplicates
141
duplicates_removed = followed_users.remove_duplicates()
142
print(f"Removed {duplicates_removed} duplicate entries")
143
```
144
145
### Managing Bot State Files
146
147
```python
148
from instabot.utils import file
149
150
# Initialize different bot state files
151
whitelist = file("whitelist.txt")
152
blacklist = file("blacklist.txt")
153
followed = file("followed.txt")
154
unfollowed = file("unfollowed.txt")
155
comments = file("comments.txt")
156
157
# Add trusted users to whitelist
158
trusted_users = ["friend1", "friend2", "business_partner"]
159
whitelist.save_list(trusted_users)
160
161
# Add problematic users to blacklist
162
blacklist.append("spam_account", allow_duplicates=False)
163
blacklist.append("fake_follower", allow_duplicates=False)
164
165
# Track follow/unfollow actions
166
def track_follow(user_id):
167
followed.append(user_id)
168
print(f"Added {user_id} to followed list")
169
170
def track_unfollow(user_id):
171
followed.remove(user_id)
172
unfollowed.append(user_id)
173
print(f"Moved {user_id} from followed to unfollowed")
174
175
# Use in bot workflow
176
track_follow("new_user123")
177
track_unfollow("old_user456")
178
179
# Analyze bot state
180
print(f"Total followed: {len(followed.list)}")
181
print(f"Total unfollowed: {len(unfollowed.list)}")
182
print(f"Blacklisted users: {len(blacklist.list)}")
183
print(f"Whitelisted users: {len(whitelist.list)}")
184
```
185
186
### Content Management
187
188
```python
189
from instabot.utils import file
190
import random
191
192
# Manage comment templates
193
comments_file = file("comments.txt")
194
195
# Add variety of comments
196
comment_templates = [
197
"Great photo! πΈ",
198
"Amazing content! π",
199
"Love this! β€οΈ",
200
"Awesome post! π₯",
201
"Beautiful shot! β¨",
202
"Incredible! π",
203
"So inspiring! π«",
204
"Perfect! π"
205
]
206
207
comments_file.save_list(comment_templates)
208
209
# Get random comment for bot usage
210
def get_random_comment():
211
return comments_file.random()
212
213
# Use in automation
214
for i in range(5):
215
comment = get_random_comment()
216
print(f"Bot comment {i+1}: {comment}")
217
218
# Clean up and maintain comments
219
print(f"Total comments available: {len(comments_file.list)}")
220
comments_file.remove_duplicates()
221
```
222
223
### Advanced File Management
224
225
```python
226
from instabot.utils import file
227
import os
228
from datetime import datetime
229
230
class BotStateManager:
231
def __init__(self, base_path="./bot_data/"):
232
self.base_path = base_path
233
os.makedirs(base_path, exist_ok=True)
234
235
# Initialize all state files
236
self.followed = file(os.path.join(base_path, "followed.txt"))
237
self.unfollowed = file(os.path.join(base_path, "unfollowed.txt"))
238
self.whitelist = file(os.path.join(base_path, "whitelist.txt"))
239
self.blacklist = file(os.path.join(base_path, "blacklist.txt"))
240
self.liked_posts = file(os.path.join(base_path, "liked_posts.txt"))
241
self.skipped_users = file(os.path.join(base_path, "skipped_users.txt"))
242
243
def backup_state(self):
244
"""Create backup of all state files"""
245
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
246
backup_path = os.path.join(self.base_path, f"backup_{timestamp}/")
247
os.makedirs(backup_path, exist_ok=True)
248
249
state_files = [
250
("followed.txt", self.followed.list),
251
("unfollowed.txt", self.unfollowed.list),
252
("whitelist.txt", self.whitelist.list),
253
("blacklist.txt", self.blacklist.list),
254
("liked_posts.txt", self.liked_posts.list),
255
("skipped_users.txt", self.skipped_users.list)
256
]
257
258
for filename, data in state_files:
259
backup_file = file(os.path.join(backup_path, filename))
260
backup_file.save_list(data)
261
262
print(f"State backed up to {backup_path}")
263
264
def clean_all_files(self):
265
"""Remove duplicates from all state files"""
266
files_to_clean = [
267
self.followed, self.unfollowed, self.whitelist,
268
self.blacklist, self.liked_posts, self.skipped_users
269
]
270
271
total_duplicates = 0
272
for state_file in files_to_clean:
273
duplicates = state_file.remove_duplicates()
274
total_duplicates += duplicates
275
276
print(f"Cleaned {total_duplicates} total duplicates")
277
278
def get_state_summary(self):
279
"""Get summary of all bot state"""
280
return {
281
"followed_count": len(self.followed.list),
282
"unfollowed_count": len(self.unfollowed.list),
283
"whitelist_count": len(self.whitelist.list),
284
"blacklist_count": len(self.blacklist.list),
285
"liked_posts_count": len(self.liked_posts.list),
286
"skipped_users_count": len(self.skipped_users.list)
287
}
288
289
# Usage
290
state_manager = BotStateManager("./my_bot_state/")
291
292
# Track bot actions
293
state_manager.followed.append("new_follower_123")
294
state_manager.liked_posts.append("media_456789")
295
296
# Maintain state
297
state_manager.clean_all_files()
298
state_manager.backup_state()
299
300
# Monitor state
301
summary = state_manager.get_state_summary()
302
for key, value in summary.items():
303
print(f"{key}: {value}")
304
```
305
306
### Integration with Bot Workflow
307
308
```python
309
from instabot import Bot
310
from instabot.utils import file
311
312
# Custom bot with enhanced file management
313
class EnhancedBot(Bot):
314
def __init__(self, **kwargs):
315
super().__init__(**kwargs)
316
317
# Initialize custom tracking files
318
self.successful_follows = file("successful_follows.txt")
319
self.failed_actions = file("failed_actions.txt")
320
self.high_engagement_users = file("high_engagement_users.txt")
321
322
def enhanced_follow(self, user_id):
323
"""Follow user with enhanced tracking"""
324
result = self.follow(user_id)
325
326
if result:
327
self.successful_follows.append(user_id)
328
print(f"Successfully followed {user_id}")
329
else:
330
self.failed_actions.append(f"follow_{user_id}")
331
print(f"Failed to follow {user_id}")
332
333
return result
334
335
def track_high_engagement(self, user_id, engagement_score):
336
"""Track users with high engagement"""
337
if engagement_score > 0.8: # 80% engagement threshold
338
self.high_engagement_users.append(user_id)
339
340
def get_follow_success_rate(self):
341
"""Calculate follow success rate"""
342
successful = len(self.successful_follows.list)
343
failed_follows = len([action for action in self.failed_actions.list
344
if action.startswith("follow_")])
345
total = successful + failed_follows
346
347
if total == 0:
348
return 0
349
350
return (successful / total) * 100
351
352
# Usage
353
enhanced_bot = EnhancedBot()
354
enhanced_bot.login(username="user", password="pass")
355
356
# Use enhanced tracking
357
target_users = ["user1", "user2", "user3"]
358
for user in target_users:
359
enhanced_bot.enhanced_follow(user)
360
361
# Analyze performance
362
success_rate = enhanced_bot.get_follow_success_rate()
363
print(f"Follow success rate: {success_rate:.1f}%")
364
365
enhanced_bot.logout()
366
```