79275447

Date: 2024-12-12 14:21:21
Score: 5.5
Natty: 4
Report link

hey can someone help me i am not able to get commnets data from instagram

this is my code files 1) @socialRouter.get("/insta/connect/{state}") async def connect_instagram(state: str): try: # Define Instagram-specific scopes scopes = [ "instagram_business_basic", "instagram_business_manage_messages", "instagram_business_manage_comments", "instagram_business_content_publish" ]

    # Use the ngrok URL for redirect
    redirect_uri =NGROK_URI_INSTA
    
    params = {
        "client_id": INSTAGRAM_CLIENT_ID,
        "redirect_uri": redirect_uri,
        "state": state,
        "scope": ",".join(scopes),
        "response_type": "code",
        "enable_fb_login": "0",
        "force_authentication": "1"
    }
    
    auth_url = f"https://www.instagram.com/oauth/authorize?{urllib.parse.urlencode(params)}"
    return {"redirect_url": auth_url}

except Exception as e:
    raise HTTPException(status_code=400, detail=f"Error getting Instagram authorization URL: {str(e)}")

@socialRouter.get('/instagram/posts/analytics/{userId}') async def getInstagramPostsAnalytics(userId: str): try: # Get the user's Instagram account details from MongoDB social_account = await database.get_collection('socialaccounts').find_one({ "userid": userId, "accounts.alias": "insta" })

    if not social_account:
        raise HTTPException(status_code=404, detail="Instagram account not found")
        
    # Find the Instagram account in the accounts array
    instagram_account = next(
        (acc for acc in social_account['accounts'] if acc['alias'] == 'insta'), 
        None
    )
    
    if not instagram_account or not instagram_account.get('linked'):
        raise HTTPException(
            status_code=400, 
            detail="Instagram account not connected"
        )

    access_token = instagram_account['accessToken']
    instagram_user_id = instagram_account['uid']

    async with httpx.AsyncClient() as client:
        # Get user's media
        media_response = await client.get(
            f"https://graph.instagram.com/v21.0/{instagram_user_id}/media",
            params={
                "access_token": access_token,
                "fields": "id,caption,media_type,media_url,thumbnail_url,permalink,timestamp,like_count,comments_count",
                "limit": 50  # Instagram API limit
            }
        )

        if media_response.status_code != 200:
            error_data = media_response.json()
            print(f"Instagram API Error: {error_data}")
            raise HTTPException(
                status_code=media_response.status_code,
                detail=f"Failed to fetch Instagram posts: {error_data.get('error', {}).get('message', 'Unknown error')}"
            )

        posts_data = media_response.json().get('data', [])
        analytics_data = []

        # Process each post
        for post in posts_data:
            try:
                # Get comments for each post
                comments_response = await client.get(
                    f"https://graph.instagram.com/v21.0/{post['id']}/comments",
                    params={
                        "access_token": access_token,
                        "fields": "id,text,timestamp,username,replies{id,text,timestamp,username}",
                        "limit": 50
                    }
                )
                
                comments_data = comments_response.json().get('data', []) if comments_response.status_code == 200 else []

                # Parse timestamp
                created_time = datetime.strptime(
                    post.get('timestamp'),
                    '%Y-%m-%dT%H:%M:%S+0000'
                ) if post.get('timestamp') else None

                post_analytics = {
                    "post_id": post.get('id'),
                    "caption": post.get('caption', ''),
                    "media_type": post.get('media_type'),
                    "media_url": post.get('media_url'),
                    "thumbnail_url": post.get('thumbnail_url'),
                    "permalink": post.get('permalink'),
                    "created_time": created_time.isoformat() if created_time else None,
                    "likes_count": post.get('like_count', 0),
                    "comments_count": post.get('comments_count', 0),
                    "comments": []
                }

                # Process comments
                for comment in comments_data:
                    try:
                        comment_time = datetime.strptime(
                            comment.get('timestamp'),
                            '%Y-%m-%dT%H:%M:%S+0000'
                        ) if comment.get('timestamp') else None

                        comment_data = {
                            "comment_id": comment.get('id'),
                            "text": comment.get('text'),
                            "username": comment.get('username'),
                            "created_time": comment_time.isoformat() if comment_time else None,
                            "replies": []
                        }

                        # Process replies if any
                        replies = comment.get('replies', {}).get('data', [])
                        for reply in replies:
                            reply_time = datetime.strptime(
                                reply.get('timestamp'),
                                '%Y-%m-%dT%H:%M:%S+0000'
                            ) if reply.get('timestamp') else None

                            reply_data = {
                                "reply_id": reply.get('id'),
                                "text": reply.get('text'),
                                "username": reply.get('username'),
                                "created_time": reply_time.isoformat() if reply_time else None
                            }
                            comment_data["replies"].append(reply_data)

                        post_analytics["comments"].append(comment_data)

                    except Exception as comment_error:
                        print(f"Error processing comment: {str(comment_error)}")
                        continue

                analytics_data.append(post_analytics)

            except Exception as post_error:
                print(f"Error processing post: {str(post_error)}")
                continue

        # Sort posts by created_time
        analytics_data.sort(
            key=lambda x: datetime.fromisoformat(x['created_time']) if x['created_time'] else datetime.min,
            reverse=True
        )

        return {
            "instagram_user_id": instagram_user_id,
            "username": instagram_account['uname'],
            "posts": analytics_data,
            "total_posts": len(analytics_data)
        }

except HTTPException as he:
    raise he
except Exception as e:
    print(f"Unexpected error: {str(e)}")
    raise HTTPException(
        status_code=500,
        detail=f"Error fetching Instagram post analytics: {str(e)}"
    )
  1. this is the postman output when i checked the api

{ "instagram_user_id": "9126911540692667", "username": "vaasuu994", "posts": [ { "post_id": "18071977783652771", "caption": "this is new post at 8 pm", "media_type": "IMAGE", "media_url": "https://scontent.cdninstagram.com/v/t51.2885-15/470059027_1631783381100932_412873310478335983_n.jpg?_nc_cat=103&ccb=1-7&_nc_sid=18de74&_nc_ohc=rbWwpxGAYSMQ7kNvgHhm609&_nc_zt=23&_nc_ht=scontent.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AYD96YiFDLNhIxVvRbOjtVp1FuuIqQEYFjb5-so2DG3nJw&oe=6760A953", "thumbnail_url": null, "permalink": "https://www.instagram.com/p/DDewPN6se4F/", "created_time": "2024-12-12T13:47:40", "likes_count": 1, "comments_count": 1, "comments": [] }, { "post_id": "18067118218776225", "caption": "this is the test 123", "media_type": "IMAGE", "media_url": "https://scontent.cdninstagram.com/v/t51.2885-15/469914946_560366433569419_5961729207973594249_n.jpg?_nc_cat=105&ccb=1-7&_nc_sid=18de74&_nc_ohc=FV3F4QZVXaYQ7kNvgFMLr28&_nc_zt=23&_nc_ht=scontent.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AYCerTY0mj-BN01CEzGlKyLpr5cLaJY0SOPqed7j7lY3GA&oe=6760B0C3", "thumbnail_url": null, "permalink": "https://www.instagram.com/p/DDd5Bb0hj3x/", "created_time": "2024-12-12T05:45:12", "likes_count": 1, "comments_count": 2, "comments": [] } ], "total_posts": 2 }

Reasons:
  • Blacklisted phrase (1): help me
  • Blacklisted phrase (1): i am not able to
  • RegEx Blacklisted phrase (3): can someone help me
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: Vasu Chourasia