Instagram ошибка 429

I do an application which deletes comments on Instagram since Saturday 31st of October, I get this response when I use API to delete comments: {"error_type":"OAuthRateLimitException","code":429,"

I do an application which deletes comments on Instagram since Saturday 31st of October, I get this response when I use API to delete comments:

{"error_type":"OAuthRateLimitException","code":429,"error_message":"The maximum number of requests per hour has been exceeded...."}}.

I see that they did a modification one year ago for the limits of the number of requests, but I don’t have this error during this execution since before the update.
How to avoid it?
Is it necessary to retrieve a new token or is there an another way to avoid it?

trotta's user avatar

trotta

1,2331 gold badge16 silver badges23 bronze badges

asked Nov 2, 2015 at 12:42

user3323940's user avatar

0

Use a secure API request to get a higher limit. I think you missed this email from Instagram:

When we announced our publishing guidelines for likes/relationship
actions, we also introduced a new technique to sign API requests. As
part of this announcement we set a deprecation date for the previous
signed-headers functionality to Sept 1, 2015.

This email is to let you know that support for signed-headers has now
been deprecated. We know that a number of developers (including your
company) are still relying on this option, and have whitelisted your
client_id for an extended period. Please plan the migration to
securing your application with signed-requests as soon as possible.
You can learn more about this feature here:
https://instagram.com/developer/secure-api-requests/.

The extended support will end on Nov 1 2015. You will see your
rate-limits for publishing likes/follows/comments reduced if you
haven’t migrated after this date.

tripleee's user avatar

tripleee

170k31 gold badges261 silver badges306 bronze badges

answered Nov 2, 2015 at 19:36

krisrak's user avatar

krisrakkrisrak

12.8k3 gold badges31 silver badges46 bronze badges

I do an application which deletes comments on Instagram since Saturday 31st of October, I get this response when I use API to delete comments:

{"error_type":"OAuthRateLimitException","code":429,"error_message":"The maximum number of requests per hour has been exceeded...."}}.

I see that they did a modification one year ago for the limits of the number of requests, but I don’t have this error during this execution since before the update.
How to avoid it?
Is it necessary to retrieve a new token or is there an another way to avoid it?

trotta's user avatar

trotta

1,2331 gold badge16 silver badges23 bronze badges

asked Nov 2, 2015 at 12:42

user3323940's user avatar

0

Use a secure API request to get a higher limit. I think you missed this email from Instagram:

When we announced our publishing guidelines for likes/relationship
actions, we also introduced a new technique to sign API requests. As
part of this announcement we set a deprecation date for the previous
signed-headers functionality to Sept 1, 2015.

This email is to let you know that support for signed-headers has now
been deprecated. We know that a number of developers (including your
company) are still relying on this option, and have whitelisted your
client_id for an extended period. Please plan the migration to
securing your application with signed-requests as soon as possible.
You can learn more about this feature here:
https://instagram.com/developer/secure-api-requests/.

The extended support will end on Nov 1 2015. You will see your
rate-limits for publishing likes/follows/comments reduced if you
haven’t migrated after this date.

tripleee's user avatar

tripleee

170k31 gold badges261 silver badges306 bronze badges

answered Nov 2, 2015 at 19:36

krisrak's user avatar

krisrakkrisrak

12.8k3 gold badges31 silver badges46 bronze badges

Содержание

  1. ОШИБКА: Код 429
  2. ОШИБКА: Код 429
  3. Что делать, если Instagram не дал доступ к API? Дополнение
  4. Установка
  5. Как ей пользоваться?
  6. [Instagram] HTTPError 429 (Too Many Requests) #22382
  7. Comments
  8. Checklist
  9. Verbose log
  10. Description
  11. 429 [Too Many Requests] from Instagram #319
  12. Comments

ОШИБКА: Код 429

Работая с теми или иными функциями программы, можно столкнуться с кодом ошибки 429. В разных задачах это может указывать на разные ограничение схожего смысла. Рассмотрим два вида ошибок с таким кодом подробнее.

ЛИМИТ НА ЗАПРОСЫ ОТ ИМЕНИ АККАУНТА

Во время сбора аудитории, у вас может возникнуть ситуация, когда сбор начинает постоянно прерываться, а в логах указано сообщение вида: «[ERROR]:[429 — на всех используемых технических аккаунтах превышен часовой лимит на запросы]«. Данное сообщение означает, что объём запросов со всех технических аккаунтов превысил допустимый лимит. В разных функциях этот лимит может менятся. Чаще всего этот лимит равен 5000 запросов в час, для некоторых функций он может быть равен 200 запросов в час. Это ограничение Instagram накладывает на любые способы работы со своим API в том числе и для своего собственного мобильного приложения.

Чтобы решить эту проблему можно взять другие технические аккаунты или дать отдохнуть текущим. Если планируется длительный непрерывный сбор аудитории, то можно взять более обширную группу технических аккаунтов и настроить переключение между ТА на каждый 32ой запрос. Это позволит распределить нагрузку на каждый из ТА во времени и обойти лимит, если за час каждый из ТА не превысит допустимый лимит по запросам.

По умолчанию в программе всюду выставлено безопасное значение в 4990 запросов. А для тех функций, где проблема лимитов стоит особенно остро — выставлено переключение между ТА на каждый 32ой запрос.

ЛИМИТ НА ЗАПРОСЫ С IP

Также существует лимит на число запросов в единицу времени в пределах каждого IP. Если вы посылаете запросы к серверу Instagram с того или иного IP слишком часто, то это также может привести к временному отказу в выполнении тех или иных запросов с того или иного IP.

В отличие от предыдущей, данный тип блокировки выдаётся на короткое время (в пределах 1-2 минут) и большинство задач на сбор или фильтрацию аудитории умеют переходить в режим ожидания при обнаружении такого типа блокировки. Тем не менее, вы можете столкнуться с функцией, которая не подразумевает наличие такого режима ожидания в качестве реакции на «Ошибку 429». Например, если вы превысили лимит на запросы с того или иного IP при использовании фильтра, а затем пытаетесь выполнить полную инициализацию Instagram-аккаунта с заблокированного IP, то получите на экран примерно такое сообщение, как указано на скриншоте ниже.

«Ошибка 429» во время инициализации Instagram-аккаунта.

В этом случае просто подождите 1-2 минуты, а затем попробуйте выполнить инициализацию аккаунта снова.

Источник

ОШИБКА: Код 429

Работая с теми или иными функциями программы, можно столкнуться с кодом ошибки 429. В разных задачах это может указывать на разные ограничение схожего смысла. Рассмотрим два вида ошибок с таким кодом подробнее.

ЛИМИТ НА ЗАПРОСЫ ОТ ИМЕНИ АККАУНТА

Во время сбора аудитории, у вас может возникнуть ситуация, когда сбор начинает постоянно прерываться, а в логах указано сообщение вида: «[ERROR]:[429 — на всех используемых технических аккаунтах превышен часовой лимит на запросы]«. Данное сообщение означает, что объём запросов со всех технических аккаунтов превысил допустимый лимит. В разных функциях этот лимит может менятся. Чаще всего этот лимит равен 5000 запросов в час, для некоторых функций он может быть равен 200 запросов в час. Это ограничение Instagram накладывает на любые способы работы со своим API в том числе и для своего собственного мобильного приложения.

Чтобы решить эту проблему можно взять другие технические аккаунты или дать отдохнуть текущим. Если планируется длительный непрерывный сбор аудитории, то можно взять более обширную группу технических аккаунтов и настроить переключение между ТА на каждый 32ой запрос. Это позволит распределить нагрузку на каждый из ТА во времени и обойти лимит, если за час каждый из ТА не превысит допустимый лимит по запросам.

По умолчанию в программе всюду выставлено безопасное значение в 4990 запросов. А для тех функций, где проблема лимитов стоит особенно остро — выставлено переключение между ТА на каждый 32ой запрос.

ЛИМИТ НА ЗАПРОСЫ С IP

Также существует лимит на число запросов в единицу времени в пределах каждого IP. Если вы посылаете запросы к серверу Instagram с того или иного IP слишком часто, то это также может привести к временному отказу в выполнении тех или иных запросов с того или иного IP.

В отличие от предыдущей, данный тип блокировки выдаётся на короткое время (в пределах 1-2 минут) и большинство задач на сбор или фильтрацию аудитории умеют переходить в режим ожидания при обнаружении такого типа блокировки. Тем не менее, вы можете столкнуться с функцией, которая не подразумевает наличие такого режима ожидания в качестве реакции на «Ошибку 429». Например, если вы превысили лимит на запросы с того или иного IP при использовании фильтра, а затем пытаетесь выполнить полную инициализацию Instagram-аккаунта с заблокированного IP, то получите на экран примерно такое сообщение, как указано на скриншоте ниже.

«Ошибка 429» во время инициализации Instagram-аккаунта.

В этом случае просто подождите 1-2 минуты, а затем попробуйте выполнить инициализацию аккаунта снова.

Источник

Что делать, если Instagram не дал доступ к API? Дополнение

Здравствуйте ещё раз! Я прочёл её и мне показалось, что её можно продолжить.

Ни для кого не секрет, что самая популярная и прибыльная площадка для рекламы, бизнеса и прочего — Instagram. Почему им стал именно сервис, в котором по началу можно было загружать только картинки определённого размера (соотношение сторон имеется ввиду) и не было абсолютно ничего, что было в тогдашних соцсетях — совсем непонятно, но факт есть факт. Ввиду чего все стараются проникнуть на площадку Instagram и захватить оттуда наибольшее количество аудитории, и делают, это, конечно же, не вручную. А за этим следует, что Instagram жёстко блокирует доступ для ботов, спамеров и прочему, дабы сеть оставалась чистой.

  1. Самые полезные функции (постинг и удаление постов) доступны только из мобильного приложения Instagram, эмуляция запросов сложна, так как надо вытащить из приложения ключ, который с каждой новой версией обновляется.
  2. Web-версия обрезана, но радует, что в ней есть возможность лайкать, комментировать и удалять комментарии
  3. Есть API, но процедура его получения удручающе долгая и спамерам и ботам такой путь точно не светит. Плюс было много моментов, когда соглашения в API менялись, что не всегда удобно.

Хоть я и связался с Instagram не для того, чтобы сделать очередного спам-бота, который может подписываться и лайкать, но возиться с получением Instagram API мне ну очень не хотелось, поэтому пришлось написать собственную библиотеку для взаимодействия с Instagram.

Хочется сказать, что работать с Web-версией Instagram очень даже приятно по двум причинам:

1. О любой страничке можно получить краткую информацию, если отправить GET запрос вида:

И ответом является JSON с доступной информацией, первыми 10 постами странички и прочим. Очень приятно.

2. Если же краткой информации не хватает, то тут есть ещё одна приятная новость. Дозагрузить фоточки, подписки, комментарии можно со помощью определённого запроса вида

, где в variables передаются переменные для обработки в формате JSON. Ответом также является JSON. Да и вообще, очевидно, что работает это всё на GraphQL, так что чтобы понять, как обрабатываются запросы, можно даже погуглить.

На основе данных знаний и построена вся библиотека. Я вкратце опишу, как её можно использовать, может, кому-то пригодится. Кстати, я там в репозитории указал лицензию BSD 3. Подскажите, может, мне стоит её поменять, чтобы не было никаких трудностей?

Установка

Устанавливать её не надо. Точнее, мне было лень прописывать всякие setup.py или упаковывать, когда библиотека состоит всего из одного файла. Поэтому там просто файл instagram.py, который подключается так:

Как ей пользоваться?

Взаимодействие с Instagram возможно либо с авторизацией, либо без. Без авторизации отсутствуют функции просмотра подписок и подписчиков, и, очевидно, невозможно что-то лайкнуть, что-то откомментировать и так далее. Единственные ограничения с авторизацией: это невозможно выкладывать посты и удалять их.

Приведу пример взаимодействия без авторизации:

Как вы поняли, данный скрипт прогружает информацию о странице Марка Цукерберга, загружает последние 100 постов с его странице и выводит их на экран.

Хочу сказать, что если бы я не написал

то выполнить загрузку постов не получилось бы, так как никакой информации о странице Цукерберга известно не было.

А вот пример с авторизацией:

Это, так называемый Hello, world!. Или быстрый старт.

А теперь расскажу подробнее:

Instagram, на самом деле, имеет всего 6 сущностей:

  1. Аккаунт
  2. Пост
  3. Геолокация
  4. Комментарий
  5. Хэштег
  6. Сторис

Всё остальное — это просто списки этих сущностей, такие как лайки, подписки, подписчики и прочее. И для каждой сущности есть свой класс. Для аккаунтов — Account, постов — Media, геолокаций — Location, комментариев — Comment, хэштегов — Tag, историй — Story. И каждый из них (кроме комментариев) нужно обновить, прежде чем работать с ним. То есть если хочется загрузить все свои посты, пролайкать их и получить список геолокаций, то нужно выполнить следующее:

А если позже надо получить последние 10 постов по определённой геолокации, то надо будет сделать следующее:

Пришлось вынести функцию обновления аккаунта из инициализации, так как при необходимости получить всех подписчиков, например, программа бы обновляла каждый из аккаунтов, а это нехорошо.

Библиотека основана на библиотеке requests, и одной из фишек я считаю то, что в методы также можно передать дополнительные параметры для requests. Такая идея пришла ко мне, когда я первый раз получил 429 ошибку от Instagram. Нужно было использовать прокси.

Например, можно сделать так:

где 127.0.0.1:80 — можно указать свой прокси

Также ещё одной фишкой, я думаю, может являться перехват ошибок.

В классах Agent и AgentAccount (те, что и производят общение с Instagram) есть словарь, организованный как дерево, он называется exception_actions. В нём в виде ключей хранятся классы исключений, а в виде значений — функции. Если вдруг произошла какая-то ошибка, она перехватывается и выполняется функция из словаря. Этой функции передаётся объект исключения и параметры, с которыми выполнялся запрос. Она может выполнить какое-то действие и вернуть изменённые (или нет) параметры запроса. Выполнение запроса повторится снова. И будет повторятся столько раз, сколько указано в параметре Agent.repeats. По умолчанию стоит 1.

А ещё можно не беспокоиться о переполнении памяти.

У класса каждой сущности есть словарь, в котором хранятся все объекты данного класса (или объекты подкласса даже). Таким образом, если Вы случайно создадите, например, аккаунт, который уже был создан, конструктор вернёт вам ссылку на ранее созданный аккаунт.

Если вы случайно пропустили ссылку на репозиторий в тексте, то вот она ещё раз.

И напоследок скажу, что из-за некоторых решений появились и некоторые проблемы:

  1. Например, проблема при повторном создании объекта. Если вдруг вы захотите использовать аккаунт как рабочий и взаимодействовать через него, а он уже ранее был создан как обычный аккаунт, то создать его снова не получиться. Пока я не знаю, как это решить.
  2. Перехват ошибок иногда ведёт себя очень странно и не до конца протестирован.

Я очень надеюсь, что, может быть, данное решение кому-нибудь пригодится, надеюсь на любые полезные комментарии и на помощь в допиливании этой штуки. В указанной мною статье был приведён пример такого скрипта на PHP, но он занимался только сбором информации и, по-моему, он работал только со старой версией веб-нитерфейса Instagram.

Источник

[Instagram] HTTPError 429 (Too Many Requests) #22382

Checklist

  • I’m reporting a broken site support
  • I’ve verified that I’m running youtube-dl version 2019.09.12.1
  • I’ve checked that all provided URLs are alive and playable in a browser
  • I’ve checked that all URLs and arguments with special characters are properly quoted or escaped
  • I’ve searched the bugtracker for similar issues including closed ones

Verbose log

Description

Trying to download an Instagram user’s videos, youtube-dl tries to get the JSON pages one at a time, causing Instagram to give an HTTP too many requests error eventually. I have seen that youtube-dl fixed this issue by downloading all page data in one request, but that doesn’t seem to be the case here.

I am terribly sorry if this is a duplicate issue. If there is something I can do to fix the issue, I would gladly help.

The text was updated successfully, but these errors were encountered:

I ran into this issue as well today in the newest version with youtube (2019.10.16)

I wonder if this is related to my issue with the only difference being that I get the error from youtube downloads.

EDIT see this: #21729 (comment)

I was experimenting last night, and I was able to (unofficially and hackish-ly) fix the problem by editing the code.

Add the following code on /usr/lib/python3.7/site-packages/youtube_dl/extractor/common.py (in case of Arch Linux, I don’t know about Windows) on line #627 to make it look like this;

(make sure to follow the indentation, since this is Python)

This is a dirty hack, and adds a 4-second delay before every download, be it metadata download, page download, or actual video download. I tried smaller delays, but 4 works the best. This prevents Instagram from limiting our access. This will also limit downloads from other websites such as YouTube, so this is only a temporary fix and should be removed when not needed. Rather, the developers should turn this into a command switch to enable or disable at will.

Also, another reminder: be sure to add -i switch because sometimes, there will be some 404 Not Found videos on Instagram. Starting from scratch again might take a very long time, so better just ignore videos that can’t be downloaded.

Edit: I will try to make a pull request to add a command line switch to add delays before downloading and fix the issue officially and publicly.

Источник

429 [Too Many Requests] from Instagram #319

On one of my sites, I get 429 error on requests to ACCOUNT_PAGE or ACCOUNT_JSON_INFO. Other queries pass without problems. Very similar to ban.
Has anyone else come across?
Is there another way to get user_id?

The text was updated successfully, but these errors were encountered:

Response code is 429

They changed the way you pass the variables.
Now there’s a part of the URI that needs to be sent in json format, also, there’s a new var called query_hash being sent together.

I adapted the URL in my code for that and it worked fine.

@th4deu code example, please.

@th4deu up question, please example code, where get query_hash or how generate?

Tests shows what if many query to link 2, anytime response rate limit, but link 1 not noticed

@aik27 and @qunn , they just replaced the «query_id» for «query_hash».
Since I’ve been testing, its value doesn’t change. Here’s an example of the called URI (i’m using my own method to call it):

$url_graph = ‘https://www.instagram.com/graphql/query/’; $variables = rawurlencode(‘<«shortcode»:»‘.$code.'», «first»:»1000″, «after»: «‘.$nextPageCode'»>‘); $url_graph_query = $url_graph . ‘?query_hash=33ba35852cb50da46f5b5e889df7d159&variables=’.$variables’;

Anyway, i’ve been monitoring my website calls to Instagram «API» yesterday and the rate limit is still being applied, but, since there are a lot of API calls, I’m studying the idea of changing the server’s IP each hour to avoid the rate limit. Its limit is being renewed each hour.

@th4deu Thank you! Your solution a little better, i’m took note your solution, but now i replace in Endpoints.php COMMENTS_BEFORE_COMMENT_ID_BY_CODE old url to my https://www.instagram.com/p/<>/?__a=1 and other code fix, result no problem, after 30 minutes many queries no rate limits.

And my solution for change IP, cURL + proxy socks5 or ipv6, and i serializend array to proxy, i have 10 in list, and random i get proxy, if 429 i take next in array, and this action in round by while do

@qunn, for the first query your endpoint works, but how are you doing for the other ones?

Because for the first query, it was already working for me, but the second one ahead was giving me rate limit error after some queries.

@th4deu this url i only use for function getMediaCommentsByCode() in Instagram.php, and i modified function where $jsonResponse[‘data’] to $jsonResponse[‘graphql’] and other replace where use [‘data’] in this function, and i change in Endpoints.php const COMMENTS_BEFORE_COMMENT_ID_BY_CODE to this url https://www.instagram.com/p/<>/?__a=1

It’s all what i do, and work is fine, no rate limits and i not use proxyes more 4 hours))) may be i don’t understand your question, what you mean first query, this function or other function?

Источник

@welcomemax

On one of my sites, I get 429 error on requests to ACCOUNT_PAGE or ACCOUNT_JSON_INFO. Other queries pass without problems. Very similar to ban.
Has anyone else come across?
Is there another way to get user_id?

@liamka

Same

Response code is 429

@th4deu

They changed the way you pass the variables.
Now there’s a part of the URI that needs to be sent in json format, also, there’s a new var called query_hash being sent together.

I adapted the URL in my code for that and it worked fine.

@aik27

@qunn

@th4deu up question, please example code, where get query_hash or how generate?

@qunn

@th4deu

@qunn

@th4deu Thank you! Your solution a little better, i’m took note your solution, but now i replace in Endpoints.php COMMENTS_BEFORE_COMMENT_ID_BY_CODE old url to my https://www.instagram.com/p/{{shortcode}}/?__a=1 and other code fix, result no problem, after 30 minutes many queries no rate limits.

And my solution for change IP, cURL + proxy socks5 or ipv6, and i serializend array to proxy, i have 10 in list, and random i get proxy, if 429 i take next in array, and this action in round by while do

@th4deu

@qunn, for the first query your endpoint works, but how are you doing for the other ones?

Because for the first query, it was already working for me, but the second one ahead was giving me rate limit error after some queries.

@qunn

@th4deu this url i only use for function getMediaCommentsByCode() in Instagram.php, and i modified function where $jsonResponse[‘data’] to $jsonResponse[‘graphql’] and other replace where use [‘data’] in this function, and i change in Endpoints.php const COMMENTS_BEFORE_COMMENT_ID_BY_CODE to this url https://www.instagram.com/p/{{shortcode}}/?__a=1

It’s all what i do, and work is fine, no rate limits and i not use proxyes more 4 hours))) may be i don’t understand your question, what you mean first query, this function or other function?

@RainGrid

@qunn , you can only take a limited number of comments from the first query. has_next_page == true means that the post has more comments than can be taken from the 1st query.

@qunn

@RainGrid, yes, you right, i try find solutions…) but now this what I need for my project, I’m not stop seek solution for more queries, but this work without 429 limit)

@adiv-phpian

There’s a way to avoid rate limit, I can able to retrieve 100K likes without any problem. All we need to do is send some prior requests to Instagram to avoid getting rate limit error.

@imkimchi

@muthu-kc what do you exactly mean by sending prior requests? do you just send request to see if response would be 429 and wait for some minutes to send again?

@adiv-phpian

@imkimchi You need to use mobile api cookies with web api. by that way you can avoid rate limits.

@imkimchi

@muthu-kc that’s interesting! how can I get mobile api cookies on pc though?

@tawfek

@imkimchi You need to use mobile api cookies with web api. by that way you can avoid rate limits.

how can i use mobile api cookies and use it with web api endpoint
do u mean some thing like this or what ?
$instagram->setUserAgent(«Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; 909) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537»);

i’m solliciting you today because i’ve a problem with selenium.
my goal is to make a full automated bot that create an account with parsed details (mail, pass, birth date…) So far, i’ve managed to almost create the bot (i just need to access to gmail and get the confirmation code).

My problem is here, because i’ve tried a lot of things, i have a Failed to load resource: the server responded with a status of 429 ()
So, i guess, instagram is blocking me.
how could i bypass this ?

asked Nov 10, 2020 at 12:41

timogo's user avatar

2

The answer is in the description of the HTTP error code. You are being blocked because you made too many requests in a short time.

Reduce the rate at which your bot makes requests and see if that helps. As far as I know there’s no way to «bypass» this check by the server.

Check if the response header has a Retry-After value to tell you when you can try again.

answered Nov 10, 2020 at 12:48

Tony's user avatar

TonyTony

9,5383 gold badges50 silver badges73 bronze badges

Status code of 429 means that you’ve bombarded Instagram’s server too many times ,and that is why Instagram has blocked your ip.

This is done mainly to prevent from DDOS attacks.

Best thing would be to try after some time ( there might be a Retry-After header in the response).

Also, increase the time interval between each request and set the specific count of number of requests made within a specified time (let’s say 1 hr).

answered Nov 10, 2020 at 12:54

demouser123's user avatar

demouser123demouser123

3,9727 gold badges47 silver badges81 bronze badges

Retry-After header is the best practice. However, there’s no such response header in this scenario.

answered Nov 4, 2022 at 13:30

pruna's user avatar

prunapruna

11 bronze badge

2

Понравилась статья? Поделить с друзьями:
  • Instagram не могу войти ошибка
  • Instagram как изменить имя аккаунта
  • Instagram изменить имя пользователя как
  • Instagram выдает ошибку при входе
  • Instagram user not found error