---
# System prepended metadata

title: updated Farcaster Feed

---

```
import requests  # Import the requests library for making HTTP requests
import argparse  # Import the argparse library for parsing command-line arguments
import os  # Import the os library for accessing environment variables

# Function to make a GET request to the Neynar API
def get(endpoint, args, api_key=None):
    url = f"https://api.neynar.com/{endpoint}"  # Construct the full URL for the endpoint
    params = args.copy()  # Copy the arguments to avoid modifying the original dictionary
    if api_key is None:
        api_key = os.getenv('NEYNAR_API_KEY')  # Retrieve the API key from the environment variable
    if api_key is None:
        raise ValueError("API key not provided")
    params["api_key"] = api_key  # Add the API key to the parameters

    response = requests.get(url, params=params)  # Make the GET request
    response.raise_for_status()  # Raise an error for bad status codes
    return response.json()  # Return the response as JSON

# Function to get user information by Farcaster username
def get_user(fc_username, api_key=None):
    user_response = get(
        "v1/farcaster/user-by-username",  # Endpoint to get user by username
        {
            "username": fc_username,  # Parameter: Farcaster username
        },
        api_key=api_key  # Optional API key
    )

    if "result" not in user_response:
        raise ValueError("No user found.")  # Raise an error if no user is found

    return user_response["result"]["user"]  # Return the user information

# Function to get casts (posts) by a user with their Farcaster ID (fid)
def get_user_casts(fid, cursor='', api_key=None):
    return get(
        "v2/farcaster/feed",  # Endpoint to get user's feed
        {
            "feed_type": "filter",  # Filter type for the feed
            "filter_type": "fids",  # Filter by fids (Farcaster IDs)
            "fids": fid,  # Parameter: user's Farcaster ID
            "with_recasts": "false",  # Exclude recasts
            "cursor": cursor,  # Pagination cursor
        },
        api_key=api_key  # Optional API key
    )

# Function to get the last 50 unique posters in a specific channel
def get_last_50_unique_posters(channel_name, api_key=None):
    unique_posters = set()
    cursor = ''
    while len(unique_posters) < 50:
        response = get(
            "v2/farcaster/feed/channels",
            {
                "channel_ids": channel_name,
                "with_recasts": "false",
                "with_replies": "false",
                "limit": 50,
                "should_moderate": "false",
                "cursor": cursor,
            },
            api_key=api_key
        )

        if "casts" not in response:
            break

        for cast in response["casts"]:
            unique_posters.add(cast["author"]["username"])
            if len(unique_posters) >= 50:
                break

        cursor = response.get("next", {}).get("cursor", '')
        if not cursor:
            break

    return list(unique_posters)

# Main function to get the last cast by a user in a specific channel
def main(fc_username, fc_channel_name):
    api_key = os.getenv('NEYNAR_API_KEY')
    
    if fc_username:
        user = get_user(fc_username, api_key)  # Get user information
        fid = user["fid"]  # Extract the user's Farcaster ID

        # Find the last cast by the user in the channel
        found_cast = None
        cursor = ''
        while not found_cast:
            casts_response = get_user_casts(fid, cursor=cursor, api_key=api_key)  # Get user's casts

            for cast in casts_response["casts"]:
                if cast["parent_url"] == f"https://warpcast.com/~/channel/{fc_channel_name}":
                    found_cast = cast  # Found the cast in the specified channel

            cursor = casts_response.get("next", {}).get("cursor", '')  # Update the cursor for pagination

        if found_cast:
            # Print the details of the found cast
            print(f'{fc_username} last casted in /{fc_channel_name} at {found_cast["timestamp"]}:')
            print()
            print(found_cast['text'])
            print()
            print('Hash:', found_cast['hash'])
            print('Warpcast URL:', f'https://warpcast.com/{fc_username}/{found_cast["hash"][:8]}')
        else:
            print(f'No casts found for {fc_username} in /{fc_channel_name}.')
    else:
        unique_posters = get_last_50_unique_posters(fc_channel_name, api_key)
        print(f'Last 50 unique posters in /{fc_channel_name}:')
        for poster in unique_posters:
            print(poster)

# Entry point of the script
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Get last cast by user in channel or last 50 unique posters')  # Create an argument parser
    parser.add_argument('fc_username', type=str, nargs='?', help='Farcaster username')  # Add Farcaster username argument
    parser.add_argument('fc_channel_name', type=str, nargs='?', default='plan', help='Channel name (default: plan)')  # Add optional channel name argument with default value

    args = parser.parse_args()  # Parse the command-line arguments
    main(args.fc_username, args.fc_channel_name)  # Call the main function with the parsed arguments

```