subzeroid / instagrapi

🔥 The fastest and powerful Python library for Instagram Private API 2024
https://hikerapi.com/p/bkXQlaVe
MIT License
4.21k stars 667 forks source link

Input should be a valid datetime issue[BUG] #1736

Open SKbarbon opened 8 months ago

SKbarbon commented 8 months ago

Describe the bug First of all, this issue is appeared with vary set of functions in this package. But this is just one of them.

To Reproduce

from instagrapi import Client
import json, time

cl = Client()
instagram_data = json.loads(open("instagram_info.secret", encoding="utf-8").read())
cl.login(instagram_data['username'], instagram_data['password'], verification_code="163465")

# Get recipient user ID
# recipient = cl.user_id_from_username("kascoplus")

print(cl.direct_threads(amount=5))

Traceback

Traceback (most recent call last):
  File "/Users/**/Documents/GitHub/personal/instagram_bot_chating/main.py", line 11, in <module>
    print(cl.direct_threads(amount=5))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/**/Documents/GitHub/personal/instagram_bot_chating/venv/lib/python3.11/site-packages/instagrapi/mixins/direct.py", line 88, in direct_threads
    threads_chunk, cursor = self.direct_threads_chunk(
                            ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/**/Documents/GitHub/personal/instagram_bot_chating/venv/lib/python3.11/site-packages/instagrapi/mixins/direct.py", line 154, in direct_threads_chunk
    threads.append(extract_direct_thread(thread))
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/**/Documents/GitHub/personal/instagram_bot_chating/venv/lib/python3.11/site-packages/instagrapi/extractors.py", line 273, in extract_direct_thread
    data["messages"].append(extract_direct_message(item))
                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/**/Documents/GitHub/personal/instagram_bot_chating/venv/lib/python3.11/site-packages/instagrapi/extractors.py", line 333, in extract_direct_message
    return DirectMessage(**data)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/**/Documents/GitHub/personal/instagram_bot_chating/venv/lib/python3.11/site-packages/pydantic/main.py", line 164, in __init__
    __pydantic_self__.__pydantic_validator__.validate_python(data, self_instance=__pydantic_self__)
pydantic_core._pydantic_core.ValidationError: 2 validation errors for DirectMessage
user_id
  Input should be a valid string [type=string_type, input_value=56955225733, input_type=int]
    For further information visit https://errors.pydantic.dev/2.5/v/string_type
timestamp
  Input should be a valid datetime, dates after 9999 are not supported as unix timestamps [type=datetime_parsing, input_value=1704364263196060, input_type=int]
    For further information visit https://errors.pydantic.dev/2.5/v/datetime_parsing

Expected behavior It Just supposed to work and to do its job. Its not returning anything, only errors.

Screenshots If applicable, add screenshots to help explain your problem.

Desktop:

AndresQuiVal commented 8 months ago

same error i have, any solution you found??

alenko commented 8 months ago

same error i have, any solution you found??

in the mean time i did this, i dont know if original dev will or how will fix this, but i changed in lib this

in extractors.py i modified extract_direct_message(data)

and added def convert_timestamp(timestamp_str):

from datetime import datetime

def convert_timestamp(timestamp_str):
    try:
        # Convert the timestamp from microseconds to seconds
        timestamp = int(timestamp_str) / 1000000.0
        return datetime.fromtimestamp(timestamp)
    except ValueError as e:
        # Handle the exception if the timestamp is not a valid number
        print(f"Invalid timestamp: {timestamp_str}, Error: {e}")
        return None
    except OverflowError as e:
        # Handle the exception if the timestamp is out of range
        print(f"Timestamp out of range: {timestamp_str}, Error: {e}")
        return None

def extract_direct_message(data):
    data["id"] = data.get("item_id")
    if "replied_to_message" in data:
        data["reply"] = extract_reply_message(data["replied_to_message"])
    if "media_share" in data:
        ms = data["media_share"]
        if not ms.get("code"):
            ms["code"] = InstagramIdCodec.encode(ms["id"])
        data["media_share"] = extract_media_v1(ms)
    if "media" in data:
        data["media"] = extract_direct_media(data["media"])
    if "voice_media" in data:
        if "media" in data["voice_media"]:
            data["media"] = extract_direct_media(data["voice_media"]["media"])
    clip = data.get("clip", {})
    if 'timestamp' in data:
        data['timestamp'] = convert_timestamp(data['timestamp'])

    if clip:
        if "clip" in clip:
            # Instagram ¯\_(ツ)_/¯
            clip = clip.get("clip")
        data["clip"] = extract_media_v1(clip)
    xma_media_share = data.get("xma_media_share", {})
    if xma_media_share:
        data["xma_share"] = extract_media_v1_xma(xma_media_share[0])

    return DirectMessage(**data)
claell commented 8 months ago

Seems to be a duplicate of #1735