Метаданные пользователя Facebook Graph API - PullRequest
0 голосов
/ 04 февраля 2020

Я хочу построить проект, в котором мы можем видеть данные Instagram. Например, у нас есть хэштег. И хэштег имеет 100 фотографий. Моя цель - отсортировать эти фотографии по количеству лайков и начать соревнование. Нет проблем с доступом к фотографиям под хэштегом. Но кроме тех, я также хочу показать имя пользователя медиа-участников. Проблема здесь. Код возвращает ошибку, если в учетной записи нет доли. Когда он распределяется, он показывает данные бизнес-аккаунта. Но я хочу получить доступ к данным тех, кто поделился этим под хэштегом. Вот код Раздел получения метаданных находится внизу кода. Раздел начинается с "// Get IGMedia Metadata".

    string access_token = "ACCESS_TOKEN";
    var values = new Dictionary<string, string>
  {
     { "access_token", access_token},
     { "scope","instagram_basic,manage_pages,pages_show_list,ads_management,business_management"},
     { "redirect_uri","" },
  };


    var content = new FormUrlEncodedContent(values);
    var response = new HttpClient().PostAsync("https://graph.facebook.com/v2.6/device/login", content);
    response.Wait();
    if (!response.Result.IsSuccessStatusCode)
        throw new Exception("Auth failed");
    var responseString = response.Result.Content.ReadAsStringAsync();
    responseString.Wait();

    dynamic data = Json.Decode(responseString.Result);

    Console.WriteLine("Code : " + data.code);
    Console.WriteLine("User Code : " + data.user_code);
    Console.WriteLine("Verification Uri : " + data.verification_uri);
    Console.WriteLine("Expires in : " + data.expires_in + " seconds");
    Console.WriteLine("Interval : " + data.interval);

    int interval = Convert.ToInt32(data.interval) * 1000;
    int expires_in = Convert.ToInt32(data.expires_in);
    string longCode = data.code;

    bool loggedIn = false;
    DateTime dtCodeGenerated = DateTime.Now;

    string TokenCall = "";
    int TokenExpireTime;

    while (!loggedIn)
    {
        Thread.Sleep(interval);

        // Poll Login Status
        values = new Dictionary<string, string>
  {
     { "access_token", access_token },
     { "code",longCode}
  };


        content = new FormUrlEncodedContent(values);
        response = new HttpClient().PostAsync("https://graph.facebook.com/v2.6/device/login_status", content);
        response.Wait();
        if (!response.Result.IsSuccessStatusCode)
            throw new Exception("Login Status failed");
        responseString = response.Result.Content.ReadAsStringAsync();
        responseString.Wait();

        data = Json.Decode(responseString.Result);


        if (data.access_token != null)
        {
            loggedIn = true;

            TokenCall = data.access_token;
            TokenExpireTime = Convert.ToInt32(data.expires_in);
            break;
        }
        else
        {
            if (data.error != null)
            {
                Console.WriteLine(data.error.error_user_title);
            }

        }


        Console.WriteLine(String.Format("Expires in : {0:000} seconds", (expires_in - (DateTime.Now - dtCodeGenerated).TotalSeconds)));


    }
    // Get Profile
    response = new HttpClient().GetAsync("https://graph.facebook.com/v2.3/me?fields=name,picture&access_token=" + TokenCall);
    response.Wait();
    if (!response.Result.IsSuccessStatusCode)
        throw new Exception("Profile Get failed");
    responseString = response.Result.Content.ReadAsStringAsync();
    responseString.Wait();

    data = Json.Decode(responseString.Result);

    Console.WriteLine("Name : " + data.name);
    Console.WriteLine("User picture : " + data.picture.data.url);
    Console.WriteLine("Id : " + data.id);

    string userID = data.id;




    // Get User's Pages

    response = new HttpClient().GetAsync("https://graph.facebook.com/v5.0/me/accounts?access_token=" + TokenCall);
    response.Wait();
    if (!response.Result.IsSuccessStatusCode)
        throw new Exception("Profile Get failed");
    responseString = response.Result.Content.ReadAsStringAsync();
    responseString.Wait();

    data = Json.Decode(responseString.Result);


    string selectedBusinessAccountID = "";
    if (data.data.Length > 0)
    {
        for (int i = 0; i < data.data.Length; i++)
        {
            Console.WriteLine("PAGE " + i.ToString());

            Console.WriteLine("Name : " + data.data[i].name);
            Console.WriteLine("Category : " + data.data[i].category);
            Console.WriteLine("Id : " + data.data[i].id);

            Console.WriteLine();
            Console.WriteLine();

            string pageID = data.data[i].id;

            // get Instagram Business Account
            response = new HttpClient().GetAsync(String.Format("https://graph.facebook.com/v5.0/{0}?fields=instagram_business_account&access_token={1}", pageID, TokenCall));
            response.Wait();
            if (!response.Result.IsSuccessStatusCode)
                throw new Exception("Profile Get failed");
            responseString = response.Result.Content.ReadAsStringAsync();
            responseString.Wait();

            dynamic data_instagram_business = Json.Decode(responseString.Result);

            if (data_instagram_business.instagram_business_account != null)
            {
                selectedBusinessAccountID = data_instagram_business.instagram_business_account.id;
                Console.WriteLine("selectedBusinessAccountID : " + selectedBusinessAccountID);

                break;
            }
        }

        // Get Hashtag id
        response = new HttpClient().GetAsync(String.Format("https://graph.facebook.com/ig_hashtag_search?user_id={0}&q={2}&access_token={1}", selectedBusinessAccountID, TokenCall, "hisseliharikalar"));
        response.Wait();
        if (!response.Result.IsSuccessStatusCode)
            throw new Exception("Hashtag ID Failed");
        responseString = response.Result.Content.ReadAsStringAsync();
        responseString.Wait();

        data = Json.Decode(responseString.Result);
        string hashtagID = "";
        if (data.data.Length > 0)
        {
            for (int i = 0; i < data.data.Length; i++)
            {

                Console.WriteLine("Id : " + data.data[i].id);
                hashtagID = data.data[i].id;
                Console.WriteLine();
                Console.WriteLine();

                break;
            }

        }




        // Get Medias of hashtag

        response = new HttpClient().GetAsync(String.Format("https://graph.facebook.com/{0}/recent_media?user_id={1}&fields={3}&access_token={2}", hashtagID, selectedBusinessAccountID, TokenCall, "id,media_type,comments_count,like_count,media_url,caption,children"));
        response.Wait();
        if (!response.Result.IsSuccessStatusCode)
            throw new Exception("Hashtag Medias Failed");
        responseString = response.Result.Content.ReadAsStringAsync();
        responseString.Wait();

        data = Json.Decode(responseString.Result);

        if (data.data.Length > 0)
        {
            for (int i = 0; i < data.data.Length; i++)
            {




                Console.WriteLine("Id : " + data.data[i].id);
                Console.WriteLine("like_count : " + data.data[i].like_count);
                Console.WriteLine("caption : " + data.data[i].caption);
                Console.WriteLine("media_type : " + data.data[i].media_type);
                Console.WriteLine("media_url : " + data.data[i].media_url);
                if (data.data[i].media_url == null)
                {
                    Console.WriteLine("children  : " + data.data[i].children);

                }

                Console.WriteLine();
                Console.WriteLine();




                // Get IGMedia Metadata
                response = new HttpClient().GetAsync(String.Format("https://graph.facebook.com/{0}?fields={3}&access_token={2}", data.data[i].id, selectedBusinessAccountID, TokenCall, "id,like_count,caption,media_type,media_url,comments_count,username,timestamp"));
                response.Wait();
                if (!response.Result.IsSuccessStatusCode)
                    throw new Exception("IGMedia metadata Failed");
                responseString = response.Result.Content.ReadAsStringAsync();
                responseString.Wait();

                dynamic dataIGMedia = Json.Decode(responseString.Result);

                Console.WriteLine("Id : " + dataIGMedia.id);
                Console.WriteLine("like_count : " + dataIGMedia.like_count);
                Console.WriteLine("caption : " + dataIGMedia.caption);
                Console.WriteLine("media_type : " + dataIGMedia.media_type);
                Console.WriteLine("media_url : " + dataIGMedia.media_url);
                Console.WriteLine("comment_count : " + dataIGMedia.comments_count);
                Console.WriteLine("username:" + dataIGMedia.username);
                Console.WriteLine("timestamp:" + dataIGMedia.timestamp);

                Console.WriteLine();
                Console.WriteLine();


            }

        }


        // 
    }





    //End
    Console.ReadKey();



}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...