Skip to content

Instantly share code, notes, and snippets.

Revisions

  1. smach created this gist Dec 25, 2022.
    48 changes: 48 additions & 0 deletions mastodon_followers_and_lists_i_assigned_them_to.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    # get all people you follow on Mastodon and which lists you've assigned them to. Inspired by Jon Udell doing this with Steampipe, his blog post: https://blog.jonudell.net/2022/12/22/lists-and-people-on-mastodon/

    library(rtoot) # need the dev version, and you need to have gotten and stored a user token
    library(dplyr)
    library(purrr)
    library(magrittr)
    library(glue)

    # If you don't know your Mastodon account ID
    my_display_name <- "YOUR DISPLAY NAME HERE"
    my_account <- rtoot::search_accounts("smach")
    # Mastodon account ID comes back in the list of account.
    # My account was the first result, hence the [1]. Check yours!
    my_id <- my_account$id[1]
    num_following <- my_account$following_count[1]

    # Find all your Mastodon lists
    all_my_lists <- rtoot(endpoint = "api/v1/lists") |>
    bind_rows()

    # This is a function to get all the members of a specific list. The endpoint defaults to a maximum of 40 list members returned. If, like me, you have larger lists, set limit to 0 as I did in the function's first line of code.
    get_list_members <- function(list_id, list_title) {
    list_info <- rtoot(endpoint = glue("api/v1/lists/{list_id}/accounts?limit=0"))
    list_members <- list_info |>
    map_dfr(magrittr::extract, c("username", "acct", "display_name", "url", "id"))
    list_members$List <- list_title
    list_members$ListID <- list_id
    return(list_members)
    }

    # Run the function on all of your lists
    my_list_members <- map2_df(all_my_lists$id, all_my_lists$title, get_list_members)

    # Now, separately, get a list of all the people you follow. I set the variable num_following above when searching for my account ID. You can set it manually.
    all_people_i_follow <- get_account_following(my_id, limit = num_following)

    # This code joins the people you follow with the people on lists
    following_w_their_lists <- left_join(all_people_i_follow[, c("id", "acct", "display_name", "note", "url")], my_list_members[, c("List", "id", "acct", "display_name")], by = c("id", "acct", "display_name"))

    # This reshapes the results to show one row for each person and a column for all the lists you've assigned them to. It also turns NA (which shows up as the string "NA" and not R NA) into blank character string ""
    following_results <- following_w_their_lists |>
    group_by(id, acct, display_name, note, url) |>
    summarize(
    Lists = paste(List, collapse = ", "),
    Lists = ifelse(Lists == "NA", "", Lists)
    ) |>
    ungroup() |>
    arrange(Lists)