ping / instagram_private_api

A Python library to access Instagram's private API.
MIT License
2.95k stars 612 forks source link

edit_profile() HTTP Error 400: Bad Request #347

Open ajbenz18 opened 3 years ago

ajbenz18 commented 3 years ago

Please follow the guide below


Before submitting an issue, make sure you have:

Which client are you using?


Describe the Bug/Error:

When attempting to change the bio for an account using edit_profile() I get an HTTP Error 400. I'm not entirely sure if I'm using the external URL field correctly. Maybe this is the problem?

I am able to successfully connect using the examples, but this is the code that causes the error:

api.edit_profile('MY NAME', "THis is a test", "https://www.instagram.com/accounts/edit/", my_email, my_phone_number, '1')

Paste the output of python -V here:

3.7.7 (v3.7.7:d7c567b08f, Mar 10 2020, 02:56:16) \n[Clang 6.0 (clang-600.0.57)]

Code (removed definition of username, password, etc at top of code):

import json
import codecs
import datetime
import os.path
import logging
import argparse
import instagram_private_api

password = ""
username = ""
settings_file_path = ""
my_email = ""
my_phone_number = ""

try:
    from instagram_private_api import (
        Client, ClientError, ClientLoginError,
        ClientCookieExpiredError, ClientLoginRequiredError,
        __version__ as client_version)
except ImportError:
    import sys
    sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
    from instagram_private_api import (
        Client, ClientError, ClientLoginError,
        ClientCookieExpiredError, ClientLoginRequiredError,
        __version__ as client_version)

def to_json(python_object):
    if isinstance(python_object, bytes):
        return {'__class__': 'bytes',
                '__value__': codecs.encode(python_object, 'base64').decode()}
    raise TypeError(repr(python_object) + ' is not JSON serializable')

def from_json(json_object):
    if '__class__' in json_object and json_object['__class__'] == 'bytes':
        return codecs.decode(json_object['__value__'].encode(), 'base64')
    return json_object

def onlogin_callback(api, new_settings_file):
    cache_settings = api.settings
    with open(new_settings_file, 'w') as outfile:
        json.dump(cache_settings, outfile, default=to_json)
        print('SAVED: {0!s}'.format(new_settings_file))

if __name__ == '__main__':

    logging.basicConfig()
    logger = logging.getLogger('instagram_private_api')
    logger.setLevel(logging.WARNING)

    # args = parser.parse_args()
    # if args.debug:
    #     logger.setLevel(logging.DEBUG)

    print('Client version: {0!s}'.format(client_version))

    device_id = None
    try:

        #settings_file = args.settings_file_path
        if not os.path.isfile(settings_file_path):
            # settings file does not exist
            print('Unable to find file: {0!s}'.format(settings_file_path))

            # login new
            api = Client(
                username, password,
                on_login=lambda x: onlogin_callback(x, settings_file_path))
        else:
            with open(settings_file_path) as file_data:
                cached_settings = json.load(file_data, object_hook=from_json)
            print('Reusing settings: {0!s}'.format(settings_file_path))

            device_id = cached_settings.get('device_id')
            # reuse auth settings
            api = Client(
                username, password,
                settings=cached_settings)

    except (ClientCookieExpiredError, ClientLoginRequiredError) as e:
        print('ClientCookieExpiredError/ClientLoginRequiredError: {0!s}'.format(e))

        # Login expired
        # Do relogin but use default ua, keys and such
        api = Client(
            username, password,
            device_id=device_id,
            on_login=lambda x: onlogin_callback(x, settings_file_path))

    except ClientLoginError as e:
        print('ClientLoginError {0!s}'.format(e))
        exit(9)
    except ClientError as e:
        print('ClientError {0!s} (Code: {1:d}, Response: {2!s})'.format(e.msg, e.code, e.error_response))
        exit(9)
    except Exception as e:
        print('Unexpected Exception: {0!s}'.format(e))
        exit(99)

    # Show when login expires
    cookie_expiry = api.cookie_jar.auth_expires
    print('Cookie Expiry: {0!s}'.format(datetime.datetime.fromtimestamp(cookie_expiry).strftime('%Y-%m-%dT%H:%M:%SZ')))

    # Call the api
    results = api.user_feed('2958144170')
    assert len(results.get('items', [])) > 0

    print('All ok')

    api.edit_profile('MY NAME', "THis is a test", "https://www.instagram.com/accounts/edit/", my_email, my_phone_number, '1')

Error/Debug Log:

/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 /Users/ajb/instagramBot/example.py
Client version: 1.6.0
Reusing settings: askhd
Cookie Expiry: 2021-08-28T23:21:42Z
All ok
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/instagram_private_api/client.py", line 523, in _call_api
    response = self.opener.open(req, timeout=self.timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 531, in open
    response = meth(req, response)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 641, in http_response
    'http', request, response, code, msg, hdrs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 569, in error
    return self._call_chain(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 503, in _call_chain
    result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 649, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/ajb/instagramBot/example.py", line 122, in <module>
    api.edit_profile('AJ Bensman', "THis is a dteat", "https://www.instagram.com/accounts/edit/", 'ajbenz18@gmail.com', '5139261003', 1)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/instagram_private_api/endpoints/accounts.py", line 111, in edit_profile
    res = self._call_api('accounts/edit_profile/', params=params)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/instagram_private_api/client.py", line 527, in _call_api
    ErrorHandler.process(e, error_response)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/instagram_private_api/errors.py", line 122, in process
    if re.search(p, error_message_type):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 183, in search
    return _compile(pattern, flags).search(string)
TypeError: expected string or bytes-like object
Stupidoodle commented 2 years ago

Same

Stupidoodle commented 2 years ago

Turn on -debug for more infos, that fixed it for me, you have to put in phone number with countrycode and your proper email