question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Instagram temporary locked

See original GitHub issue

Describe the bug I’ve been letting instaloader run every 5 min for the last few months. Yesterday, it raised a 400 Bad Request exception and when I went to instagram I was met with a temporarily locked page and was forced to change my password. I changed the password and re-created the instaloader-session file with the new credentials and restarted instaloader. All was working fine until today at 03:00 AM where it started having the same issues. I went to the instagram page and I was temporarily locked again.

To Reproduce Steps to reproduce the behavior: (e.g. Instaloader command line) It’s a python script that I have running against profiles on a sql table on a schedule every 5 min (each iteration runs against 1 profile only. The next profile runs on the next iteration). It runs in order the following instaloader functions:

  • get_posts()
    • download_post()
  • get_tagged_posts()
    • download_post()
  • get_stories()
    • get_items()
      • download_storyitem()

Expected behavior A clear and concise description of what you expected to happen (even if it seems obvious). To run instaloader without raising 400 Bad Request exceptions which may be the reason or a result of my account being locked.

Error messages and tracebacks If applicable, add error messages and tracebacks to help explain your problem.

Job "update_instagram_profile (trigger: cron[year='*', month='*', day='*', hour='*', minute='*/5'], next run at: 2020-10-05 07:55:00 UTC)" raised an exception
Traceback (most recent call last):
  File "/workspace/environment/lib/python3.8/site-packages/apscheduler/executors/base.py", line 125, in run_job
    retval = job.func(*job.args, **job.kwargs)
  File "/workspace/social_network_apps/instagram/functions.py", line 155, in update_instagram_profile
    raise _e
  File "/workspace/social_network_apps/instagram/functions.py", line 99, in update_instagram_profile
    _instagram_profile_object = retrieve_instagram_profile(
  File "/workspace/social_network_apps/instagram/functions.py", line 10, in retrieve_instagram_profile
    _instagram_profile_object = instaloader.Profile.from_username(instaloader_object.context, db_profile_object.instagram_name)
  File "/workspace/environment/lib/python3.8/site-packages/instaloader/structures.py", line 560, in from_username
    profile._obtain_metadata()  # to raise ProfileNotExistException now in case username is invalid
  File "/workspace/environment/lib/python3.8/site-packages/instaloader/structures.py", line 604, in _obtain_metadata
    metadata = self._context.get_json('{}/'.format(self.username), params={})
  File "/workspace/environment/lib/python3.8/site-packages/instaloader/instaloadercontext.py", line 406, in get_json
    raise QueryReturnedBadRequestException("400 Bad Request")
instaloader.exceptions.QueryReturnedBadRequestException: 400 Bad Request

Instaloader version instaloader --version output. 4.5.3

Additional context Add any other context about the problem here. I will change the schedule to run every 7 min and see if the problem is the timer. (shouldn’t be since it has been running fine for months now. Maybe instagram changed something on their side?)

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:6
  • Comments:44 (3 by maintainers)

github_iconTop GitHub Comments

8reactions
AyluinReymaercommented, Oct 12, 2020

Ok, so I haven’t had any issues for the past few days.

Here is what I have done:

  • Setup my scheduler to only run instaloader functions on mid-day and mid-night for half of the target profiles in my sql table (currently 26), meaning it will run 13 on mid-day and another 13 on mid-night;
  • After creating the session file with instaloader, I went to instagram to confirm that the recent login was indeed performed by me. You can find this option under Login Activity under instagram settings;
  • Starting from 11:55 until at least 12:05 and 23:55 until at least 00:05, I don’t go to instagram in any platforms (phone, web browser or anything else). Let instaloader do it’s thing and when it’s done you are free to go.

I believe the last point is the dominant one as I believe instagram is currently checking for simultaneous active sessions and locking the account if an account matches this criteria. The best way to confirm this is if someone who is having the same issue, to not use instagram on the phone or web browser when instaloader is running.

2reactions
AyluinReymaercommented, Apr 22, 2022

@sotiris-bos I’m using the instaloader python module in a python script. Not the CLI.

Below is the full code of how I’m using instaloader and a cron scheduler.

It could use some optimization for sure, but it works so I didn’t bother with optimization.

You will need to install apscheduler which this uses to schedule cronjobs.

# Create a class to handle the cron schedule.
class Schedule():
    def __init__(self):
        self.day_of_week = "*"
        self.year = "*"
        self.month = "*"
        self.day = "*"
        self.hour = "8-23"
        self.minute = "*/30"

    def cron_to_dict(self):
        return {
            "day_of_week": self.day_of_week,
            "year": self.year,
            "month": self.month,
            "day": self.day,
            "hour": self.hour,
            "minute": self.minute
        }

    def __repr__(self):
        return '<Schedule (day_of_week=%r, year=%r, month=%r, day=%r, hour=%r, minute=%r)>' % (self.day_of_week, self.year, self.month, self.day, self.hour, self.minute)


# Create a class to handle the app creation and cron scheduler.
# It will create a few things and store them as properties so that it is easier to manage:
# - Instaloader instance
# - Cron scheduler
# - Cron job
# - Custom instaloader function that the cron job will call
class Instagram_App_Constructor():
    def __init__(self, instance_username, instance_session_path="/workspace/instaloader-session"):
        # Import the BackgroundScheduler which is used to create the cron job.
        from apscheduler.schedulers.background import BackgroundScheduler
        from instaloader import Instaloader
        from . import functions
        import atexit

        # Create the cron schedule with the class Schedule class we created above.
        self.schedule = Schedule()

        # Create the BackgroundScheduler which will be used to create the cron job.
        self.scheduler = BackgroundScheduler()

        # Define relevant properties to create the instaloader instance.
        self.instance_username = instance_username
        self.instance_session_path = instance_session_path

        # Define the function that the cron job will call
        self.instance_function = functions.update_instagram_profile

        # Create the instaloader instance.
        self.instaloader = Instaloader(
            compress_json = False,
            post_metadata_txt_pattern = "",
            filename_pattern = '{date}_{profile}_{owner_id}_{shortcode}',
            fatal_status_codes=[400,500]
        )

        # Load the instaloader session.    
        self.instaloader.load_session_from_file(username=instance_username, filename=instance_session_path)

        # Clean shutdown of the scheduler when the app is closed.
        atexit.register(lambda: self.scheduler.shutdown())

    # Create the cron job.
    # Define the function that the cron job will call.
    # Define the schedule the cron job will run.
    # Define the arguments that will be passed to the function in the kwargs parameter.
    def start_scheduler(self):
        self.job = self.scheduler.add_job(
            func=self.instance_function,
            trigger="cron",
            year=self.schedule.year,
            month=self.schedule.month,
            day=self.schedule.day,
            hour=self.schedule.hour,
            minute=self.schedule.minute,
            kwargs={
                "instaloader_object": self.instaloader
            }
        )

        return self.scheduler.start()

    # In case we change the schedule, we can update the cron job with the new schedule.
    def modify_schedule(self):
        self.job.reschedule('cron', **self.schedule.cron_to_dict())
        return self.job.trigger

    # In case we want to trigger instaloader manually, this will pause the scheduler, call the function and then resume the scheduler.
    def update_profile(self, id):
        self.job.pause()
        self.instance_function(self.instaloader, id=id)
        self.job.resume()

        return "insta profile with id '%r' updated at : %r" % (id, datetime.now().strftime("%d/%m/%Y %H:%M:%S"))

    def __repr__(self):
        return "<Instagram_App (instance_username=%r, next_run_time=%r)>" % (self.instance_username, self.job.next_run_time.strftime("%d/%m/%Y %H:%M"))


# Create the app and pass the username and optionally the session path to the constructor.
Instagram_App = Instagram_App_Constructor(app.config["instagram_username"])

if app.env == 'production':
    # Start the scheduler.
    Instagram_App.start_scheduler()

Read more comments on GitHub >

github_iconTop Results From Across the Web

My Instagram account 'has been temporarily locked ... - Quora
If your Instagram account has been blocked, you will need to log in to the instagram app and enter your username and password,...
Read more >
How to Fix “Your Account Has Been Temporarily Locked” on ...
Step 1: Submit the “My Instagram Account Has Been Deactivated” Form · Step 2: Send a Photo of the Code to Confirm You...
Read more >
3 Simple Ways to Unlock an Instagram Account - wikiHow
1. Using a third-party app with your Instagram account. If you were using an app that automatically likes, follows, unfollows, or performs other...
Read more >
How To Fix "Your Account Has Been ... - Punch 5 Media Limited
How to Fix “Your Account Has Been Temporarily Locked” on Instagram · STEP 1: Get The Correct Form · STEP 2: Fill Out...
Read more >
How To Fix a Temporarily Locked Instagram Account - ITGeared
Method #2: Fix Locked Instagram Profile by Filling a Form · Step #1: Search “My Instagram Account Has Been Deactivated” · Step #2:...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found