Created
January 5, 2024 18:14
-
-
Save aandergr/35ad3881e726e2be8925cf09e719a68b to your computer and use it in GitHub Desktop.
Get Instagram comments with Instaloader via iPhone API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
from typing import Iterable | |
from instaloader import ( | |
PostCommentAnswer, | |
Post, | |
PostComment, | |
Profile, | |
InstaloaderContext, | |
) | |
def get_comments(context: InstaloaderContext, post: Post) -> Iterable[PostComment]: | |
def _query(min_id=None): | |
pagination_params = {"min_id": min_id} if min_id is not None else {} | |
return context.get_iphone_json( | |
f"api/v1/media/{post.mediaid}/comments/", | |
{ | |
"can_support_threading": "true", | |
"permalink_enabled": "false", | |
**pagination_params, | |
}, | |
) | |
def _answers(comment_node): | |
def _answer(child_comment): | |
return PostCommentAnswer( | |
id=int(child_comment["pk"]), | |
created_at_utc=datetime.utcfromtimestamp(child_comment["created_at"]), | |
text=child_comment["text"], | |
owner=Profile.from_iphone_struct(context, child_comment["user"]), | |
likes_count=child_comment["comment_like_count"], | |
) | |
child_comment_count = comment_node["child_comment_count"] | |
if child_comment_count == 0: | |
return | |
preview_child_comments = comment_node["preview_child_comments"] | |
if child_comment_count == len(preview_child_comments): | |
yield from ( | |
_answer(child_comment) for child_comment in preview_child_comments | |
) | |
return | |
pk = comment_node["pk"] | |
answers_json = context.get_iphone_json( | |
f"api/v1/media/{post.mediaid}/comments/{pk}/child_comments/", | |
{"max_id": ""}, | |
) | |
yield from ( | |
_answer(child_comment) for child_comment in answers_json["child_comments"] | |
) | |
def _paginated_comments(comments_json): | |
for comment_node in comments_json.get("comments", []): | |
yield PostComment( | |
id=int(comment_node["pk"]), | |
created_at_utc=datetime.utcfromtimestamp(comment_node["created_at"]), | |
text=comment_node["text"], | |
owner=Profile.from_iphone_struct(context, comment_node["user"]), | |
likes_count=comment_node["comment_like_count"], | |
answers=_answers(comment_node), | |
) | |
next_min_id = comments_json.get("next_min_id") | |
if next_min_id: | |
yield from _paginated_comments(_query(next_min_id)) | |
yield from _paginated_comments(_query()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment