---
title: "Setting up and Getting Started with meetupr"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Setting up and Getting Started with meetupr}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r}
#| include: false
#| label: setup

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = TRUE
)

vcr::setup_knitr(prefix = "meetupr-")
meetupr:::mock_if_no_auth()
meetupr::local_meetupr_debug(0)
```

```{r}
#| label: load
library(meetupr)
```


meetupr is an R package that provides a client for the Meetup.com GraphQL API.
It allows you to search for groups, retrieve event information, get member lists, and access other Meetup data directly from R.
This vignette will guide you through setup, authentication, and common use cases.

## Quick Setup Check

Start by running `meetupr_sitrep()` to check your authentication status or set up authentication:

```{r}
#| label: sitrep
#| cassette: true

meetupr_sitrep()
```

This function shows you:

- Which authentication method is currently active  
- Whether your credentials are properly configured  
- API connectivity status  
- Setup instructions if authentication is missing  

The function provides actionable feedback, telling you exactly what to do if authentication isn't working.

## Authentication

Authentication is required to access the Meetup API.
meetupr automatically detects whether you're working interactively or in an automated environment:

- **Interactive sessions** (RStudio, R console): OAuth opens a browser for authorization
- **Non-interactive sessions** (CI/CD, scheduled scripts): OAuth uses pre-cached tokens

This detection uses `rlang::is_interactive()` to determine the context and switch authentication flows accordingly.

When working interactively:

```r
# First time: browser opens for authorization
get_group("rladies-lagos")

# Subsequent calls: uses cached token (no browser)
get_group_events("rladies-lagos")
```

When running non-interactively (GitHub Actions, cron jobs):

```r
# Load token from environment variables (set via CI secrets)
meetupr_encrypt_load()

# All API calls use the loaded token
get_group_events("rladies-lagos")
```

The package handles the switching automatically — you don't need to change your code between environments.

### Interactive Authentication

For interactive use (exploring data, one-off analyses), simply authenticate when prompted:

```r
# Authenticate interactively (opens browser)
meetupr_auth()

# Check authentication status
meetupr_auth_status()
```

When you run `meetupr_auth()`:

1. A browser window opens to Meetup's authorization page  
2. You log in with your Meetup credentials  
3. You grant permission to the meetupr app  
4. The OAuth token is securely cached on your system  

The OAuth token is stored locally in your httr2 cache directory.
Token files follow the naming pattern: `{hash}-token.rds.enc`.
These files are encrypted and specific to your system.

You only need to authenticate once.
The token will be reused in future R sessions until it expires (typically after 90 days).

### Non-Interactive Authentication (CI/CD)

meetupr also supports secure, non-interactive authentication for automated workflows (such as GitHub Actions, GitLab CI, and other CI/CD systems). 
This allows you to run scripts and scheduled jobs without manual login.

For details on setting up meetupr in CI/CD, including secure token management and advanced authentication options, see the [Advanced Authentication](advanced-auth.html) vignette.

## Verification

After authenticating, verify the setup:

```{r}
#| label: verify-sitrep
#| cassette: true
meetupr_sitrep()
```

The output shows:

- Whether an OAuth token exists and is valid  
- Whether you're in CI mode (token loaded from environment variables)  
- API connectivity status  

## Basic Usage Examples

Once authenticated, you can start querying the Meetup API.
All functions return tibbles (data frames) for easy manipulation with dplyr and other tidyverse packages.

### Get Group Information

Retrieve detailed information about a specific group using its URL name (the part after `meetup.com/` in the URL):

```{r}
#| label: group-info
#| cassette: true
group_info <- get_group("rladies-lagos")
str(group_info)
```

The result includes:

- Group name, description, and URL  
- Location (city, state, country)  
- Member count  
- Organizer information  
- Group creation date  

### List Group Events

Get events for a specific group.
By default, this returns upcoming events:

```{r}
#| label: upcoming-events
#| cassette: true
events <- get_group_events("rladies-lagos")
head(events)
```

Each row represents an event with:

- Event ID, title, and description  
- Date and time (as POSIXct objects)  
- Duration  
- RSVP counts (yes, waitlist, total)  
- Venue information (if available)  

### Get Past Events

To retrieve historical events, use the `status` parameter:

```{r}
#| label: past-events
#| cassette: true
past_events <- get_group_events(
  "rladies-lagos",
  status = "past",
  max_results = 10
)
head(past_events)
```


### Filter Events by Date

You can filter events within a specific date range:

```{r}
#| label: date-filter
#| cassette: true
# Events from 2024 onwards
recent_events <- get_group_events(
  "rladies-lagos",
  status = "past",
  date_after = "2024-01-01T00:00:00Z"
)
head(recent_events)
```

Dates must be in ISO 8601 format with timezone (typically UTC: `YYYY-MM-DDTHH:MM:SSZ`).

### Get Event Details

Retrieve detailed information about a specific event using its ID:

```{r}
#| label: event-details
#| cassette: true
event <- get_event(id = "103349942")
event
```

The `print()` method displays a formatted summary.
Access individual fields with `$` notation:

```r
event$title
event$dateTime
event$going
```

### Get Event RSVPs

See who has RSVP'd to an event:

```{r}
#| label: event-rsvps
#| cassette: true
rsvps <- get_event_rsvps(id = "103349942")
head(rsvps)
```

Each row represents one RSVP with:

- Member ID and name  
- RSVP response (yes, no, waitlist)  
- Number of guests  
- RSVP creation time  

This is useful for analyzing attendance patterns or contacting attendees (with appropriate permissions).

### Get Group Members

List members of a group:

```{r}
#| label: group-members
#| cassette: true
members <- get_group_members("rladies-lagos", max_results = 10)
head(members)
```

Member data includes:

- Member ID and name  
- Join date  
- Member status (active, organizer, etc.)  
- Bio and profile URL  

Note: Due to privacy settings, some member information may be limited.

### Search for Groups

Find groups matching a search term:

```{r}
#| label: search-groups
#| cassette: true
r_groups <- find_groups("R programming")
head(r_groups)
```

Search results include:

- Group name and URL name  
- Location  
- Member count  
- Description snippet  

This is useful for discovering groups in your area or analyzing group networks.

### Pagination and Rate Limits

The Meetup API limits how many results can be returned in a single request.
The `max_results` parameter controls pagination:

```{r}
#| label: pagination
#| cassette: true
# Get up to 50 events (may require multiple API calls)
many_events <- get_group_events(
  "rladies-san-francisco",
  status = "past",
  max_results = 50
)

cli::cli_alert_info("Retrieved {nrow(many_events)} events")
```

meetupr automatically handles pagination behind the scenes.
It makes multiple API requests if needed and combines the results into a single tibble.

The Meetup API rate limit is 500 requests per 60 seconds.
meetupr automatically throttles requests to stay under this limit.
For large batch operations, consider adding explicit delays:

```r
# Process multiple groups with delays
groups <- c("rladies-nyc", "rladies-sf", "rladies-london")

events <- purrr::map_dfr(groups, \(x) {
  result <- get_group_events(x, max_results = 20)
  Sys.sleep(0.5)  # 500ms delay between requests
  result
})
```

## Pro Account Features

If you have a Meetup Pro account, you can access network-wide data using the Pro functions.
These functions require appropriate permissions and will error if you don't have Pro access.

### List All Pro Groups

```{r}
#| label: pro-groups
#| eval: false

# Get all groups in the R-Ladies network
pro_groups <- get_pro_groups("rladies")
head(pro_groups)
```

### Network-Wide Events

```{r}
#| label: pro-events
#| eval: false

# Get upcoming events across all groups in network
upcoming <- get_pro_events("rladies", status = "upcoming")
head(upcoming)

# Get cancelled events
cancelled <- get_pro_events("rladies", status = "cancelled")
head(cancelled)
```

Pro functions return data for all groups in your network with a single API call, which is more efficient than querying each group individually.

## Debug Mode

Sometimes issues arise due to misconfiguration or unexpected API behavior.
Enabling debug mode shows the exact GraphQL queries being sent to the API.

```{r}
#| label: debug
#| cassette: true

local_meetupr_debug(1)
meetupr_sitrep()
find_groups("R programming")
```

Debug output includes:

- The complete GraphQL query sent to the API  
- Variable values being passed  
- The raw JSON response  

This is invaluable when queries fail unexpectedly or you're unsure what data is being returned.

To turn it off again, set it to `0`:

```{r}
#| label: debug-off
#| cassette: true

local_meetupr_debug(0)
meetupr_sitrep()
find_groups("R programming")
```

For persistent debugging across R sessions, set the environment variable in your `.Renviron` file:

```
MEETUPR_DEBUG=1
```

## Common Issues

### Authentication Errors

```
Error: Authentication required
```

**Solution**: Run `meetupr_sitrep()` to diagnose the issue.
Common causes include:

- No OAuth token cached (run `meetupr_auth()`)  
- Expired token (re-authenticate with `meetupr_auth()`)  
- Missing CI environment variables (check `meetupr_token` and `meetupr_token_file`)  

### Multiple Token Warning

```
Warning: Multiple tokens found in cache
```

**Solution**: Clear old tokens and re-authenticate:

```r
meetupr_deauth()
meetupr_auth()
```

This happens when tokens from different OAuth applications accumulate in your cache directory.

### Rate Limiting

```
Error: Rate limit exceeded
```

**Solution**: The Meetup API limits you to 500 requests per 60 seconds.
If you hit this limit:

1. Add delays between requests (`Sys.sleep(0.5)`)  
2. Reduce `max_results` to minimize pagination  
3. Cache results locally to avoid repeated queries  

meetupr automatically throttles requests, but aggressive batch operations may still hit limits.

### Group Not Found

```
Error: Group not found
```

**Solution**: Verify the group URL name.
The URL name is the part after `meetup.com/` in the group's URL.
For example, for `https://www.meetup.com/rladies-san-francisco/`, the URL name is `rladies-san-francisco`.

## Next Steps

Now that you're set up, explore more advanced features:

- **Custom GraphQL Queries**: See the [GraphQL vignette](graphql.html) to write custom queries and access fields not available through wrapper functions  
- **Custom OAuth Application**: See the [Advanced Authentication vignette](advanced-auth.html) for setting up your own OAuth app for higher rate limits  
- **API Schema Exploration**: See the [Inspecting the API vignette](introspection.html) for exploring the Meetup GraphQL schema
- **Data Analysis**: Combine meetupr with dplyr, ggplot2, and other tidyverse packages for analysis and visualization  

For package updates and issues, visit the [GitHub repository](https://github.com/rladies/meetupr).

## Getting Help

If you encounter issues:

1. **Check `meetupr_sitrep()`** for authentication diagnostics  
2. **Enable debug mode** (`local_meetupr_debug(1)`) to see API queries  
3. **Search existing issues** on GitHub  
4. **File a bug report** with a reproducible example (use `reprex::reprex()`)  

When reporting issues, include:

- Output from `meetupr_sitrep()`  
- Debug output (if relevant)  
- A minimal reproducible example  
- Your R and package versions (`sessionInfo()`)  

This helps maintainers diagnose and fix problems quickly.
