diezo / Ensta

🔥 Fast & Reliable Python Package For Instagram API - 2024
https://bit.ly/ensta-discord
MIT License
372 stars 44 forks source link

HTTP Response not valid JSON #31

Closed owckie closed 12 months ago

owckie commented 12 months ago

Hey!

I'm writing a program to unfollow people I don't follow and the library was working for a while (until I unfollowed around 30 people) until I started seeing this error. I haven't made any changes to my code since I started running it & am using BaseHost with a sessionID as I've got an authenticator enabled on my account. Any advice on what could be going wrong? Happy to post snippets of my code if required.

Thanks in advance!


  File "/Users/z/Documents/Code/InstagramUnfollow/venv/lib/python3.11/site-packages/requests/models.py", line 971, in json
    return complexjson.loads(self.text, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/Cellar/python@3.11/3.11.5/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/Cellar/python@3.11/3.11.5/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/Cellar/python@3.11/3.11.5/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/z/Documents/Code/InstagramUnfollow/venv/lib/python3.11/site-packages/ensta/Guest.py", line 113, in profile
    response_json: dict = http_response.json()
                          ^^^^^^^^^^^^^^^^^^^^
  File "/Users/z/Documents/Code/InstagramUnfollow/venv/lib/python3.11/site-packages/requests/models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/z/Documents/Code/InstagramUnfollow/unfollow.py", line 105, in <module>
    host.unfollow(user)
  File "/Users/z/Documents/Code/InstagramUnfollow/venv/lib/python3.11/site-packages/ensta/BaseHost.py", line 169, in unfollow
    conversion_success, identifier = self._identifier(identifier, UID)
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/z/Documents/Code/InstagramUnfollow/venv/lib/python3.11/site-packages/ensta/BaseHost.py", line 413, in _identifier
    user_id = self.guest.get_uid(identifier)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/z/Documents/Code/InstagramUnfollow/venv/lib/python3.11/site-packages/ensta/Guest.py", line 183, in get_uid
    response: Profile | None = self.profile(username, __session__)
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/z/Documents/Code/InstagramUnfollow/venv/lib/python3.11/site-packages/ensta/Guest.py", line 179, in profile
    raise NetworkError("HTTP Response is not a valid JSON.")
ensta.lib.Exceptions.NetworkError: HTTP Response is not a valid JSON.```
diezo commented 12 months ago

Can you please show me your code?

owckie commented 12 months ago

Sure! It's not very well put together just warning, I've only put it together over the last hour or so.


from ensta import BaseHost
from json import dump, load
from os import path

# file for keeping names i didnt unfollow
no_unfollow = 'did_not_unfollow.json'

# read from list
def readList(filename):
    # read into lines
    with open(filename) as f:
        items = f.readlines()

    # strip the newline char '\n'
    for index, item in enumerate(items):
        items[index] = item.strip()

    return items

# write a list to a file
def writeList(filename, content, ifAppend):
    # placeholder for all of the names, including the ones already mentioned
    full_file = []
    if ifAppend:
        # if file already exists, read the names and add them to full_file
        if path.isfile(filename):
            existing = readList(filename)

            for user in existing:
                full_file.append(user)

    for user in content:
        full_file.append(user)

    with open(filename, 'w') as f:
        for item in full_file:
            # write the item and a new space
            f.write(f'{item}\n')

# Writes the users I chose not to unfollow as json as 
# {username: username, reason: reason_not_to_unfollow}
# Expects the file declared in no_unfollow variable to exist (ie: did_not_unfollow.json)
# This file is used for tracking the pages I chose not to unfollow for any reason
# If there is already a list of users I chose not to unfollow, don't overwrite the 
# file, but append to it.
def write_not_unfollowed_users(usernames_not_unfollowed):
    # first check if the file exists
    if path.isfile(no_unfollow):
        print('Detected: A file exists containing account I chose not to follow.')
    else: 
        raise Exception(f"A file for tracking account I chose not to follow does \
                        not exist. Create a file called '{no_unfollow}'")

    # file exists, read into it
    with open(no_unfollow, 'r') as existing_no_follow:
        existing_users = load(existing_no_follow)

    full_list = existing_users + usernames_not_unfollowed

   # write to the file 
    with open(no_unfollow, 'w') as json_file:
        dump(full_list, json_file, indent=4)

def decide_if_unfollow(username):
    decision = input(f'{username}: y Unfollow - n DONT unfollow - l Link to page - ')
    if decision == 'y':
        print(f'Unfollowed {username}')
        unfollowed.append(username)
        print()
        return True
    elif decision == 'n': 
        reason = input('Reason?')
        print(f'Did not unfollow: "user" as {reason}')
        not_unfollowed_users.append(
            {
                'userame': username, 
                "reason": reason
            })
        return False
    elif decision == 'l':
        print(f'Link: http://instagram.com/{username}')
        decide_if_unfollow(username)

    else: 
        print('Choose an option! y or n')
        decide_if_unfollow(username)

# __________ End Functions _________

# Use a sessionID as I have an authenticator enabled
sessionID = '<ommited>'
host = BaseHost(sessionID)
username = '<ommited>'

consider_unfollowing = readList('they_dont_follow_back.txt')
# people that I've unfollowed
unfollowed = []
not_unfollowed_users = []

for user in consider_unfollowing:
    decision = decide_if_unfollow(user)
    if decision:
        host.unfollow(user)
    write_not_unfollowed_users(not_unfollowed_users)
    writeList('unfollowed.txt', unfollowed, True)
    consider_unfollowing.remove(user)
    writeList('they_dont_follow_back.txt', consider_unfollowing, False)```
owckie commented 12 months ago

Can you please show me your code?

Goal of my code is to iterate the people I'm following but not following me and give me an option to unfollow, don't unfollow or link their profile (y, n or l). I then use the library to unfollow them and write to the lists I have as text files with newline separators.

Hope this helps you understand what is going on if its not too clear.

diezo commented 12 months ago

I've understood what you're trying to do here. Just realised there's a tiny bug in the BaseHost class on line 413. Please wait while I fix it.

diezo commented 12 months ago

i've fixed the bug and everything should now work as expected. please upgrade ensta using: pip install ensta==5.0.1

please do let me know if that worked. thanks

owckie commented 12 months ago

Bug fixed! Really appreciate for the fast response, thank you.

diezo commented 12 months ago

You're welcome!

I would really appreciate if you star this repository so that more developers know about ensta.

Thankyou!