Skip to content

Commit

Permalink
Merge pull request InstaPy#2727 from CharlesCCC/master
Browse files Browse the repository at this point in the history
Log the userid when following other users
  • Loading branch information
timgrossmann authored Aug 23, 2018
2 parents 2d3614c + 9f9e857 commit 479ed8e
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 25 deletions.
4 changes: 2 additions & 2 deletions instapy/print_log_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,13 @@ def log_following_num(browser, username, logfolder):
return following_num


def log_followed_pool(login, followed, logger, logfolder, logtime):
def log_followed_pool(login, followed, logger, logfolder, logtime, userid):
"""Prints and logs the followed to
a seperate file"""
try:
with open('{0}{1}_followedPool.csv'.format(logfolder, login), 'a+') as followPool:
with interruption_handler():
followPool.write('{} ~ {},\n'.format(logtime, followed))
followPool.write('{} ~ {} ~ {},\n'.format(logtime, followed,userid))
except BaseException as e:
logger.error("log_followed_pool error {}".format(str(e)))

Expand Down
74 changes: 52 additions & 22 deletions instapy/unfollow_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,27 +33,40 @@


def set_automated_followed_pool(username, unfollow_after, logger, logfolder, pool='followedPool'):
automatedFollowedPool = {"all":[], "eligible":[]}
automatedFollowedPool = {"all":[], "allid":[], "eligible":[],"eligibleid":[]}
try:
with open('{0}{1}_{2}.csv'.format(logfolder, username, pool), 'r+') as followedPoolFile:
reader = csv.reader(followedPoolFile)
for row in reader:
row_segement = row[0].split(' ~ ')
if unfollow_after is not None:
try:
ftime = datetime.strptime(row[0].split(' ~ ')[0], '%Y-%m-%d %H:%M')
ftime = datetime.strptime(row_segement[0], '%Y-%m-%d %H:%M')
ftimestamp = (ftime - datetime(1970, 1, 1)).total_seconds()
realtimestamp = (datetime.now() - datetime(1970, 1, 1)).total_seconds()
fword = row[0].split(' ~ ')[1]
fword = row_segement[1]
if realtimestamp - ftimestamp > unfollow_after:
automatedFollowedPool["eligible"].append(fword)
automatedFollowedPool["all"].append(fword)
if len(row_segement) > 2:
fuid = row_segement[2]
if realtimestamp - ftimestamp > unfollow_after:
automatedFollowedPool["eligibleid"].append(fuid)
automatedFollowedPool["allid"].append(fuid)
except ValueError:
fword = row[0]
fword = row_segement[1]
automatedFollowedPool["all"].append(fword)
automatedFollowedPool["eligible"].append(fword)
if len(row_segement) > 2:
fuid = row_segement[2]
automatedFollowedPool["allid"].append(fuid)
automatedFollowedPool["eligibleid"].append(fuid)
else:
try:
fword = row[0].split(' ~ ')[1]
fword = row_segement[1]
if len(row_segement) > 2:
fuid = row_segement[2]
automatedFollowedPool["eligibleid"].append(fuid)
except IndexError:
fword = row[0]
automatedFollowedPool["all"].append(fword)
Expand Down Expand Up @@ -87,8 +100,9 @@ def get_following_status(browser, person, logger):
except:
logger.error(
'--> Unfollow error with {},'
' maybe no longer exists...'
' maybe no longer exists....'
.format(person.encode('utf-8')))
raise Exception

return following, follow_button

Expand Down Expand Up @@ -168,6 +182,7 @@ def unfollow(browser,
elif InstapyFollowed == True:
logger.info("Unfollowing the users followed by InstaPy\n")
unfollow_list = automatedFollowedPool["eligible"]
unfollowid_list = automatedFollowedPool["eligibleid"]

elif nonFollowers == True:
logger.info("Unfollowing the users who do not follow back\n")
Expand Down Expand Up @@ -231,6 +246,7 @@ def unfollow(browser,
try:
sleep_counter = 0
sleep_after = random.randint(8, 12)
index = 0

for person in unfollow_list:
if unfollowNum >= amount:
Expand All @@ -250,17 +266,25 @@ def unfollow(browser,
pass

if person not in dont_include:
browser.get('https://www.instagram.com/' + person)
sleep(2)

try:
browser.get('https://www.instagram.com/' + person)
following, follow_button = get_following_status(browser, person, logger)
except:
logger.error(
'--> Unfollow error with {},'
' maybe no longer exists...'
' maybe username has changed or he/she blocked you...'
.format(person.encode('utf-8')))
continue
try:
browser.get('https://www.instagram.com/web/friendships/{}/follow/'.format(unfollowid_list[index]))
following, follow_button = get_following_status(browser, person, logger)
except:
logger.error(
'--> Unfollow error with {},'
' maybe no longer exists...'
.format(person.encode('utf-8')))
continue
pass

if following:
# click the button
Expand Down Expand Up @@ -292,8 +316,7 @@ def unfollow(browser,
' now unfollowing: {}'
.format(str(unfollowNum), amount, person.encode('utf-8')))

delete_line_from_file('{0}{1}_followedPool.csv'.format(logfolder, username), person +
",\n", logger)
delete_line_from_file('{0}{1}_followedPool.csv'.format(logfolder, username), person, logger)

print('')
sleep(15)
Expand Down Expand Up @@ -325,7 +348,7 @@ def unfollow(browser,
.format(str(unfollowNum), person.encode('utf-8')))

delete_line_from_file('{0}{1}_followedPool.csv'.format(logfolder, username),
person + ",\n", logger)
person, logger)

print('')
sleep(2)
Expand All @@ -334,13 +357,13 @@ def unfollow(browser,
# if he is a white list user (set at init and not during run time)
if person in white_list:
delete_line_from_file('{0}{1}_followedPool.csv'.format(logfolder, username),
person + ",\n", logger)
person, logger)
list_type = 'whitelist'
else:
list_type = 'dont_include'
logger.info("Not unfollowing '{}'! ~user is in the list {}\n".format(person, list_type))
index += 1
continue

except BaseException as e:
logger.error("Unfollow loop error: {}\n".format(str(e)))

Expand Down Expand Up @@ -450,8 +473,7 @@ def unfollow(browser,
'--> Ongoing Unfollow {}/{}, now unfollowing: {}'
.format(str(unfollowNum), amount, person.encode('utf-8')))

delete_line_from_file('{0}{1}_followedPool.csv'.format(logfolder, username), person +
",\n", logger)
delete_line_from_file('{0}{1}_followedPool.csv'.format(logfolder, username), person, logger)

print('')
sleep(15)
Expand Down Expand Up @@ -491,10 +513,11 @@ def follow_user(browser, login, user_name, blacklist, logger, logfolder):
"arguments[0].style.opacity = 1", follow_button)
click_element(browser, follow_button) # follow_button.click()
update_activity('follows')
userid = browser.execute_script("return window._sharedData.entry_data.PostPage[0].graphql.shortcode_media.owner.id")

logger.info('--> Now following')
logtime = datetime.now().strftime('%Y-%m-%d %H:%M')
log_followed_pool(login, user_name, logger, logfolder, logtime)
log_followed_pool(login, user_name, logger, logfolder, logtime, userid)
follow_restriction("write", user_name, None, logger)
if blacklist['enabled'] is True:
action = 'followed'
Expand Down Expand Up @@ -532,8 +555,7 @@ def unfollow_user(browser, username, person, relationship_data, logger, logfolde
click_element(browser, unfollow_button) # unfollow_button.send_keys("\n")
logger.warning("--> Unfollowed '{}' due to Inappropriate Content".format(person))

delete_line_from_file('{0}{1}_followedPool.csv'.format(logfolder, username), person +
",\n", logger)
delete_line_from_file('{0}{1}_followedPool.csv'.format(logfolder, username), person, logger)

if person in relationship_data[username]["all_following"]:
relationship_data[username]["all_following"].remove(person)
Expand Down Expand Up @@ -567,7 +589,9 @@ def follow_given_user(browser,
update_activity('follows')
logger.info('---> Now following: {}'.format(acc_to_follow))
logtime = datetime.now().strftime('%Y-%m-%d %H:%M')
log_followed_pool(login, acc_to_follow, logger, logfolder, logtime)
userid = browser.execute_script("return window._sharedData.entry_data.ProfilePage[0].graphql.user.id")
#userid = browser.execute_script("return window._sharedData.entry_data.PostPage[0].graphql.shortcode_media.owner.id")
log_followed_pool(login, acc_to_follow, logger, logfolder, logtime, userid)
follow_restriction("write", acc_to_follow, None, logger)

if blacklist['enabled'] is True:
Expand Down Expand Up @@ -753,8 +777,14 @@ def follow_through_dialog(browser,

click_element(browser, button)
sleep(1)

browser.get('https://www.instagram.com/' + person)
userid = browser.execute_script("return window._sharedData.entry_data.ProfilePage[0].graphql.user.id")

logtime = datetime.now().strftime('%Y-%m-%d %H:%M')
log_followed_pool(login, person, logger, logfolder, logtime)
log_followed_pool(login, person, logger, logfolder, logtime, userid)

browser.execute_script("window.history.go(-1)")

update_activity('follows')

Expand Down
2 changes: 1 addition & 1 deletion instapy/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ def delete_line_from_file(filepath, lineToDelete, logger):

f = open(file_path_Temp, "w")
for line in lines:
if not line.endswith(lineToDelete):
if (line.find(lineToDelete) < 0):
f.write(line)
else:
logger.info("\tRemoved '{}' from followedPool.csv file".format(line.split(',\n')[0]))
Expand Down

0 comments on commit 479ed8e

Please sign in to comment.