The hardware and bandwidth for this mirror is donated by dogado GmbH, the Webhosting and Full Service-Cloud Provider. Check out our Wordpress Tutorial.
If you wish to report a bug, or if you are interested in having us mirror your free-software or open-source project, please feel free to contact us at mirror[@]dogado.de.

Package {twscrapeR}


Type: Package
Title: Twitter/X Scraping via Python's 'twscrape' Library
Version: 0.1.3
Date: 2026-05-23
Description: A comprehensive R interface to Python's 'twscrape' library for scraping Twitter/X data. This package uses 'reticulate' to provide a seamless R interface to the fully functional Python 'twscrape' library. Supports searching tweets, user timelines, followers, and more, with built-in rate limiting and multi-account support. Built on top of 'twscrape' by vladkens https://github.com/vladkens/twscrape and inspired by 'snscrape' by JustAnotherArchivist https://github.com/JustAnotherArchivist/snscrape.
License: MIT + file LICENSE
Encoding: UTF-8
Depends: R (≥ 3.6.0)
Imports: reticulate (≥ 1.20), cli (≥ 3.0.0), jsonlite
Suggests: dplyr, purrr, tibble, testthat (≥ 3.0.0)
Config/testthat/edition: 3
RoxygenNote: 7.3.3
URL: https://github.com/agusnieto77/twscrapeR
BugReports: https://github.com/agusnieto77/twscrapeR/issues
NeedsCompilation: no
Packaged: 2026-05-30 02:35:27 UTC; agustin
Author: Agustin Nieto [aut, cre], Claude AI [ctb] (Package development assistance)
Maintainer: Agustin Nieto <agustin.nieto77@gmail.com>
Repository: CRAN
Date/Publication: 2026-06-03 13:10:02 UTC

Entorno global para almacenar configuracion

Description

Entorno global para almacenar configuracion

Usage

.twscraper_env

Format

An object of class environment of length 3.


Agregar Cuenta de Twitter

Description

Agrega una cuenta de Twitter con cookies y la activa automaticamente. IMPORTANTE: Las cookies son obligatorias para activar la cuenta correctamente.

Usage

add_account(
  username,
  password,
  email,
  email_password,
  cookies,
  db_file = "accounts.db",
  verbose = TRUE
)

Arguments

username

Nombre de usuario

password

Contrasena

email

Email de la cuenta

email_password

Contrasena del email

cookies

Cookies de sesion (OBLIGATORIO - formato: "auth_token=...; ct0=...")

db_file

Archivo de base de datos (default: "accounts.db")

verbose

Si 'TRUE', emite mensajes informativos con 'message()'/'warning()'; puede silenciarse con 'suppressMessages()'/'suppressWarnings()'.

Value

Invisibly returns 'TRUE' if the account was added and is active; invisibly returns 'FALSE' if it was not added, already existed, or could not be activated.

Examples


if (check_setup() && interactive()) {
  # add_account(
  #   username = "your_username",
  #   password = "your_password",
  #   email = "you@example.com",
  #   email_password = "your_email_password",
  #   cookies = "auth_token=...; ct0=..."
  # )
}


Agregar Cuenta desde Variables de Entorno

Description

Lee credenciales desde '.Renviron' o variables de entorno y agrega la cuenta sin exponer secretos en el codigo.

Usage

add_account_from_env(prefix = "TWS_", db_file = "accounts.db", verbose = TRUE)

Arguments

prefix

Prefijo de las variables de entorno (default: "TWS_")

db_file

Archivo de base de datos (default: "accounts.db")

verbose

Si 'TRUE', emite mensajes informativos con 'message()'/'warning()'; puede silenciarse con 'suppressMessages()'/'suppressWarnings()'.

Value

'TRUE' si la cuenta se agrego y activo; 'FALSE' si se agrego pero no quedo activa o hubo error

Examples


# En .Renviron:
# TWS_USERNAME='mi_usuario'
# TWS_PASSWORD='mi_password'
# TWS_EMAIL='mi@email.com'
# TWS_EMAIL_PASSWORD='email_pass'
# TWS_AUTH_TOKEN='auth_token_del_navegador'
# TWS_CT0='ct0_del_navegador'

if (check_setup() && interactive()) {
  add_account_from_env()

  # Para una segunda cuenta, usa otro prefijo:
  # TWS2_USERNAME='otra_cuenta'
  # TWS2_PASSWORD='otra_password'
  # ...
  add_account_from_env(prefix = "TWS2_")
}


Convertir Usuario a Data Frame

Description

Convierte un usuario individual a data.frame de una fila

Usage

## S3 method for class 'twscraper_user'
as.data.frame(x, ...)

Arguments

x

Usuario de get_user()

...

Argumentos adicionales

Value

data.frame


Verificar si twscrapeR esta configurado

Description

Verifica si Python y twscrape estan configurados en la sesion actual.

Usage

check_setup(...)

Arguments

...

Ignorado; reservado para compatibilidad futura.

Value

'TRUE' si twscrapeR esta configurado en la sesion actual; 'FALSE' en caso contrario.

Examples

check_setup()

Eliminar Cuenta

Description

Elimina una cuenta de la base de datos

Usage

delete_account(username, db_file = "accounts.db", verbose = TRUE)

Arguments

username

Nombre de usuario a eliminar

db_file

Archivo de base de datos (default: "accounts.db")

verbose

Si 'TRUE', emite mensajes informativos con 'message()'/'warning()'; puede silenciarse con 'suppressMessages()'/'suppressWarnings()'.

Value

Invisibly returns 'TRUE' if the account was deleted; invisibly returns 'FALSE' otherwise.

Examples


if (check_setup() && interactive()) {
  # delete_account("your_username")
}


Asegurar que twscrapeR esta configurado

Description

Uso interno - verifica configuracion antes de operaciones

Usage

ensure_configured()

Filtrar Tweets por Fecha

Description

Filtra tweets por rango de fechas

Usage

filter_by_date(tweets, from = NULL, to = NULL)

Arguments

tweets

Lista de tweets

from

Fecha inicial (POSIXct o character)

to

Fecha final (POSIXct o character)

Value

Lista filtrada de tweets

Examples


tweets <- list(
  list(id = "1", date = as.POSIXct("2026-01-01")),
  list(id = "2", date = as.POSIXct("2026-02-01"))
)
class(tweets) <- c("twscraper_tweets", "list")
tweets_recent <- filter_by_date(tweets, from = "2025-10-01")


Filtrar Tweets por Idioma

Description

Filtra tweets por idioma

Usage

filter_by_lang(tweets, lang)

Arguments

tweets

Lista de tweets

lang

Codigo de idioma (ej: "es", "en", "pt")

Value

Lista filtrada de tweets

Examples


tweets <- list(
  list(id = "1", lang = "es"),
  list(id = "2", lang = "en")
)
class(tweets) <- c("twscraper_tweets", "list")
tweets_es <- filter_by_lang(tweets, "es")


Obtener Seguidores de un Usuario

Description

Obtiene la lista de seguidores de un usuario

Usage

get_followers(username, n = 100, progress = TRUE)

Arguments

username

Nombre de usuario (sin @)

n

Numero maximo de seguidores (default: 100)

progress

Mostrar progreso (default: TRUE)

Value

Lista de usuarios

Examples


if (check_setup()) {
  followers <- get_followers("elonmusk", n = 100)
}


Obtener Usuarios Seguidos

Description

Obtiene la lista de usuarios que sigue un usuario

Usage

get_following(username, n = 100, progress = TRUE)

Arguments

username

Nombre de usuario (sin @)

n

Numero maximo de usuarios (default: 100)

progress

Mostrar progreso (default: TRUE)

Value

Lista de usuarios

Examples


if (check_setup()) {
  following <- get_following("elonmusk", n = 100)
}


Obtener Usuarios que Retuitearon

Description

Obtiene la lista de usuarios que retuitearon un tweet especifico

Usage

get_retweeters(tweet_id, n = 100, progress = TRUE)

Arguments

tweet_id

ID del tweet

n

Numero maximo de usuarios (default: 100)

progress

Mostrar progreso (default: TRUE)

Value

Lista de usuarios

Examples


if (check_setup()) {
  retweeters <- get_retweeters(1234567890, n = 100)
}


Obtener Retweeters para Varios Tweets

Description

Obtiene usuarios que retuitearon varios tweets en una sola llamada de R.

Usage

get_retweeters_batch(tweets, n = 100, progress = TRUE, flatten = TRUE)

Arguments

tweets

Vector de IDs, lista de tweets 'twscraper_tweets', tweet individual o data.frame con columna 'id'/'tweet_id'.

n

Numero maximo de usuarios por tweet (default: 100)

progress

Mostrar progreso (default: TRUE)

flatten

Si es TRUE, devuelve una lista plana de usuarios con columna 'source_tweet_id' para usar con 'to_dataframe()'. Si es FALSE, devuelve una lista agrupada por tweet.

Value

Lista de usuarios con 'source_tweet_id' o lista agrupada por tweet

Examples


if (check_setup()) {
  tweets <- search_tweets("rstats", n = 10)
  retweeters <- get_retweeters_batch(tweets, n = 50)
  retweeters_df <- to_dataframe(retweeters)

  retweeters_by_tweet <- get_retweeters_batch(tweets, n = 50, flatten = FALSE)
}


Obtener Informacion de Usuario

Description

Obtiene informacion detallada de un usuario

Usage

get_user(username, progress = TRUE)

Arguments

username

Nombre de usuario (sin @)

progress

Mostrar progreso (default: TRUE)

Value

Lista con informacion del usuario

Examples


if (check_setup()) {
  user <- get_user("hadleywickham")
}


Listar Cuentas

Description

Lista todas las cuentas configuradas

Usage

list_accounts(db_file = "accounts.db", verbose = TRUE)

Arguments

db_file

Archivo de base de datos (default: "accounts.db")

verbose

Si 'TRUE', emite mensajes informativos con 'message()'/'warning()'; puede silenciarse con 'suppressMessages()'/'suppressWarnings()'.

Value

Invisibly returns a list of configured accounts. Each account contains 'username', 'email', 'active', and 'locks'; an empty list indicates no accounts or an error.

Examples


if (check_setup()) {
  accounts <- list_accounts()
  print(accounts)
}


Metodo Print para Tweet Individual

Description

Imprime informacion de un tweet individual

Usage

## S3 method for class 'twscraper_tweet'
print(x, ...)

Arguments

x

Informacion de un tweet

...

Argumentos adicionales

Value

Invisibly returns 'x', a 'twscraper_tweet' list with tweet metadata, author fields, engagement counts, language, and URL.


Metodo Print para Tweets

Description

Imprime resumen de tweets

Usage

## S3 method for class 'twscraper_tweets'
print(x, ...)

Arguments

x

Lista de tweets

...

Argumentos adicionales

Value

Invisibly returns 'x', a 'twscraper_tweets' list. Each element represents one tweet with fields such as 'id', 'date', 'text', 'username', engagement counts, language, and URL.


Metodo Print para Usuario

Description

Imprime informacion de usuario

Usage

## S3 method for class 'twscraper_user'
print(x, ...)

Arguments

x

Informacion de usuario

...

Argumentos adicionales

Value

Invisibly returns 'x', a 'twscraper_user' list with fields such as 'id', 'username', 'displayname', 'description', follower/following counts, verification status, location, URL, and profile image URL.


Metodo Print para Lista de Usuarios

Description

Imprime resumen de usuarios

Usage

## S3 method for class 'twscraper_users'
print(x, ...)

Arguments

x

Lista de usuarios

...

Argumentos adicionales

Value

Invisibly returns 'x', a 'twscraper_users' list. Each element represents one user with profile metadata and account statistics.


Guardar Tweets como CSV

Description

Guarda tweets en formato CSV

Usage

save_csv(tweets, file)

Arguments

tweets

Lista de tweets

file

Nombre del archivo

Value

Invisibly returns the output file path. The CSV contains one row per tweet/user-like item after conversion with 'to_dataframe()'.

Examples


tweets <- list(list(id = "1", text = "Hello R", username = "rstats"))
save_csv(tweets, tempfile(fileext = ".csv"))


Guardar Tweets como JSON

Description

Guarda tweets en formato JSON

Usage

save_json(tweets, file)

Arguments

tweets

Lista de tweets

file

Nombre del archivo

Value

Invisibly returns the output file path. The JSON file contains the list structure supplied in 'tweets', written with 'jsonlite::write_json()'.

Examples


tweets <- list(list(id = "1", text = "Hello R", username = "rstats"))
save_json(tweets, tempfile(fileext = ".json"))


Buscar por Hashtag

Description

Busca tweets que contengan un hashtag especifico

Usage

search_hashtag(hashtag, n = 100, progress = TRUE)

Arguments

hashtag

Hashtag (con o sin #)

n

Numero maximo de tweets (default: 100)

progress

Mostrar progreso (default: TRUE)

Value

Lista de tweets

Examples


if (check_setup()) {
  tweets <- search_hashtag("rstats", n = 50)
  tweets <- search_hashtag("#datascience", n = 100)
}


Buscar Menciones de un Usuario

Description

Busca tweets que mencionen a un usuario especifico

Usage

search_mentions(username, n = 100, progress = TRUE)

Arguments

username

Nombre de usuario (sin @)

n

Numero maximo de tweets (default: 100)

progress

Mostrar progreso (default: TRUE)

Value

Lista de tweets

Examples


if (check_setup()) {
  mentions <- search_mentions("hadleywickham", n = 50)
}


Buscar Tweets

Description

Busca tweets usando una consulta

Usage

search_tweets(query, n = 100, progress = TRUE, product = c("Latest", "Top"))

Arguments

query

Consulta de busqueda (ej: "rstats", "#datascience", "from:usuario")

n

Numero maximo de tweets a retornar (default: 100)

progress

Mostrar barra de progreso (default: TRUE)

product

Tipo de busqueda: "Latest" para tweets recientes o "Top" para tweets destacados (default: "Latest")

Value

Lista de tweets

Examples


if (check_setup()) {
  tweets <- search_tweets("rstats", n = 50)
  top_tweets <- search_tweets("rstats", n = 50, product = "Top")
  df <- to_dataframe(tweets)
}


Setup twscrapeR

Description

Checks that Python and the Python 'twscrape' package are available and configures the active reticulate session. It does not install Python or Python packages automatically.

Usage

setup_twscraper(python_path = NULL, install_python = TRUE, ask = TRUE)

Arguments

python_path

Ruta a Python (opcional, se detecta automaticamente)

install_python

Deprecated compatibility argument. Ignored; installation must be performed by the user outside package functions.

ask

Deprecated compatibility argument. Ignored; retained to avoid breaking existing calls.

Value

Invisibly returns 'TRUE' when Python >= 3.10 and the Python 'twscrape' module are available and configured. Invisibly returns 'FALSE' otherwise, after printing installation instructions.

Examples


if (interactive()) {
  setup_twscraper()
}


Ordenar Tweets

Description

Ordena tweets por algun criterio

Usage

sort_tweets(tweets, by = "date", decreasing = TRUE)

Arguments

tweets

Lista de tweets

by

Campo por el cual ordenar ("date", "like_count", "retweet_count", "views_count")

decreasing

Orden descendente (default: TRUE)

Value

Lista ordenada de tweets

Examples


tweets <- list(
  list(id = "1", date = as.POSIXct("2026-01-01"), like_count = 2),
  list(id = "2", date = as.POSIXct("2026-02-01"), like_count = 10)
)
class(tweets) <- c("twscraper_tweets", "list")
top_tweets <- sort_tweets(tweets, by = "like_count")


Convertir Tweets o Usuarios a Data Frame

Description

Convierte una lista de tweets o usuarios a data.frame usando purrr::map_dfr

Usage

to_dataframe(x)

Arguments

x

Lista de tweets o usuarios

Value

data.frame o tibble

Examples


tweets <- list(
  list(
    id = "1", date = as.POSIXct("2026-01-01"), text = "Hello R",
    username = "rstats", user_displayname = "R Stats", user_id = "10",
    reply_count = 0, retweet_count = 1, like_count = 2, quote_count = 0,
    views_count = 100, lang = "en", url = "https://example.com/1",
    user_followers = 1000, user_verified = FALSE
  )
)
class(tweets) <- c("twscraper_tweets", "list")
df <- to_dataframe(tweets)

users <- list(list(
  id = "10", username = "rstats", displayname = "R Stats",
  description = "Example user", followers_count = 1000,
  following_count = 50, tweets_count = 200, verified = FALSE,
  created = "2026-01-01", location = "", url = "",
  profile_image_url = ""
))
class(users) <- c("twscraper_users", "list")
users_df <- to_dataframe(users)

users[[1]]$source_tweet_id <- "1"
retweeters_df <- to_dataframe(users)  # incluye source_tweet_id


Obtener Detalles de un Tweet

Description

Obtiene informacion detallada de un tweet especifico por su ID

Usage

tweet_details(tweet_id, progress = TRUE)

Arguments

tweet_id

ID del tweet (numero o string)

progress

Mostrar progreso (default: TRUE)

Value

Lista con informacion del tweet o NULL si no se encuentra

Examples


if (check_setup()) {
  tweet <- tweet_details(1234567890)
}


Obtener Respuestas a un Tweet

Description

Obtiene las respuestas (replies) a un tweet especifico

Usage

tweet_replies(tweet_id, n = 100, progress = TRUE)

Arguments

tweet_id

ID del tweet

n

Numero maximo de respuestas (default: 100)

progress

Mostrar progreso (default: TRUE)

Value

Lista de tweets (respuestas)

Examples


if (check_setup()) {
  replies <- tweet_replies(1234567890, n = 50)
}


Obtener Tweets con Media de un Usuario

Description

Obtiene solo los tweets que contienen imagenes o videos

Usage

user_media(username, n = 100, progress = TRUE)

Arguments

username

Nombre de usuario (sin @)

n

Numero maximo de tweets (default: 100)

progress

Mostrar progreso (default: TRUE)

Value

Lista de tweets

Examples


if (check_setup()) {
  media_tweets <- user_media("elonmusk", n = 100)
}


Obtener Tweets de un Usuario

Description

Obtiene los tweets recientes de un usuario especifico

Usage

user_tweets(username, n = 100, progress = TRUE)

Arguments

username

Nombre de usuario (sin @)

n

Numero maximo de tweets (default: 100)

progress

Mostrar progreso (default: TRUE)

Value

Lista de tweets

Examples


if (check_setup()) {
  tweets <- user_tweets("hadleywickham", n = 50)
}


Obtener Tweets y Respuestas de un Usuario

Description

Obtiene tweets y respuestas de un usuario (timeline completo)

Usage

user_tweets_and_replies(username, n = 100, progress = TRUE)

Arguments

username

Nombre de usuario (sin @)

n

Numero maximo de tweets (default: 100)

progress

Mostrar progreso (default: TRUE)

Value

Lista de tweets

Examples


if (check_setup()) {
  all_tweets <- user_tweets_and_replies("elonmusk", n = 100)
}


Convertir Usuarios a Dataframe (alias de to_dataframe)

Description

Alias interno de to_dataframe() - usar to_dataframe() directamente

Usage

users_to_dataframe(users)

Arguments

users

Lista de usuarios

Value

data.frame con informacion de usuarios


Obtener Seguidores Verificados

Description

Obtiene solo los seguidores que tienen cuenta verificada

Usage

verified_followers(username, n = 100, progress = TRUE)

Arguments

username

Nombre de usuario (sin @)

n

Numero maximo de seguidores (default: 100)

progress

Mostrar progreso (default: TRUE)

Value

Lista de usuarios verificados

Examples


if (check_setup()) {
  verified <- verified_followers("elonmusk", n = 100)
}

These binaries (installable software) and packages are in development.
They may not be fully stable and should be used with caution. We make no claims about them.
Health stats visible at Monitor.