Prompts:

  1. Is there an api that my program can use to monitor / read posts from a public page on facebook?
  2. Write me a c# example of both, please, that would build c# objects from the posts that meet a commont interface

Response:

Here’s a C# example that fetches posts from both Facebook Pages and Facebook Groups using the Facebook Graph API and builds C# objects implementing a common interface.


1. Define a Common Interface for Posts

Both PagePost and GroupPost will implement this interface:

public interface IFacebookPost
{
    string Id { get; set; }
    string Message { get; set; }
    DateTime CreatedTime { get; set; }
}

2. Define Models for Facebook Page and Group Posts

public class PagePost : IFacebookPost
{
    public string Id { get; set; }
    public string Message { get; set; }
    public DateTime CreatedTime { get; set; }
}

public class GroupPost : IFacebookPost
{
    public string Id { get; set; }
    public string Message { get; set; }
    public DateTime CreatedTime { get; set; }
}

3. Facebook API Helper Class

This class will fetch posts from both a Page and a Group:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

public class FacebookApiClient
{
    private readonly HttpClient _httpClient;
    private readonly string _accessToken;

    public FacebookApiClient(string accessToken)
    {
        _httpClient = new HttpClient();
        _accessToken = accessToken;
    }

    private async Task<string> GetFacebookDataAsync(string url)
    {
        var response = await _httpClient.GetAsync(url);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }

    public async Task<List<IFacebookPost>> GetPagePostsAsync(string pageId)
    {
        string url = $"https://graph.facebook.com/v19.0/{pageId}/posts?fields=id,message,created_time&access_token={_accessToken}";
        string jsonResponse = await GetFacebookDataAsync(url);
        
        var pagePosts = JsonSerializer.Deserialize<FacebookResponse<PagePost>>(jsonResponse);
        return pagePosts?.Data ?? new List<IFacebookPost>();
    }

    public async Task<List<IFacebookPost>> GetGroupPostsAsync(string groupId)
    {
        string url = $"https://graph.facebook.com/v19.0/{groupId}/feed?fields=id,message,created_time&access_token={_accessToken}";
        string jsonResponse = await GetFacebookDataAsync(url);
        
        var groupPosts = JsonSerializer.Deserialize<FacebookResponse<GroupPost>>(jsonResponse);
        return groupPosts?.Data ?? new List<IFacebookPost>();
    }
}

public class FacebookResponse<T> where T : IFacebookPost
{
    public List<T> Data { get; set; }
}

4. Using the API Client

This example fetches posts from both a Facebook Page and a Facebook Group:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string accessToken = "YOUR_FACEBOOK_ACCESS_TOKEN";
        string pageId = "YOUR_PAGE_ID";
        string groupId = "YOUR_GROUP_ID";

        var facebookClient = new FacebookApiClient(accessToken);

        List<IFacebookPost> pagePosts = await facebookClient.GetPagePostsAsync(pageId);
        List<IFacebookPost> groupPosts = await facebookClient.GetGroupPostsAsync(groupId);

        Console.WriteLine("=== Page Posts ===");
        foreach (var post in pagePosts)
        {
            Console.WriteLine($"[{post.CreatedTime}] {post.Message}");
        }

        Console.WriteLine("\n=== Group Posts ===");
        foreach (var post in groupPosts)
        {
            Console.WriteLine($"[{post.CreatedTime}] {post.Message}");
        }
    }
}

5. Explanation

  • Common Interface (IFacebookPost): Ensures both PagePost and GroupPost share the same structure.
  • API Helper (FacebookApiClient):
    • Uses HttpClient to call the Facebook Graph API.
    • Fetches posts from either a Page or a Group.
    • Deserializes the response into C# objects.
  • Main Program (Program.cs):
    • Calls both GetPagePostsAsync and GetGroupPostsAsync.
    • Prints out posts from both sources.

6. Requirements

  • Install System.Text.Json (if using .NET Core or .NET 5+)
  • Get a Facebook Access Token from the Facebook Developer Portal.
  • Replace YOUR_FACEBOOK_ACCESS_TOKEN, YOUR_PAGE_ID, and YOUR_GROUP_ID.

7. Notes

  • Permissions Required:
    • pages_read_engagement for Page posts.
    • groups_access_member_info for Group posts (and must be added to the group).
    • An App Review is required if accessing posts at scale.

Would you like help testing this with a real API call?