Skip to content

Instantly share code, notes, and snippets.

@Dentrax
Created July 24, 2023 06:29
Show Gist options
  • Save Dentrax/c4a9ea787b1c3cf9f60e10bfce0ea07a to your computer and use it in GitHub Desktop.
Save Dentrax/c4a9ea787b1c3cf9f60e10bfce0ea07a to your computer and use it in GitHub Desktop.
Move Instagram Collections to Another
from instagrapi import Client
from instagrapi.exceptions import ClientLoginRequired, ClientError
import os
# Instagram accounts credentials
acc1_username = os.environ.get('IM_FROM_USERNAME')
acc1_password = os.environ.get('IM_FROM_PASSWORD')
acc2_username = os.environ.get('IM_TO_USERNAME')
acc2_password = os.environ.get('IM_TO_PASSWORD')
# Create InstaGrapi sessions for each account
session_from = Client()
session_to = Client()
migrate_collection_name = "<COLLECTION_TO_MIGRATE>"
try:
# Login to both accounts
session_from.login(acc1_username, acc1_password)
session_to.login(acc2_username, acc2_password)
# Get the collection from acc1
acc1_collections = session_from.collections()
print("Found collections: " + str(len(acc1_collections)))
target_collection = None
for collection in acc1_collections:
if collection.name == migrate_collection_name:
target_collection = collection
break
if not target_collection:
print("Error: Couldn't find target collection on acc1")
exit()
target_collection_pk = session_to.collection_pk_by_name(migrate_collection_name)
# Traverse acc1's collection
posts = session_from.collection_medias(target_collection.id, 9999)
print("Total posts found in collection {0}: {1}".format(migrate_collection_name, len(posts)))
counter = 0
for post in posts:
counter += 1
print("Migrated {0}".format(counter))
# Find the target insta post on acc2 and save it to collection
try:
saved_post = session_to.media_save(post.id, target_collection_pk)
except ClientError as e:
print(f"Error: Couldn't save post on acc2 - {e}")
continue
# On acc1, unsave the post item
session_from.media_unsave(post.id, target_collection.id)
print("DONE!")
except ClientLoginRequired:
print("Error: Login failed, please check your credentials")
finally:
# Close the sessions
session_from.logout()
session_to.logout()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment