| Title: | Interact with the 'Telegram' 'MTProto' API |
|---|---|
| Description: | Provides a full-featured client for the 'Telegram' 'MTProto' protocol (<https://core.telegram.org/api>), enabling programmatic access to 'Telegram' chats, channels, messages, media, and stories. Implements binary encoding and decoding of the 'Telegram' 'TL' (Type Language) schema, authentication (including two-factor), encrypted transport, and high-level helpers for downloading channel history and reactions at scale. Intended for social-science research and data collection tasks that require direct API access rather than the 'Bot API'. |
| Authors: | Roman Kyrychenko [aut, cre, cph] |
| Maintainer: | Roman Kyrychenko <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.0.1 |
| Built: | 2026-06-05 19:53:46 UTC |
| Source: | https://github.com/romankyrychenko/telegramr |
This is tricky because we can't easily override '+' for base 'raw' type. But if the first operand is 'raw_bytes', it works. If the first operand is 'raw', we might need to cast it.
## S3 method for class 'raw' e1 + e2## S3 method for class 'raw' e1 + e2
e1 |
Left operand (raw vector). |
e2 |
Right operand (raw vector). |
A new raw_bytes object.
Allows using '+' to concatenate raw_bytes objects, mimicking Python's byte concatenation.
## S3 method for class 'raw_bytes' e1 + e2## S3 method for class 'raw_bytes' e1 + e2
e1 |
Left operand. |
e2 |
Right operand. |
A new raw_bytes object.
Add a user to a chat or channel
add_user_to_chat(client, chat, user, fwd_limit = 10)add_user_to_chat(client, chat, user, fwd_limit = 10)
client |
TelegramClient instance. |
chat |
Chat/channel (username, link, or entity). |
user |
User (username, link, or entity). |
fwd_limit |
Forward limit for basic chats. Default is 10. |
The API response.
Downloads info and messages for multiple channels in sequence, running each
channel in an isolated callr subprocess so crashes cannot corrupt the
parent session. Supports resume: channels already present in msgs_file
are skipped when skip_completed = TRUE.
batch_download_channels( channels, session, api_id, api_hash, info_file = NULL, msgs_file = NULL, reactions_file = NULL, replies_file = NULL, start_date = NULL, limit = Inf, timeout_sec = 30, max_timeouts = 5, chunk_size = 5000L, skip_completed = TRUE, dedup = TRUE, pkg_path = NULL, workers = 1L, verbose = TRUE )batch_download_channels( channels, session, api_id, api_hash, info_file = NULL, msgs_file = NULL, reactions_file = NULL, replies_file = NULL, start_date = NULL, limit = Inf, timeout_sec = 30, max_timeouts = 5, chunk_size = 5000L, skip_completed = TRUE, dedup = TRUE, pkg_path = NULL, workers = 1L, verbose = TRUE )
channels |
character vector. Channel usernames (with or without "@") or numeric ids. |
session |
character. Path to the Telegram session file (passed to
|
api_id |
integer. Telegram API id. |
api_hash |
character. Telegram API hash. |
info_file |
character. Required. Path to the CSV file for channel info rows (appended to). |
msgs_file |
character. Required. Path to the CSV file for message rows (appended to, streamed
in |
reactions_file |
character or NULL. If set, reaction counts are written to this CSV file. |
replies_file |
character or NULL. If set, reply counts are written to this CSV file. |
start_date |
character/Date/POSIXct or NULL. Passed to
|
limit |
integer or Inf. Max messages per channel. |
timeout_sec |
numeric. Per-fetch timeout in seconds. |
max_timeouts |
integer. Timeouts before aborting a single channel. |
chunk_size |
integer. Rows buffered before each CSV flush. |
skip_completed |
logical. If TRUE (default), skip channels whose
username already appears in |
dedup |
logical. If TRUE (default), skip messages already present in
|
pkg_path |
character or NULL. Path to the package root; passed to
|
workers |
integer. Number of parallel workers. Default 1L (sequential). |
verbose |
logical. If TRUE (default), print progress messages. |
A tibble with columns channel, status
("ok"/"skipped"/"error"), rows_downloaded, error_message.
Check a chat invite link without joining
check_invite_link(client, invite_link)check_invite_link(client, invite_link)
client |
TelegramClient instance. |
invite_link |
Invite link or invite hash. |
The API response.
Adds the phone number to the authenticated account's contacts via 'ImportContactsRequest', captures any matching user, then removes the contact via 'DeleteContactsRequest'. The contact addition is transient — Telegram users are not notified.
check_phone_on_telegram( client, phone, download_profile_photo = FALSE, photo_dir = NULL )check_phone_on_telegram( client, phone, download_profile_photo = FALSE, photo_dir = NULL )
client |
An authenticated [TelegramClient] instance. |
phone |
Phone number string in international format (e.g. '"+15551234567"'). |
download_profile_photo |
If 'TRUE', attempt to download the matched user's profile photo into 'photo_dir' (default: 'tempdir()'). Failures are reported as warnings. |
photo_dir |
Directory to save downloaded profile photos; created if it doesn't exist. Ignored when 'download_profile_photo' is 'FALSE'. |
A named list with the user's public fields, or a list with an 'error' field describing why the lookup failed (no match, multiple matches, RPC error, ...).
[check_phones_on_telegram()] for batch lookups.
Convenience wrapper around [check_phone_on_telegram()] that accepts either a character vector or a single comma-separated string (matching the upstream Python CLI). Duplicates are silently de-duplicated.
check_phones_on_telegram( client, phones, download_profile_photo = FALSE, photo_dir = NULL )check_phones_on_telegram( client, phones, download_profile_photo = FALSE, photo_dir = NULL )
client |
An authenticated [TelegramClient] instance. |
phones |
Character vector of phone numbers, or a single comma-separated string. |
download_profile_photo, photo_dir
|
See [check_phone_on_telegram()]. |
A tibble with one row per unique phone number. Successful lookups expose the user's public fields; failures expose an 'error' column.
[check_phone_on_telegram()] for the single-phone variant.
Looks up the username via 'client$get_entity()'. Channels and group chats produce an 'error' row — this helper is for user accounts only.
check_username_on_telegram( client, username, download_profile_photo = FALSE, photo_dir = NULL )check_username_on_telegram( client, username, download_profile_photo = FALSE, photo_dir = NULL )
client |
An authenticated [TelegramClient] instance. |
username |
Username, with or without a leading '@'. |
download_profile_photo, photo_dir
|
See [check_phone_on_telegram()]. |
A named list with the user's public fields, or a list with an 'error' field.
[check_usernames_on_telegram()] for batch lookups.
Convenience wrapper around [check_username_on_telegram()].
check_usernames_on_telegram( client, usernames, download_profile_photo = FALSE, photo_dir = NULL )check_usernames_on_telegram( client, usernames, download_profile_photo = FALSE, photo_dir = NULL )
client |
An authenticated [TelegramClient] instance. |
usernames |
Character vector of usernames, or a single comma-separated string. Leading '@' is optional and stripped. |
download_profile_photo, photo_dir
|
See [check_phone_on_telegram()]. |
A tibble with one row per unique username.
[check_username_on_telegram()] for the single-username variant.
Fetches channel entity and full channel info by username or numeric id and returns a tibble.
download_channel_info( client, channel, region = NULL, include_raw = FALSE, timeout_sec = getOption("telegramR.iter_timeout", 60), reconnect_on_timeout = TRUE, max_attempts = 3, skip_estimate = FALSE, hard_timeout_sec = NULL )download_channel_info( client, channel, region = NULL, include_raw = FALSE, timeout_sec = getOption("telegramR.iter_timeout", 60), reconnect_on_timeout = TRUE, max_attempts = 3, skip_estimate = FALSE, hard_timeout_sec = NULL )
client |
TelegramClient instance. |
channel |
character or numeric. Channel username (with or without "@") or numeric id. |
region |
character or NULL. Optional region tag to attach. |
include_raw |
logical. If TRUE, include raw Telegram objects as list columns. |
timeout_sec |
numeric. Timeout in seconds for network operations. |
reconnect_on_timeout |
logical. Reconnect on timeout if TRUE. |
max_attempts |
integer. Number of retry attempts for resolving and full info. |
skip_estimate |
logical. If TRUE, skip estimate step for last_message_id. |
hard_timeout_sec |
numeric or NULL. Optional hard time limit for the whole call. |
A tibble with flattened channel info and optional list columns for raw objects.
Downloads media (photos/videos/documents) from a channel by username or numeric id and returns a tibble with file paths.
download_channel_media( client, channel, limit = Inf, start_date = NULL, end_date = NULL, media_types = c("photo", "video", "image", "document"), out_dir = NULL, show_progress = TRUE, wait_time = 0, retries = 1, include_errors = TRUE, use_original_filename = FALSE, ... )download_channel_media( client, channel, limit = Inf, start_date = NULL, end_date = NULL, media_types = c("photo", "video", "image", "document"), out_dir = NULL, show_progress = TRUE, wait_time = 0, retries = 1, include_errors = TRUE, use_original_filename = FALSE, ... )
client |
TelegramClient instance. |
channel |
character or numeric. Channel username (with or without "@") or numeric id. |
limit |
integer or Inf. Maximum number of messages to fetch. |
start_date |
POSIXct/Date/character. Earliest date to include (UTC). |
end_date |
POSIXct/Date/character. Latest date to include (UTC). |
media_types |
character vector. Media types to download (e.g. "photo", "video", "document", "image", "audio"). |
out_dir |
character. Required. Directory to save files into (e.g. |
show_progress |
logical. If TRUE, display a progress bar. |
wait_time |
numeric. Seconds to sleep between requests to avoid flood waits. |
retries |
integer. Number of retries per media download on failure. |
include_errors |
logical. If TRUE, include error messages per row. |
use_original_filename |
logical. If TRUE and a document has a filename attribute, use it for the saved file name. |
... |
Passed to client$iter_messages() (e.g. offset_id, max_id, min_id). |
A tibble with message_id, channel info, media_type, file_path, and original_filename.
Fetches channel members (participants) by username or numeric id.
download_channel_members( client, channel, limit = Inf, search = "", filter = NULL, include_channel = TRUE, show_progress = TRUE )download_channel_members( client, channel, limit = Inf, search = "", filter = NULL, include_channel = TRUE, show_progress = TRUE )
client |
TelegramClient instance. |
channel |
character or numeric. Channel username (with or without "@") or numeric id. |
limit |
integer or Inf. Maximum number of members to fetch. |
search |
character. Search query for participant names/usernames. |
filter |
A participants filter, e.g. ChannelParticipantsAdmins. |
include_channel |
logical. If TRUE, include channel fields on every row. |
show_progress |
logical. If TRUE, display a progress bar. |
A tibble.
Fetches messages for a channel by username or numeric id and returns a tibble with message fields and nested structures as list columns.
download_channel_messages( client, channel, limit = Inf, include_channel = TRUE, start_date = NULL, end_date = NULL, since_message_id = NULL, show_progress = TRUE, timeout_sec = getOption("telegramR.iter_timeout", 60), max_timeouts = 3, reconnect_on_timeout = TRUE, output_file = NULL, chunk_size = 5000L, partial_on_error = TRUE, ... )download_channel_messages( client, channel, limit = Inf, include_channel = TRUE, start_date = NULL, end_date = NULL, since_message_id = NULL, show_progress = TRUE, timeout_sec = getOption("telegramR.iter_timeout", 60), max_timeouts = 3, reconnect_on_timeout = TRUE, output_file = NULL, chunk_size = 5000L, partial_on_error = TRUE, ... )
client |
TelegramClient instance. |
channel |
character or numeric. Channel username (with or without "@") or numeric id. |
limit |
integer or Inf. Maximum number of messages to fetch. |
include_channel |
logical. If TRUE, include channel fields on every row. |
start_date |
POSIXct/Date/character. Earliest date to include (UTC). |
end_date |
POSIXct/Date/character. Latest date to include (UTC). |
since_message_id |
integer or NULL. If set, only fetch messages with id > this value
(incremental/resume download). Maps to |
show_progress |
logical. If TRUE, display a progress bar. |
timeout_sec |
numeric. Max seconds to wait per fetch before retrying. Use 0 to disable. |
max_timeouts |
integer. Number of timeouts to tolerate before aborting. |
reconnect_on_timeout |
logical. If TRUE, reconnect client on timeout. |
output_file |
character or NULL. When set, rows are written to this CSV file in chunks rather than accumulated in memory. Returns the row count invisibly instead of a tibble. Appends to the file if it already exists (adds header only on first write). |
chunk_size |
integer. Number of rows to buffer before each write when
|
partial_on_error |
logical. If TRUE (default), non-timeout errors emit a warning and return the rows collected so far rather than throwing. If FALSE, errors propagate immediately. |
... |
Passed to client$iter_messages() (e.g. offset_id, max_id, min_id). |
A tibble (or invisible row count when output_file is set).
Fetches message reactions for a channel by username or numeric id.
download_channel_reactions( client, channel, limit = Inf, start_date = NULL, end_date = NULL, include_channel = TRUE, show_progress = TRUE, output_file = NULL, chunk_size = 5000L, ... )download_channel_reactions( client, channel, limit = Inf, start_date = NULL, end_date = NULL, include_channel = TRUE, show_progress = TRUE, output_file = NULL, chunk_size = 5000L, ... )
client |
TelegramClient instance. |
channel |
character or numeric. Channel username (with or without "@") or numeric id. |
limit |
integer or Inf. Maximum number of messages to fetch. |
start_date |
POSIXct/Date/character. Earliest date to include (UTC). |
end_date |
POSIXct/Date/character. Latest date to include (UTC). |
include_channel |
logical. If TRUE, include channel fields on every row. |
show_progress |
logical. If TRUE, display a progress bar. |
output_file |
character or NULL. When set, rows are written to this CSV file in chunks instead of being accumulated in memory. |
chunk_size |
integer. Number of rows to buffer before each write when |
... |
Passed to client$iter_messages() (e.g. offset_id, max_id, min_id). |
A tibble.
Fetches replies (comments) to channel posts by username or numeric id.
download_channel_replies( client, channel, message_ids = NULL, message_limit = 100, reply_limit = Inf, include_channel = TRUE, show_progress = TRUE, output_file = NULL, chunk_size = 5000L, ... )download_channel_replies( client, channel, message_ids = NULL, message_limit = 100, reply_limit = Inf, include_channel = TRUE, show_progress = TRUE, output_file = NULL, chunk_size = 5000L, ... )
client |
TelegramClient instance. |
channel |
character or numeric. Channel username (with or without "@") or numeric id. |
message_ids |
integer vector or NULL. If NULL, replies are fetched for the most recent posts. |
message_limit |
integer. Number of recent posts to inspect when message_ids is NULL. |
reply_limit |
integer or Inf. Maximum number of replies per post. |
include_channel |
logical. If TRUE, include channel fields on every row. |
show_progress |
logical. If TRUE, display a progress bar. |
output_file |
character or NULL. When set, rows are written to this CSV file in chunks instead of being accumulated in memory. |
chunk_size |
integer. Number of rows to buffer before each write when |
... |
Passed to client$iter_messages() when fetching recent posts. |
A tibble.
Gets the latest message ID and uses it as an upper-bound estimate of total posts. This is approximate due to deletions and gaps in message IDs.
estimate_channel_post_count( client, channel, timeout_sec = getOption("telegramR.iter_timeout", 60), reconnect_on_timeout = TRUE )estimate_channel_post_count( client, channel, timeout_sec = getOption("telegramR.iter_timeout", 60), reconnect_on_timeout = TRUE )
client |
TelegramClient instance. |
channel |
character or numeric. Channel username (with or without "@") or numeric id. |
timeout_sec |
numeric. Timeout in seconds for network operations. |
reconnect_on_timeout |
logical. Reconnect on timeout if TRUE. |
A tibble with last_message_id and a note.
Retrieve full information about a user
get_full_user(client, user = "me")get_full_user(client, user = "me")
client |
TelegramClient instance. |
user |
User (username, id, link) or "me". |
The API response (UserFull).
Increase view count for channel messages
increase_view_count(client, channel, message_ids)increase_view_count(client, channel, message_ids)
client |
TelegramClient instance. |
channel |
Channel (username, link, or entity). |
message_ids |
Numeric vector of message IDs. |
The API response (views).
Join a chat or channel by username or invite link
join_channel(client, channel)join_channel(client, channel)
client |
TelegramClient instance. |
channel |
Username/link or invite link. |
The API response.
Join a private chat or channel by invite link
join_private_chat(client, invite_link)join_private_chat(client, invite_link)
client |
TelegramClient instance. |
invite_link |
Invite link (e.g. https://t.me/joinchat/... or https://t.me/+...). |
The API response.
Join a public channel by username
join_public_channel(client, channel)join_public_channel(client, channel)
client |
TelegramClient instance. |
channel |
Public channel username or link (non-invite). |
The API response.
These helpers port the functionality of bellingcat's telegram-phone-number-checker Python tool to R. They use the currently authenticated [TelegramClient] to look up users by phone number (via 'ImportContactsRequest' / 'DeleteContactsRequest') or by username (via 'client$get_entity()'), and return the public profile fields Telegram returns about the matched user.
Phone-number lookups briefly add the number to your contact list and then delete it. Telegram throttles abusive callers — Bellingcat recommends using a fresh, residential-IP account rather than a personal one.
Convenience wrapper to send an audio file to a target entity.
send_audio(client, entity, file, ...)send_audio(client, entity, file, ...)
client |
TelegramClient instance. |
entity |
Target entity (username, id, or TLObject). |
file |
Audio file path or file-like object. |
... |
Additional arguments passed to 'TelegramClient$send_message()' (e.g., 'message', 'attributes', 'thumb', 'parse_mode', 'buttons'). |
The sent message object (or Updates result).
Convenience wrapper to send a document (file) to a target entity.
send_document(client, entity, file, ...)send_document(client, entity, file, ...)
client |
TelegramClient instance. |
entity |
Target entity (username, id, or TLObject). |
file |
File path or file-like object. |
... |
Additional arguments passed to 'TelegramClient$send_message()' (e.g., 'message', 'attributes', 'thumb', 'parse_mode', 'buttons'). |
The sent message object (or Updates result).
Convenience wrapper around 'TelegramClient$send_message()' that sends a file and resolves futures/promises.
send_file(client, entity, file, ...)send_file(client, entity, file, ...)
client |
TelegramClient instance. |
entity |
Target entity (username, id, or TLObject). |
file |
File path or file-like object. |
... |
Additional arguments passed to 'TelegramClient$send_message()' (e.g., 'message', 'force_document', 'attributes', 'thumb', 'parse_mode'). |
The sent message object (or Updates result).
Convenience wrapper around 'TelegramClient$send_message()' that resolves futures/promises and returns the sent message (or Updates object).
send_message(client, entity, ...)send_message(client, entity, ...)
client |
TelegramClient instance. |
entity |
Target entity (username, id, or TLObject). |
... |
Passed to 'TelegramClient$send_message()'. |
The sent message object (or Updates result).
Convenience wrapper to send a photo to a target entity.
send_photo(client, entity, file, ...)send_photo(client, entity, file, ...)
client |
TelegramClient instance. |
entity |
Target entity (username, id, or TLObject). |
file |
Photo file path or file-like object. |
... |
Additional arguments passed to 'TelegramClient$send_message()' (e.g., 'message', 'parse_mode', 'buttons'). |
The sent message object (or Updates result).
Convenience wrapper to send a video to a target entity.
send_video(client, entity, file, ...)send_video(client, entity, file, ...)
client |
TelegramClient instance. |
entity |
Target entity (username, id, or TLObject). |
file |
Video file path or file-like object. |
... |
Additional arguments passed to 'TelegramClient$send_message()' (e.g., 'message', 'supports_streaming', 'parse_mode', 'buttons'). |
The sent message object (or Updates result).
Low-level Telegram MTProto client. Most users should use TelegramClient.
TelegramBaseClientTelegramBaseClient
This is an R6 class providing lower-level transport and protocol operations.
An R6 object of class TelegramBaseClient.
## Not run: client <- TelegramClient$new("my_session", api_id = 123, api_hash = "abc") client$connect() ## End(Not run)## Not run: client <- TelegramClient$new("my_session", api_id = 123, api_hash = "abc") client$connect() ## End(Not run)
High-level Telegram MTProto client. Use TelegramClient$new() to create a session and connect.
TelegramClientTelegramClient
This is an R6 class. Typical usage:
client <- TelegramClient$new("my_session", api_id = 123, api_hash = "...")
client$connect()
An R6 object of class TelegramClient.
## Not run: client <- TelegramClient$new("my_session", api_id = 123, api_hash = "...") client$connect() ## End(Not run)## Not run: client <- TelegramClient$new("my_session", api_id = 123, api_hash = "...") client$connect() ## End(Not run)
Update your name and/or bio
update_profile(client, first_name = NULL, last_name = NULL, bio = NULL)update_profile(client, first_name = NULL, last_name = NULL, bio = NULL)
client |
TelegramClient instance. |
first_name |
First name (optional). |
last_name |
Last name (optional). |
bio |
About/bio text (optional). |
The API response.
Update your profile photo
update_profile_photo(client, file, progress_callback = NULL)update_profile_photo(client, file, progress_callback = NULL)
client |
TelegramClient instance. |
file |
Path to image file. |
progress_callback |
Optional callback (pos, total). |
The API response.
Update your username
update_username(client, username)update_username(client, username)
client |
TelegramClient instance. |
username |
New username (without @). |
The API response.