davidteather / TikTok-Api

The Unofficial TikTok API Wrapper In Python
https://davidteather.github.io/TikTok-Api
MIT License
4.52k stars 928 forks source link

[BUG] Error handling if user does not exist #1158

Open mi01 opened 4 weeks ago

mi01 commented 4 weeks ago

Describe the bug

I try to retrieve public user data for a list of TikTok accounts. This usually works fine, but there are some issues with this library, which should be fixed.

The buggy code

async with TikTokApi() as api:
    await api.create_sessions(
        ms_tokens=[ms_token],
        num_sessions=1,
        sleep_after=3,
        executable_path="/opt/google/chrome/google-chrome",
    )

    user = api.user(username=username)
    user_info = None
    try:
        user_info = await user.info()
        print(f"SUCCESS: {username}")
    except (KeyError, exceptions.InvalidResponseException, exceptions.EmptyResponseException, Exception) as e:
        print(f"ERROR: {e} :: https://www.tiktok.com/@{username} :: {user_info}")

Expected behavior

If the account does not exist, I expect to get a meaningful exception. But when running the code above for a non-existing account I get the following response from TikTok:

{"extra":{"fatal_item_ids":[],"logid":"...","now":1717514022000},"log_pb": "impr_id":"..."},"statusCode":10221,"status_code":0,"status_msg":"","userInfo":{}}

In my code example above this response triggers a KeyError instead of a meaningful exception. So I had a look into this library. make_request() in tiktok.py checks, if the result is None or an empty string or if we can decode the JSON or if status_code != 0.

https://github.com/davidteather/TikTok-Api/blob/5a249c4af8338967f61c0a090a37c4f0fd6c829c/TikTokApi/tiktok.py#L433-L451

None of this error conditions is true for this response. Then info() in user.py tries to extract data with__extract_from_data() not present in the response, so a KeyError is raised.

By the way, if the account does exist "statusCode": 0 is in the response.

But there is another issue, which makes it hard to distinguish between a non-existing account and this other case. When retrieving user data for several accounts, sometimes this error occurs:

2024-06-04 17:36:14,559 - TikTokApi.tiktok - ERROR - Got an unexpected status code: {'userInfo': {'user': {}, 'stats': {}, 'shareMeta': {}}}

And again in this case I get a KeyError instead of an meaningful exception, since none of the error conditions apply. For both cases user.info() return None by the way.

Thank you for this great library. But the error handling needs some updates, probably because TikTok slightly changed its API.

Desktop (please complete the following information):