Skip to content

Commit

Permalink
Add async for commenting
Browse files Browse the repository at this point in the history
  • Loading branch information
birdhouses committed Apr 26, 2023
1 parent 353ee37 commit 63fccfc
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 40 deletions.
2 changes: 1 addition & 1 deletion instabot/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .utils import get_client, load_config, get_user_id, get_followers, calculate_sleep_time
from .utils import get_client, load_config, get_user_id, get_followers, calculate_sleep_time, logger
from .follow import follow_user_followers, unfollow_users
from .like_media import like_recent_posts
from .comment import comment_on_media
33 changes: 22 additions & 11 deletions instabot/comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,34 @@
logger = logging.getLogger()

async def comment_on_media(cl: Client, account: Dict[str, Any]) -> None:
comment_on_tag = account['comment_on_media']['comment_on_tag']
amount_per_day = account['comment_on_media']['amount_per_day']
try:
comment_on_tag = account['comment_on_media']['comment_on_tag']
amount_per_day = account['comment_on_media']['amount_per_day']

posts_to_comment = cl.hashtag_medias_recent(comment_on_tag, amount_per_day)
posts_to_comment = cl.hashtag_medias_recent(comment_on_tag, amount_per_day)

for post in posts_to_comment:
comment = random.choice(account['comment_on_media']['comments'])
for post in posts_to_comment:
try:
comment = random.choice(account['comment_on_media']['comments'])

sleep_time = calculate_sleep_time(amount_per_day)
logger.info(f"Sleeping for {sleep_time} before commenting")
# await asyncio.sleep(sleep_time)
sleep_time = calculate_sleep_time(amount_per_day)
logger.info(f"Sleeping for {sleep_time} before commenting")
await asyncio.sleep(sleep_time)

comment = cl.media_comment(post.id, comment)
comment = cl.media_comment(post.id, comment)

save_comment(comment.pk, account['username'])
save_comment(comment.pk, account['username'])

logger.info(f"Commented on post {post.id}")
logger.info(f"Commented on post {post.id}")
except Exception as e:
logger.error(f"Error while commenting on media {post['pk']}: {e}")
# Continue with the next iteration without stopping the whole task
continue

except Exception as e:
logger.error(f"Error while fetching media for hashtag {comment_on_tag}: {e}")
# Exit the current task without affecting other tasks
return

def save_comment(comment_pk: int, username: str):
comment_folder = "comments"
Expand Down
18 changes: 13 additions & 5 deletions instabot/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import time
import json
import os
import os.path
import logging
import random
import requests
Expand Down Expand Up @@ -78,10 +79,14 @@ def load_or_login_and_save_session(client, username, password, session_file_path
login_and_save_session(client, username, password, session_file_path)

def remove_session_and_login(client, username, password, session_file_path):
try:
os.remove(session_file_path)
except OSError as e:
logger.warning(f"Error removing session file: {e}")
if os.path.exists(session_file_path):
try:
os.remove(session_file_path)
logger.info(f"Session file removed: {session_file_path}")
except OSError as e:
logger.warning(f"Error removing session file: {e}")
else:
logger.warning(f"Session file not found: {session_file_path}")

login_and_save_session(client, username, password, session_file_path)

Expand All @@ -96,8 +101,10 @@ def get_client(username: str, password: str) -> Union[Client, None]:
session_file_path = os.path.join(settings_folder, f"settings_{username}.json")

def handle_exception(client: Client, e: Exception) -> Union[bool, None]:
logger.warning(f"Error while logging in: {e}")
if isinstance(e, BadPassword):
raise e
logger.error(f"Login failed for user {username}: {e}")
return None
elif isinstance(e, LoginRequired):
remove_session_and_login(client, username=username, password=password, session_file_path=session_file_path)
return True
Expand All @@ -114,6 +121,7 @@ def handle_exception(client: Client, e: Exception) -> Union[bool, None]:
return True
elif isinstance(e, RetryError):
client.set_proxy(next_proxy())
freeze(e, 1)
remove_session_and_login(client, username=username, password=password, session_file_path=session_file_path)
return True
raise e
Expand Down
62 changes: 39 additions & 23 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,48 @@
import instabot
import asyncio
from instabot import follow_user_followers, unfollow_users, comment_on_media
from instabot import logger
from threading import Thread

async def main(account):
username = account['username']
password = account['password']

logger.info(f'Started process for {username}')

async with asyncio.TaskGroup() as tg:
if account['follow_users']['enabled']:
cl = instabot.get_client(username, password)
follow_task = tg.create_task(
follow_user_followers(cl, account)
)
if account['unfollow_users']['enabled']:
cl = instabot.get_client(username, password)
unfollow_task = tg.create_task(
unfollow_users(cl, account['unfollow_users']['unfollow_after_days'])
)
if account['comment_on_media']['enabled']:
cl = instabot.get_client(username, password)
comment_task = tg.create_task(
comment_on_media(cl, account)
)

def run_account(account):
asyncio.run(main(account))

async def main(accounts):
for account in accounts:
username = account['username']
password = account['password']

cl = instabot.get_client(username, password)

async with asyncio.TaskGroup() as tg:
if account['follow_users']['enabled']:
follow_task = tg.create_task(
follow_user_followers(cl, account)
)
if account['unfollow_users']['enabled']:
unfollow_task = tg.create_task(
unfollow_users(cl, account['unfollow_users']['unfollow_after_days'])
)
if account['comment_on_media']['enabled']:
comment_task = tg.create_task(
comment_on_media(cl, account)
)

print("All tasks have finished...")
if __name__ == "__main__":
config = instabot.load_config('config.json')

# Get the accounts from the configuration file
accounts = config['accounts']
asyncio.run(main(accounts))

# Create a thread for each account and run the main function
account_threads = []
for account in accounts:
account_thread = Thread(target=run_account, args=(account,))
account_threads.append(account_thread)
account_thread.start()

# Wait for all account threads to finish
for account_thread in account_threads:
account_thread.join()

0 comments on commit 63fccfc

Please sign in to comment.