Title: | Develop a 'Telegram Bot' with R |
---|---|
Description: | Provides a pure interface for the 'Telegram Bot API' <http://core.telegram.org/bots/api>. In addition to the pure API implementation, it features a number of tools to make the development of 'Telegram' bots with R easy and straightforward, providing an easy-to-use interface that takes some work off the programmer. |
Authors: | Ernest Benedito [aut, cre], Chris Stefano [ctb] |
Maintainer: | Ernest Benedito <[email protected]> |
License: | GPL-3 |
Version: | 3.0.0 |
Built: | 2024-10-29 04:17:30 UTC |
Source: | https://github.com/ebeneditos/telegram.bot |
With +
you can add any kind of Handler
to
an Updater
's Dispatcher
(or directly to a
Dispatcher
).
## S3 method for class 'TelegramObject' e1 + e2
## S3 method for class 'TelegramObject' e1 + e2
e1 |
An object of class |
e2 |
An object of class |
See add_handler
for further information.
## Not run: # You can chain multiple handlers start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } echo <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = update$message$text ) } updater <- Updater("TOKEN") + CommandHandler("start", start) + MessageHandler(echo, MessageFilters$text) # And keep adding... caps <- function(bot, update, args) { if (length(args > 0L)) { text_caps <- toupper(paste(args, collapse = " ")) bot$sendMessage( chat_id = update$message$chat_id, text = text_caps ) } } updater <- updater + CommandHandler("caps", caps, pass_args = TRUE) # Give it a try! updater$start_polling() # Send '/start' to the bot, '/caps foo' or just a simple text ## End(Not run)
## Not run: # You can chain multiple handlers start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } echo <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = update$message$text ) } updater <- Updater("TOKEN") + CommandHandler("start", start) + MessageHandler(echo, MessageFilters$text) # And keep adding... caps <- function(bot, update, args) { if (length(args > 0L)) { text_caps <- toupper(paste(args, collapse = " ")) bot$sendMessage( chat_id = update$message$chat_id, text = text_caps ) } } updater <- updater + CommandHandler("caps", caps, pass_args = TRUE) # Give it a try! updater$start_polling() # Send '/start' to the bot, '/caps foo' or just a simple text ## End(Not run)
Registers an error handler in the Dispatcher
.
add_error_handler(callback)
add_error_handler(callback)
callback |
A function that takes |
You can also use add_handler
to register error handlers
if the handler is of type ErrorHandler
.
## Not run: updater <- Updater(token = "TOKEN") # Create error callback error_callback <- function(bot, error) { warning(simpleWarning(conditionMessage(error), call = "Updates polling")) } # Register it to the updater's dispatcher updater$dispatcher$add_error_handler(error_callback) # or updater$dispatcher$add_handler(ErrorHandler(error_callback)) # or updater <- updater + ErrorHandler(error_callback) ## End(Not run)
## Not run: updater <- Updater(token = "TOKEN") # Create error callback error_callback <- function(bot, error) { warning(simpleWarning(conditionMessage(error), call = "Updates polling")) } # Register it to the updater's dispatcher updater$dispatcher$add_error_handler(error_callback) # or updater$dispatcher$add_handler(ErrorHandler(error_callback)) # or updater <- updater + ErrorHandler(error_callback) ## End(Not run)
Register a handler. A handler must be an instance of a subclass of
Handler
. All handlers are organized in groups with a numeric
value. The default group is 1. All groups will be evaluated for handling an
update, but only 0 or 1 handler per group will be used.
add_handler(handler, group = 1L)
add_handler(handler, group = 1L)
handler |
A |
group |
The group identifier, must be higher or equal to 1. Default is 1. |
You can use the add
(+
) operator instead.
The priority/order of handlers is determined as follows:
Priority of the group (lower group number = higher priority)
The first handler in a group which should handle an update will be used. Other handlers from the group will not be used. The order in which handlers were added to the group defines the priority (the first handler added in a group has the highest priority).
Use this method to send answers to callback queries sent from inline
keyboards. The answer will be displayed to the user as a notification at the
top of the chat screen or as an alert. On success, TRUE
is returned.
answerCallbackQuery( callback_query_id, text = NULL, show_alert = FALSE, url = NULL, cache_time = NULL )
answerCallbackQuery( callback_query_id, text = NULL, show_alert = FALSE, url = NULL, cache_time = NULL )
callback_query_id |
Unique identifier for the query to be answered. |
text |
(Optional). Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters. |
show_alert |
(Optional). If |
url |
(Optional). URL that will be opened by the user's client. |
cache_time |
(Optional). The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. |
You can also use it's snake_case equivalent answer_callback_query
.
Use this method to send answers to an inline query. No more than 50 results per query are allowed.
answerInlineQuery( inline_query_id, results, cache_time = 300L, is_personal = NULL, next_offset = NULL, switch_pm_text = NULL, switch_pm_parameter = NULL )
answerInlineQuery( inline_query_id, results, cache_time = 300L, is_personal = NULL, next_offset = NULL, switch_pm_text = NULL, switch_pm_parameter = NULL )
inline_query_id |
Unique identifier for the answered query. |
results |
A list of |
cache_time |
(Optional). The maximum amount of time in seconds that the result of the inline query may be cached on the server. |
is_personal |
(Optional). Pass |
next_offset |
(Optional). Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes. |
switch_pm_text |
(Optional). If passed, clients will display a button
with specified text that switches the user to a private chat with the
bot and sends the bot a start message with the parameter
|
switch_pm_parameter |
(Optional). Deep-linking parameter for the
Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an auth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities. |
To enable this option, send the /setinline
command to
@BotFather and provide the placeholder text
that the user will see in the input field after typing your bot's name.
You can also use it's snake_case equivalent answer_inline_query
.
Base class for all Message Filters.
BaseFilter(filter) as.BaseFilter(x, ...) is.BaseFilter(x)
BaseFilter(filter) as.BaseFilter(x, ...) is.BaseFilter(x)
filter |
If you want to create your own filters you can call this
generator passing by a |
x |
Object to be coerced or tested. |
... |
Further arguments passed to or from other methods. |
See filtersLogic
to know more about combining filter
functions.
## Not run: # Create a filter function text_or_command <- function(message) !is.null(message$text) # Make it an instance of BaseFilter with its generator: text_or_command <- BaseFilter(filter = text_or_command) # Or by coercing it with as.BaseFilter: text_or_command <- as.BaseFilter(function(message) !is.null(message$text)) ## End(Not run)
## Not run: # Create a filter function text_or_command <- function(message) !is.null(message$text) # Make it an instance of BaseFilter with its generator: text_or_command <- BaseFilter(filter = text_or_command) # Or by coercing it with as.BaseFilter: text_or_command <- as.BaseFilter(function(message) !is.null(message$text)) ## End(Not run)
This object represents a Telegram Bot.
Bot(token, base_url = NULL, base_file_url = NULL, request_config = NULL) is.Bot(x)
Bot(token, base_url = NULL, base_file_url = NULL, request_config = NULL) is.Bot(x)
token |
The bot's token given by the BotFather. |
base_url |
(Optional). Telegram Bot API service URL. |
base_file_url |
(Optional). Telegram Bot API file URL. |
request_config |
(Optional). Additional configuration settings
to be passed to the bot's POST requests. See the The |
x |
Object to be tested. |
An R6Class
object.
To take full advantage of this library take a look at Updater
.
You can also use its methods snake_case
equivalent.
answerCallbackQuery
Send answers to callback queries
answerInlineQuery
Send answers to an inline query
deleteMessage
Delete a message
deleteWebhook
Remove webhook integration
editMessageText
Edit a text message
editMessageCaption
Edit a caption
editMessageReplyMarkup
Edit the reply markup of a message
forwardMessage
Forward messages of any kind
getFile
Prepare a file for downloading
getMe
Check your bot's information
getUpdates
Receive incoming updates
getUserProfilePhotos
Get a user's profile photos
getWebhookInfo
Get current webhook status
leaveChat
Leave a chat
sendAnimation
Send animation files
sendAudio
Send audio files
sendChatAction
Send a chat action
sendDocument
Send general files
sendLocation
Send point on the map
sendMessage
Send text messages
sendPhoto
Send image files
sendSticker
Send a sticker
sendVideo
Send a video
sendVideoNote
Send video messages
sendVoice
Send voice files
setWebhook
Set a webhook
clean_updates
Clean any pending updates
set_token
Change your bot's auth token
## Not run: bot <- Bot(token = "TOKEN") # In case you want to set a proxy (see ?httr:use_proxy) bot <- Bot( token = "TOKEN", request_config = httr::use_proxy(...) ) ## End(Not run)
## Not run: bot <- Bot(token = "TOKEN") # In case you want to set a proxy (see ?httr:use_proxy) bot <- Bot( token = "TOKEN", request_config = httr::use_proxy(...) ) ## End(Not run)
Obtain token from system variables (in .Renviron
) set
according to the naming convention R_TELEGRAM_BOT_X
where X
is the bot's name.
bot_token(bot_name)
bot_token(bot_name)
bot_name |
The bot's name. |
## Not run: # Open the `.Renviron` file file.edit(path.expand(file.path("~", ".Renviron"))) # Add the line (uncomment and replace <bot-token> by your bot TOKEN): # R_TELEGRAM_BOT_RTelegramBot=<bot-token> # Save and restart R bot_token("RTelegramBot") ## End(Not run)
## Not run: # Open the `.Renviron` file file.edit(path.expand(file.path("~", ".Renviron"))) # Add the line (uncomment and replace <bot-token> by your bot TOKEN): # R_TELEGRAM_BOT_RTelegramBot=<bot-token> # Save and restart R bot_token("RTelegramBot") ## End(Not run)
Handler
class to handle Telegram callback queries. Optionally
based on a regex.
CallbackQueryHandler(callback, pattern = NULL)
CallbackQueryHandler(callback, pattern = NULL)
callback |
The callback function for this handler.
See |
pattern |
(Optional). Regex pattern to test. |
An R6Class
object.
This method is called to determine if an update should be handled by
this handler instance. It should always be overridden (see
Handler
).
check_update(update)
check_update(update)
update |
The update to be tested. |
Use this method to clean any pending updates on Telegram servers. Requires no parameters.
clean_updates()
clean_updates()
Handler
class to handle Telegram commands.
CommandHandler( command, callback, filters = NULL, pass_args = FALSE, username = NULL )
CommandHandler( command, callback, filters = NULL, pass_args = FALSE, username = NULL )
command |
The command or vector of commands this handler should listen for. |
callback |
The callback function for this handler.
See |
filters |
(Optional). Only allow updates with these filters. See
|
pass_args |
(Optional). Determines whether the handler should be passed
|
username |
(Optional). Bot's username, you can retrieve it from
|
An R6Class
object.
## Not run: # Initialize bot bot <- Bot("TOKEN") username <- bot$getMe()$username updater <- Updater(bot = bot) # Add a command start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = "Hi, I am a bot!" ) } updater <- updater + CommandHandler("start", start, username = username) ## End(Not run)
## Not run: # Initialize bot bot <- Bot("TOKEN") username <- bot$getMe()$username updater <- Updater(bot = bot) # Add a command start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = "Hi, I am a bot!" ) } updater <- updater + CommandHandler("start", start, username = username) ## End(Not run)
Use this method to delete a message. A message can only be deleted if it was sent less than 48 hours ago. Any such recently sent outgoing message may be deleted. Additionally, if the bot is an administrator in a group chat, it can delete any message. If the bot is an administrator in a supergroup, it can delete messages from any other user and service messages about people joining or leaving the group (other types of service messages may only be removed by the group creator). In channels, bots can only remove their own messages.
deleteMessage(chat_id, message_id)
deleteMessage(chat_id, message_id)
chat_id |
Unique identifier for the target chat or username of the target channel. |
message_id |
Identifier of the message to delete. |
You can also use it's snake_case equivalent delete_message
.
Use this method to remove webhook integration if you decide to switch back
to getUpdates
. Requires no parameters.
deleteWebhook()
deleteWebhook()
You can also use it's snake_case equivalent delete_webhook
.
This class dispatches all kinds of updates to its registered handlers.
Dispatcher(bot) is.Dispatcher(x)
Dispatcher(bot) is.Dispatcher(x)
bot |
The bot object that should be passed to the handlers. |
x |
Object to be tested. |
An R6Class
object.
add_handler
Registers a handler in the
Dispatcher
.
add_error_handler
Registers an error handler in the
Dispatcher
.
Use this method to edit captions of messages.
editMessageCaption( chat_id = NULL, message_id = NULL, inline_message_id = NULL, caption = NULL, parse_mode = NULL, reply_markup = NULL )
editMessageCaption( chat_id = NULL, message_id = NULL, inline_message_id = NULL, caption = NULL, parse_mode = NULL, reply_markup = NULL )
chat_id |
(Optional). Unique identifier for the target chat or username of the target channel. |
message_id |
(Optional). Required if inline_message_id is not specified. Identifier of the sent message. |
inline_message_id |
(Optional). Required if chat_id and message_id are not specified. Identifier of the inline message. |
caption |
(Optional). New caption of the message. |
parse_mode |
(Optional). Send 'Markdown' or 'HTML', if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. |
reply_markup |
(Optional). A Reply Markup parameter object, it can be either: |
You can also use it's snake_case equivalent
edit_message_caption
.
Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
editMessageReplyMarkup( chat_id = NULL, message_id = NULL, inline_message_id = NULL, reply_markup = NULL )
editMessageReplyMarkup( chat_id = NULL, message_id = NULL, inline_message_id = NULL, reply_markup = NULL )
chat_id |
(Optional). Unique identifier for the target chat or username of the target channel. |
message_id |
(Optional). Required if inline_message_id is not specified. Identifier of the sent message. |
inline_message_id |
(Optional). Required if chat_id and message_id are not specified. Identifier of the inline message. |
reply_markup |
(Optional). A Reply Markup parameter object, it can be either: |
You can also use it's snake_case equivalent
edit_message_reply_markup
.
Use this method to edit text messages.
editMessageText( chat_id = NULL, message_id = NULL, inline_message_id = NULL, text, parse_mode = NULL, disable_web_page_preview = NULL, reply_markup = NULL )
editMessageText( chat_id = NULL, message_id = NULL, inline_message_id = NULL, text, parse_mode = NULL, disable_web_page_preview = NULL, reply_markup = NULL )
chat_id |
(Optional). Unique identifier for the target chat or username of the target channel. |
message_id |
(Optional). Required if inline_message_id is not specified. Identifier of the sent message. |
inline_message_id |
(Optional). Required if chat_id and message_id are not specified. Identifier of the inline message. |
text |
New text of the message. |
parse_mode |
(Optional). Send 'Markdown' or 'HTML', if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. |
disable_web_page_preview |
(Optional). Disables link previews for links in this message. |
reply_markup |
(Optional). A Reply Markup parameter object, it can be either: |
You can also use it's snake_case equivalent
edit_message_text
.
The chat that this update was sent in, no matter what kind of
update this is. Will be None
for inline_query
,
chosen_inline_result
, callback_query
from inline messages,
shipping_query
and pre_checkout_query
.
effective_chat()
effective_chat()
The message included in this update, no matter what kind of
update this is. Will be None
for inline_query
,
chosen_inline_result
, callback_query
from inline messages,
shipping_query
and pre_checkout_query
.
effective_message()
effective_message()
The user that sent this update, no matter what kind of update this
is. Will be NULL
for channel_post
.
effective_user()
effective_user()
Handler
class to handle errors in the
Dispatcher
.
ErrorHandler(callback) is.ErrorHandler(x)
ErrorHandler(callback) is.ErrorHandler(x)
callback |
A function that takes |
x |
Object to be tested. |
An R6Class
object.
## Not run: updater <- Updater(token = "TOKEN") # Create error callback error_callback <- function(bot, error) { warning(simpleWarning(conditionMessage(error), call = "Updates polling")) } # Register it to the updater's dispatcher updater$dispatcher$add_handler(ErrorHandler(error_callback)) # or updater <- updater + ErrorHandler(error_callback) ## End(Not run)
## Not run: updater <- Updater(token = "TOKEN") # Create error callback error_callback <- function(bot, error) { warning(simpleWarning(conditionMessage(error), call = "Updates polling")) } # Register it to the updater's dispatcher updater$dispatcher$add_handler(ErrorHandler(error_callback)) # or updater <- updater + ErrorHandler(error_callback) ## End(Not run)
Creates a function which returns the corresponding logical
operation between what f
and g
return.
## S3 method for class 'BaseFilter' !f ## S3 method for class 'BaseFilter' f & g ## S3 method for class 'BaseFilter' f | g
## S3 method for class 'BaseFilter' !f ## S3 method for class 'BaseFilter' f & g ## S3 method for class 'BaseFilter' f | g
f , g
|
Arbitrary |
See BaseFilter
and MessageFilters
for
further details.
not_command <- !MessageFilters$command text_and_reply <- MessageFilters$text & MessageFilters$reply audio_or_video <- MessageFilters$audio | MessageFilters$video
not_command <- !MessageFilters$command text_and_reply <- MessageFilters$text & MessageFilters$reply audio_or_video <- MessageFilters$audio | MessageFilters$video
Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply').
ForceReply(force_reply = TRUE, selective = NULL)
ForceReply(force_reply = TRUE, selective = NULL)
force_reply |
Shows reply interface to the user, as if they manually
selected the bot's message and tapped 'Reply'. Defaults to |
selective |
(Optional). Use this parameter if you want to show the keyboard to specific users only. |
## Not run: # Initialize bot bot <- Bot(token = "TOKEN") chat_id <- "CHAT_ID" # Set input parameters text <- "Don't forget to send me the answer!" # Send reply message bot$sendMessage(chat_id, text, reply_markup = ForceReply()) ## End(Not run)
## Not run: # Initialize bot bot <- Bot(token = "TOKEN") chat_id <- "CHAT_ID" # Set input parameters text <- "Don't forget to send me the answer!" # Send reply message bot$sendMessage(chat_id, text, reply_markup = ForceReply()) ## End(Not run)
Use this method to forward messages of any kind.
forwardMessage(chat_id, from_chat_id, message_id, disable_notification = FALSE)
forwardMessage(chat_id, from_chat_id, message_id, disable_notification = FALSE)
chat_id |
Unique identifier for the target chat or username of the target channel. |
from_chat_id |
Unique identifier for the chat where the original message was sent. |
message_id |
Message identifier in the chat specified in from_chat_id. |
disable_notification |
(Optional). Sends the message silently. Users will receive a notification with no sound. |
You can also use it's snake_case equivalent forward_message
.
Get the id
from the Update
's effective chat.
from_chat_id()
from_chat_id()
Get the id
from the Update
's effective user.
from_user_id()
from_user_id()
Use this method to get basic info about a file and prepare it for
downloading. For the moment, bots can download files of up to 20MB in size.
It is guaranteed that the link will be valid for at least 1 hour. When the
link expires, a new one can be requested by calling getFile
again.
getFile(file_id, destfile = NULL, ...)
getFile(file_id, destfile = NULL, ...)
file_id |
The file identifier. |
destfile |
(Optional). If you want to save the file, pass by a
character string with the name where the downloaded file is saved.
See the |
... |
(Optional). Additional parameters to be passed to
|
You can also use it's snake_case equivalent get_file
.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") photos <- bot$getUserProfilePhotos(chat_id = chat_id) # Download user profile photo file_id <- photos$photos[[1L]][[1L]]$file_id bot$getFile(file_id, destfile = "photo.jpg") ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") photos <- bot$getUserProfilePhotos(chat_id = chat_id) # Download user profile photo file_id <- photos$photos[[1L]][[1L]]$file_id bot$getFile(file_id, destfile = "photo.jpg") ## End(Not run)
A simple method for testing your bot's auth token. Requires no parameters.
getMe()
getMe()
You can also use it's snake_case equivalent get_me
.
Use this method to receive incoming updates. It returns a
list of Update
objects.
getUpdates(offset = NULL, limit = 100L, timeout = 0L, allowed_updates = NULL)
getUpdates(offset = NULL, limit = 100L, timeout = 0L, allowed_updates = NULL)
offset |
(Optional). Identifier of the first update to be returned. |
limit |
(Optional). Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100. |
timeout |
(Optional). Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only. |
allowed_updates |
(Optional). String or vector of strings with the
types of updates you want your bot to receive. For example, specify
Please note that this parameter doesn't affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time. |
1. This method will not work if an outgoing webhook is set up.
2. In order to avoid getting duplicate updates, recalculate offset after
each server response or use Bot
method clean_updates
.
3. To take full advantage of this library take a look at
Updater
.
You can also use it's snake_case equivalent get_updates
.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) updates <- bot$getUpdates() ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) updates <- bot$getUpdates() ## End(Not run)
Use this method to get a list of profile pictures for a user.
getUserProfilePhotos(user_id, offset = NULL, limit = 100L)
getUserProfilePhotos(user_id, offset = NULL, limit = 100L)
user_id |
Unique identifier of the target user. |
offset |
(Optional). Sequential number of the first photo to be returned. By default, all photos are returned. |
limit |
(Optional). Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100. |
You can also use it's snake_case equivalent get_user_profile_photos
.
See getFile
to know how to download files.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") photos <- bot$getUserProfilePhotos(chat_id = chat_id) ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") photos <- bot$getUserProfilePhotos(chat_id = chat_id) ## End(Not run)
Use this method to get current webhook status. Requires no parameters.
getWebhookInfo()
getWebhookInfo()
If the bot is using getUpdates
, will return an object with the url
field empty.
You can also use it's snake_case equivalent get_webhook_info
.
This method is called if it was determined that an update should indeed
be handled by this instance. It should also be overridden (see
Handler
).
handle_update(update, dispatcher)
handle_update(update, dispatcher)
update |
The update to be handled. |
dispatcher |
The dispatcher to collect optional arguments. |
In most cases self$callback(dispatcher$bot, update)
can be called,
possibly along with optional arguments.
The base class for all update handlers. Create custom handlers by inheriting from it.
Handler( callback, check_update = NULL, handle_update = NULL, handlername = NULL ) is.Handler(x)
Handler( callback, check_update = NULL, handle_update = NULL, handlername = NULL ) is.Handler(x)
callback |
The callback function for this handler. Its inputs will be
|
check_update |
Function that will override the default
|
handle_update |
Function that will override the default
|
handlername |
Name of the customized class, which will inherit from
|
x |
Object to be tested. |
An R6Class
object.
check_update
Called to determine if an update should be handled by this handler instance.
handle_update
Called if it was determined that an update should indeed be handled by this instance.
MessageHandler
To handle Telegram messages.
CommandHandler
To handle Telegram commands.
CallbackQueryHandler
To handle Telegram callback queries.
ErrorHandler
To handle errors while polling for updates.
## Not run: # Example of a Handler callback_method <- function(bot, update) { chat_id <- update$effective_chat()$id bot$sendMessage(chat_id = chat_id, text = "Hello") } hello_handler <- Handler(callback_method) # Customizing Handler check_update <- function(update) { TRUE } handle_update <- function(update, dispatcher) { self$callback(dispatcher$bot, update) } foo_handler <- Handler(callback_method, check_update = check_update, handle_update = handle_update, handlername = "FooHandler" ) ## End(Not run)
## Not run: # Example of a Handler callback_method <- function(bot, update) { chat_id <- update$effective_chat()$id bot$sendMessage(chat_id = chat_id, text = "Hello") } hello_handler <- Handler(callback_method) # Customizing Handler check_update <- function(update) { TRUE } handle_update <- function(update, dispatcher) { self$callback(dispatcher$bot, update) } foo_handler <- Handler(callback_method, check_update = check_update, handle_update = handle_update, handlername = "FooHandler" ) ## End(Not run)
This object represents one button of an inline keyboard. You
must use exactly one of the optional fields. If all optional fields
are NULL, by defect it will generate callback_data
with same data as
in text
.
InlineKeyboardButton( text, url = NULL, callback_data = NULL, switch_inline_query = NULL, switch_inline_query_current_chat = NULL ) is.InlineKeyboardButton(x)
InlineKeyboardButton( text, url = NULL, callback_data = NULL, switch_inline_query = NULL, switch_inline_query_current_chat = NULL ) is.InlineKeyboardButton(x)
text |
Label text on the button. |
url |
(Optional). HTTP url to be opened when button is pressed. |
callback_data |
(Optional). Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes. |
switch_inline_query |
(Optional). If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. Can be empty, in which case just the bot's username will be inserted. |
switch_inline_query_current_chat |
(Optional). If set, pressing the button will insert the bot's username and the specified inline query in the current chat's input field. Can be empty, in which case only the bot's username will be inserted. |
x |
Object to be tested. |
Note: After the user presses a callback button,
Telegram clients will display a progress bar until you call
answerCallbackQuery
. It is, therefore, necessary to
react by calling answerCallbackQuery
even if no notification
to the user is needed (e.g., without specifying any of the
optional parameters).
This object represents an inline keyboard that appears right next to the message it belongs to.
InlineKeyboardMarkup(inline_keyboard)
InlineKeyboardMarkup(inline_keyboard)
inline_keyboard |
List of button rows, each represented by a list of
|
Note: After the user presses a callback button,
Telegram clients will display a progress bar until you call
answerCallbackQuery
. It is, therefore, necessary to
react by calling answerCallbackQuery
even if no notification
to the user is needed (e.g., without specifying any of the
optional parameters).
## Not run: # Initialize bot bot <- Bot(token = "TOKEN") chat_id <- "CHAT_ID" # Create Inline Keyboard text <- "Could you type their phone number, please?" IKM <- InlineKeyboardMarkup( inline_keyboard = list( list( InlineKeyboardButton(1), InlineKeyboardButton(2), InlineKeyboardButton(3) ), list( InlineKeyboardButton(4), InlineKeyboardButton(5), InlineKeyboardButton(6) ), list( InlineKeyboardButton(7), InlineKeyboardButton(8), InlineKeyboardButton(9) ), list( InlineKeyboardButton("*"), InlineKeyboardButton(0), InlineKeyboardButton("#") ) ) ) # Send Inline Keyboard bot$sendMessage(chat_id, text, reply_markup = IKM) ## End(Not run)
## Not run: # Initialize bot bot <- Bot(token = "TOKEN") chat_id <- "CHAT_ID" # Create Inline Keyboard text <- "Could you type their phone number, please?" IKM <- InlineKeyboardMarkup( inline_keyboard = list( list( InlineKeyboardButton(1), InlineKeyboardButton(2), InlineKeyboardButton(3) ), list( InlineKeyboardButton(4), InlineKeyboardButton(5), InlineKeyboardButton(6) ), list( InlineKeyboardButton(7), InlineKeyboardButton(8), InlineKeyboardButton(9) ), list( InlineKeyboardButton("*"), InlineKeyboardButton(0), InlineKeyboardButton("#") ) ) ) # Send Inline Keyboard bot$sendMessage(chat_id, text, reply_markup = IKM) ## End(Not run)
Baseclass for the InlineQueryResult* classes.
InlineQueryResult(type, id, ...) is.InlineQueryResult(x)
InlineQueryResult(type, id, ...) is.InlineQueryResult(x)
type |
Type of the result. See the documentation for a list of supported types. |
id |
Unique identifier for this result, 1-64 Bytes. |
... |
Additional parameters for the selected type. See the
documentation
for the description of the
parameters depending on the |
x |
Object to be tested. |
## Not run: document_url <- paste0( "https://github.com/ebeneditos/telegram.bot/raw/gh-pages/docs/", "telegram.bot.pdf" ) result <- InlineQueryResult( type = "document", id = 1, title = "Documentation", document_url = document_url, mime_type = "application/pdf" ) ## End(Not run)
## Not run: document_url <- paste0( "https://github.com/ebeneditos/telegram.bot/raw/gh-pages/docs/", "telegram.bot.pdf" ) result <- InlineQueryResult( type = "document", id = 1, title = "Documentation", document_url = document_url, mime_type = "application/pdf" ) ## End(Not run)
This object represents one button of the reply keyboard. Optional fields are mutually exclusive.
KeyboardButton(text, request_contact = NULL, request_location = NULL) is.KeyboardButton(x)
KeyboardButton(text, request_contact = NULL, request_location = NULL) is.KeyboardButton(x)
text |
Text of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed. |
request_contact |
(Optional). If |
request_location |
(Optional). If |
x |
Object to be tested. |
Note: request_contact
and request_location
options will only work in Telegram versions released after 9 April,
2016. Older clients will ignore them.
Use this method for your bot to leave a group, supergroup or channel.
leaveChat(chat_id)
leaveChat(chat_id)
chat_id |
Unique identifier for the target chat or username of the target channel. |
You can also use it's snake_case equivalent leave_chat
.
Predefined filters for use as the filter
argument of class
MessageHandler
.
MessageFilters
MessageFilters
A list
with filtering functions.
See BaseFilter
and filtersLogic
for
advanced filters.
all
: All Messages.
text
: Text Messages.
command
: Messages starting with /
.
reply
: Messages that are a reply to another message.
audio
: Messages that contain audio.
document
: Messages that contain document.
photo
: Messages that contain photo.
sticker
: Messages that contain sticker.
video
: Messages that contain video.
voice
: Messages that contain voice.
contact
: Messages that contain contact.
location
: Messages that contain location.
venue
: Messages that are forwarded.
game
: Messages that contain game.
## Not run: # Use to filter all video messages video_handler <- MessageHandler(callback_method, MessageFilters$video) # To filter all contacts, etc. contact_handler <- MessageHandler(callback_method, MessageFilters$contact) ## End(Not run)
## Not run: # Use to filter all video messages video_handler <- MessageHandler(callback_method, MessageFilters$video) # To filter all contacts, etc. contact_handler <- MessageHandler(callback_method, MessageFilters$contact) ## End(Not run)
Handler
class to handle Telegram messages. They might contain
text, media or status updates.
MessageHandler(callback, filters = NULL)
MessageHandler(callback, filters = NULL)
callback |
The callback function for this handler.
See |
filters |
(Optional). Only allow updates with these filters. Use
|
An R6Class
object.
## Not run: callback_method <- function(bot, update) { chat_id <- update$message$chat_id bot$sendMessage(chat_id = chat_id, text = "Hello") } # No filtering message_handler <- MessageHandler(callback_method, MessageFilters$all) ## End(Not run)
## Not run: callback_method <- function(bot, update) { chat_id <- update$message$chat_id bot$sendMessage(chat_id = chat_id, text = "Hello") } # No filtering message_handler <- MessageHandler(callback_method, MessageFilters$all) ## End(Not run)
This object represents a custom keyboard with reply options.
ReplyKeyboardMarkup( keyboard, resize_keyboard = NULL, one_time_keyboard = NULL, selective = NULL )
ReplyKeyboardMarkup( keyboard, resize_keyboard = NULL, one_time_keyboard = NULL, selective = NULL )
keyboard |
List of button rows, each represented by a list of
|
resize_keyboard |
(Optional). Requests clients to resize the keyboard
vertically for optimal fit. Defaults to |
one_time_keyboard |
(Optional). Requests clients to hide the keyboard
as soon as it's been used. The keyboard will still be available, but
clients will automatically display the usual letter-keyboard in the
chat - the user can press a special button in the input field to see the
custom keyboard again. Defaults to |
selective |
(Optional). Use this parameter if you want to show the keyboard to specific users only. |
## Not run: # Initialize bot bot <- Bot(token = "TOKEN") chat_id <- "CHAT_ID" # Create Custom Keyboard text <- "Aren't those custom keyboards cool?" RKM <- ReplyKeyboardMarkup( keyboard = list( list(KeyboardButton("Yes, they certainly are!")), list(KeyboardButton("I'm not quite sure")), list(KeyboardButton("No...")) ), resize_keyboard = FALSE, one_time_keyboard = TRUE ) # Send Custom Keyboard bot$sendMessage(chat_id, text, reply_markup = RKM) ## End(Not run)
## Not run: # Initialize bot bot <- Bot(token = "TOKEN") chat_id <- "CHAT_ID" # Create Custom Keyboard text <- "Aren't those custom keyboards cool?" RKM <- ReplyKeyboardMarkup( keyboard = list( list(KeyboardButton("Yes, they certainly are!")), list(KeyboardButton("I'm not quite sure")), list(KeyboardButton("No...")) ), resize_keyboard = FALSE, one_time_keyboard = TRUE ) # Send Custom Keyboard bot$sendMessage(chat_id, text, reply_markup = RKM) ## End(Not run)
Upon receiving a message with this object, Telegram clients will
remove the current custom keyboard and display the default
letter-keyboard. By default, custom keyboards are displayed until
a new keyboard is sent by a bot. An exception is made for one-time
keyboards that are hidden immediately after the user presses a
button (see ReplyKeyboardMarkup
).
ReplyKeyboardRemove(remove_keyboard = TRUE, selective = NULL)
ReplyKeyboardRemove(remove_keyboard = TRUE, selective = NULL)
remove_keyboard |
Requests clients to remove the custom keyboard.
(user will not be able to summon this keyboard; if you want to hide
the keyboard from sight but keep it accessible, use
|
selective |
(Optional). Use this parameter if you want to show the keyboard to specific users only. |
## Not run: # Initialize bot bot <- Bot(token = "TOKEN") chat_id <- "CHAT_ID" # Create Custom Keyboard text <- "Don't forget to send me the answer!" RKM <- ReplyKeyboardMarkup( keyboard = list( list(KeyboardButton("Yes, they certainly are!")), list(KeyboardButton("I'm not quite sure")), list(KeyboardButton("No...")) ), resize_keyboard = FALSE, one_time_keyboard = FALSE ) # Send Custom Keyboard bot$sendMessage(chat_id, text, reply_markup = RKM) # Remove Keyboard bot$sendMessage( chat_id, "Okay, thanks!", reply_markup = ReplyKeyboardRemove() ) ## End(Not run)
## Not run: # Initialize bot bot <- Bot(token = "TOKEN") chat_id <- "CHAT_ID" # Create Custom Keyboard text <- "Don't forget to send me the answer!" RKM <- ReplyKeyboardMarkup( keyboard = list( list(KeyboardButton("Yes, they certainly are!")), list(KeyboardButton("I'm not quite sure")), list(KeyboardButton("No...")) ), resize_keyboard = FALSE, one_time_keyboard = FALSE ) # Send Custom Keyboard bot$sendMessage(chat_id, text, reply_markup = RKM) # Remove Keyboard bot$sendMessage( chat_id, "Okay, thanks!", reply_markup = ReplyKeyboardRemove() ) ## End(Not run)
Returns TRUE
when listening for updates.
running()
running()
Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
sendAnimation( chat_id, animation, duration = NULL, width = NULL, height = NULL, caption = NULL, parse_mode = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL )
sendAnimation( chat_id, animation, duration = NULL, width = NULL, height = NULL, caption = NULL, parse_mode = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL )
chat_id |
Unique identifier for the target chat or username of the target channel. |
animation |
Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a local file by passing a file path. |
duration |
(Optional). Duration of sent audio in seconds. |
width |
(Optional). Video width. |
height |
(Optional). Video height. |
caption |
(Optional). Animation caption, 0-1024 characters. |
parse_mode |
(Optional). Send 'Markdown' or 'HTML', if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. |
disable_notification |
(Optional). Sends the message silently. Users will receive a notification with no sound. |
reply_to_message_id |
(Optional). If the message is a reply, ID of the original message. |
reply_markup |
(Optional). A Reply Markup parameter object, it can be either: |
You can also use it's snake_case equivalent send_animation
.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") animation_url <- "http://techslides.com/demos/sample-videos/small.mp4" bot$sendAnimation( chat_id = chat_id, animation = animation_url ) ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") animation_url <- "http://techslides.com/demos/sample-videos/small.mp4" bot$sendAnimation( chat_id = chat_id, animation = animation_url ) ## End(Not run)
Use this method to send audio files, if you want Telegram clients to display
them in the music player. Your audio must be in the .mp3 format. On success,
the sent Message is returned. Bots can currently send audio files of up to
50 MB in size, this limit may be changed in the future.
For sending voice messages, use the sendVoice
method instead.
sendAudio( chat_id, audio, duration = NULL, performer = NULL, title = NULL, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, parse_mode = NULL )
sendAudio( chat_id, audio, duration = NULL, performer = NULL, title = NULL, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, parse_mode = NULL )
chat_id |
Unique identifier for the target chat or username of the target channel. |
audio |
Audio file to send. Pass a file_id as String to send an audio that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio from the Internet, or upload a local audio file by passing a file path. |
duration |
(Optional). Duration of sent audio in seconds. |
performer |
(Optional). Performer. |
title |
(Optional). Track name. |
caption |
(Optional). Audio caption, 0-1024 characters. |
disable_notification |
(Optional). Sends the message silently. Users will receive a notification with no sound. |
reply_to_message_id |
(Optional). If the message is a reply, ID of the original message. |
reply_markup |
(Optional). A Reply Markup parameter object, it can be either: |
parse_mode |
(Optional). Send 'Markdown' or 'HTML', if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. |
You can also use it's snake_case equivalent send_audio
.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") audio_url <- "http://www.largesound.com/ashborytour/sound/brobob.mp3" bot$sendAudio( chat_id = chat_id, audio = audio_url ) ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") audio_url <- "http://www.largesound.com/ashborytour/sound/brobob.mp3" bot$sendAudio( chat_id = chat_id, audio = audio_url ) ## End(Not run)
Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status).
sendChatAction(chat_id, action)
sendChatAction(chat_id, action)
chat_id |
Unique identifier for the target chat or username of the target channel. |
action |
Type of action to broadcast. Choose one, depending on what the user is about to receive:
|
You can also use it's snake_case equivalent send_chat_action
.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") bot$sendChatAction( chat_id = chat_id, action = "typing" ) ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") bot$sendChatAction( chat_id = chat_id, action = "typing" ) ## End(Not run)
Use this method to send general files.
sendDocument( chat_id, document, filename = NULL, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, parse_mode = NULL )
sendDocument( chat_id, document, filename = NULL, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, parse_mode = NULL )
chat_id |
Unique identifier for the target chat or username of the target channel. |
document |
File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a local file by passing a file path |
filename |
(Optional). File name that shows in telegram message. |
caption |
(Optional). Document caption, 0-1024 characters. |
disable_notification |
(Optional). Sends the message silently. Users will receive a notification with no sound. |
reply_to_message_id |
(Optional). If the message is a reply, ID of the original message. |
reply_markup |
(Optional). A Reply Markup parameter object, it can be either: |
parse_mode |
(Optional). Send 'Markdown' or 'HTML', if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. |
You can also use it's snake_case equivalent send_document
.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") document_url <- paste0( "https://github.com/ebeneditos/telegram.bot/raw/gh-pages/docs/", "telegram.bot.pdf" ) bot$sendDocument( chat_id = chat_id, document = document_url ) ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") document_url <- paste0( "https://github.com/ebeneditos/telegram.bot/raw/gh-pages/docs/", "telegram.bot.pdf" ) bot$sendDocument( chat_id = chat_id, document = document_url ) ## End(Not run)
Use this method to send point on the map.
sendLocation( chat_id, latitude, longitude, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL )
sendLocation( chat_id, latitude, longitude, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL )
chat_id |
Unique identifier for the target chat or username of the target channel. |
latitude |
Latitude of location. |
longitude |
Longitude of location. |
disable_notification |
(Optional). Sends the message silently. Users will receive a notification with no sound. |
reply_to_message_id |
(Optional). If the message is a reply, ID of the original message. |
reply_markup |
(Optional). A Reply Markup parameter object, it can be either: |
You can also use it's snake_case equivalent send_location
.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") bot$sendLocation( chat_id = chat_id, latitude = 51.521727, longitude = -0.117255 ) ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") bot$sendLocation( chat_id = chat_id, latitude = 51.521727, longitude = -0.117255 ) ## End(Not run)
Use this method to send text messages.
sendMessage( chat_id, text, parse_mode = NULL, disable_web_page_preview = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL )
sendMessage( chat_id, text, parse_mode = NULL, disable_web_page_preview = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL )
chat_id |
Unique identifier for the target chat or username of the target channel. |
text |
Text of the message to be sent. |
parse_mode |
(Optional). Send 'Markdown' or 'HTML', if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. |
disable_web_page_preview |
(Optional). Disables link previews for links in this message. |
disable_notification |
(Optional). Sends the message silently. Users will receive a notification with no sound. |
reply_to_message_id |
(Optional). If the message is a reply, ID of the original message. |
reply_markup |
(Optional). A Reply Markup parameter object, it can be either: |
You can also use it's snake_case equivalent send_message
.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") bot$sendMessage( chat_id = chat_id, text = "foo *bold* _italic_", parse_mode = "Markdown" ) ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") bot$sendMessage( chat_id = chat_id, text = "foo *bold* _italic_", parse_mode = "Markdown" ) ## End(Not run)
Use this method to send photos.
sendPhoto( chat_id, photo, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, parse_mode = NULL )
sendPhoto( chat_id, photo, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, parse_mode = NULL )
chat_id |
Unique identifier for the target chat or username of the target channel. |
photo |
Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a local photo by passing a file path. |
caption |
(Optional). Photo caption (may also be used when re-sending photos by file_id), 0-1024 characters. |
disable_notification |
(Optional). Sends the message silently. Users will receive a notification with no sound. |
reply_to_message_id |
(Optional). If the message is a reply, ID of the original message. |
reply_markup |
(Optional). A Reply Markup parameter object, it can be either: |
parse_mode |
(Optional). Send 'Markdown' or 'HTML', if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. |
You can also use it's snake_case equivalent send_photo
.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") photo_url <- "https://telegram.org/img/t_logo.png" bot$sendPhoto( chat_id = chat_id, photo = photo_url, caption = "Telegram Logo" ) ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") photo_url <- "https://telegram.org/img/t_logo.png" bot$sendPhoto( chat_id = chat_id, photo = photo_url, caption = "Telegram Logo" ) ## End(Not run)
Use this method to send .webp
stickers.
sendSticker( chat_id, sticker, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL )
sendSticker( chat_id, sticker, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL )
chat_id |
Unique identifier for the target chat or username of the target channel. |
sticker |
Sticker to send. Pass a file_id as String to send a file that
exists on the Telegram servers (recommended), pass an HTTP URL as a
String for Telegram to get a |
disable_notification |
(Optional). Sends the message silently. Users will receive a notification with no sound. |
reply_to_message_id |
(Optional). If the message is a reply, ID of the original message. |
reply_markup |
(Optional). A Reply Markup parameter object, it can be either: |
You can also use it's snake_case equivalent send_sticker
.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") sticker_url <- "https://www.gstatic.com/webp/gallery/1.webp" bot$sendSticker( chat_id = chat_id, sticker = sticker_url ) ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") sticker_url <- "https://www.gstatic.com/webp/gallery/1.webp" bot$sendSticker( chat_id = chat_id, sticker = sticker_url ) ## End(Not run)
Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document).
sendVideo( chat_id, video, duration = NULL, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, width = NULL, height = NULL, parse_mode = NULL, supports_streaming = NULL )
sendVideo( chat_id, video, duration = NULL, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, width = NULL, height = NULL, parse_mode = NULL, supports_streaming = NULL )
chat_id |
Unique identifier for the target chat or username of the target channel. |
video |
Video file to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a local video file by passing a file path. |
duration |
(Optional). Duration of sent audio in seconds. |
caption |
(Optional). Video caption, 0-1024 characters. |
disable_notification |
(Optional). Sends the message silently. Users will receive a notification with no sound. |
reply_to_message_id |
(Optional). If the message is a reply, ID of the original message. |
reply_markup |
(Optional). A Reply Markup parameter object, it can be either: |
width |
(Optional). Video width. |
height |
(Optional). Video height. |
parse_mode |
(Optional). Send 'Markdown' or 'HTML', if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. |
supports_streaming |
(Optional). Pass |
You can also use it's snake_case equivalent send_video
.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") video_url <- "http://techslides.com/demos/sample-videos/small.mp4" bot$sendVideo( chat_id = chat_id, video = video_url ) ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") video_url <- "http://techslides.com/demos/sample-videos/small.mp4" bot$sendVideo( chat_id = chat_id, video = video_url ) ## End(Not run)
Use this method to send video messages.
sendVideoNote( chat_id, video_note, duration = NULL, length = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL )
sendVideoNote( chat_id, video_note, duration = NULL, length = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL )
chat_id |
Unique identifier for the target chat or username of the target channel. |
video_note |
Video note file to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video note from the Internet, or upload a local video note file by passing a file path. |
duration |
(Optional). Duration of sent audio in seconds. |
length |
(Optional). Video width and height. |
disable_notification |
(Optional). Sends the message silently. Users will receive a notification with no sound. |
reply_to_message_id |
(Optional). If the message is a reply, ID of the original message. |
reply_markup |
(Optional). A Reply Markup parameter object, it can be either: |
You can also use it's snake_case equivalent send_video_note
.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") video_note_url <- "http://techslides.com/demos/sample-videos/small.mp4" bot$sendVideoNote( chat_id = chat_id, video_note = video_note_url ) ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") video_note_url <- "http://techslides.com/demos/sample-videos/small.mp4" bot$sendVideoNote( chat_id = chat_id, video_note = video_note_url ) ## End(Not run)
Use this method to send audio files, if you want Telegram clients to display
the file as a playable voice message. For this to work, your audio must be
in an .ogg
file encoded with OPUS (other formats may be sent with
sendAudio
or sendDocument
).
sendVoice( chat_id, voice, duration = NULL, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, parse_mode = NULL )
sendVoice( chat_id, voice, duration = NULL, caption = NULL, disable_notification = FALSE, reply_to_message_id = NULL, reply_markup = NULL, parse_mode = NULL )
chat_id |
Unique identifier for the target chat or username of the target channel. |
voice |
Voice file to send. Pass a file_id as String to send a voice file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a voice file from the Internet, or upload a local voice file file by passing a file path. |
duration |
(Optional). Duration of sent audio in seconds. |
caption |
(Optional). Voice message caption, 0-1024 characters. |
disable_notification |
(Optional). Sends the message silently. Users will receive a notification with no sound. |
reply_to_message_id |
(Optional). If the message is a reply, ID of the original message. |
reply_markup |
(Optional). A Reply Markup parameter object, it can be either: |
parse_mode |
(Optional). Send 'Markdown' or 'HTML', if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. |
You can also use it's snake_case equivalent send_voice
.
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") ogg_url <- "https://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg" bot$sendVoice( chat_id = chat_id, voice = ogg_url ) ## End(Not run)
## Not run: bot <- Bot(token = bot_token("RTelegramBot")) chat_id <- user_id("Me") ogg_url <- "https://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg" bot$sendVoice( chat_id = chat_id, voice = ogg_url ) ## End(Not run)
Use this method to change your bot's auth token.
set_token(token)
set_token(token)
token |
The bot's token given by the BotFather. |
Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update.
setWebhook( url = NULL, certificate = NULL, max_connections = 40L, allowed_updates = NULL, ip_address = NULL, drop_pending_updates = FALSE, secret_token = NULL )
setWebhook( url = NULL, certificate = NULL, max_connections = 40L, allowed_updates = NULL, ip_address = NULL, drop_pending_updates = FALSE, secret_token = NULL )
url |
HTTPS url to send updates to. Use an empty string to remove webhook integration. |
certificate |
(Optional). Upload your public key certificate so that the root certificate in use can be checked. See Telegram's self-signed guide for details. |
max_connections |
(Optional). Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput. |
allowed_updates |
(Optional). String or vector of strings with the
types of updates you want your bot to receive. For example, specify
Please note that this parameter doesn't affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time. |
ip_address |
(Optional). The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS. |
drop_pending_updates |
(Optional). Pass True to drop all pending updates. |
secret_token |
(Optional). A secret token to be sent in a header
|
If you'd like to make sure that the webhook request comes from Telegram, we
recommend using a secret path in the URL, e.g.
https://www.example.com/<token>
.
You can also use it's snake_case equivalent set_webhook
.
Starts polling updates from Telegram. You can stop the polling either by
using the the interrupt R
command in the session menu or with the
stop_polling
method.
start_polling( timeout = 10L, clean = FALSE, allowed_updates = NULL, verbose = FALSE )
start_polling( timeout = 10L, clean = FALSE, allowed_updates = NULL, verbose = FALSE )
timeout |
(Optional). Passed to |
clean |
(Optional). Whether to clean any pending updates on Telegram
servers before actually starting to poll. Default is |
allowed_updates |
(Optional). Passed to |
verbose |
(Optional). If |
## Not run: # Start polling example start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } updater <- Updater("TOKEN") + CommandHandler("start", start) updater$start_polling(verbose = TRUE) ## End(Not run)
## Not run: # Start polling example start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } updater <- Updater("TOKEN") + CommandHandler("start", start) updater$start_polling(verbose = TRUE) ## End(Not run)
Starts the webhook for updates from Telegram. You can stop listening either by
using the RStudio's interrupt R
command in the session menu or with the
stop_server
method.
start_server(host = "127.0.0.1", port = 5001, clean = FALSE, blocking = TRUE)
start_server(host = "127.0.0.1", port = 5001, clean = FALSE, blocking = TRUE)
host |
a string that is a valid IPv4 or IPv6 address that is owned by this server, which the application will listen on. "0.0.0.0" represents all IPv4 addresses and "::/0" represents all IPv6 addresses. Default is "127.0.0.1". |
port |
a number or integer that indicates the server port that should be listened on. Note that on most Unix-like systems including Linux and Mac OS X, port numbers smaller than 1025 require root privileges. Default is 5001. |
clean |
(Optional). Whether to clean any pending updates on Telegram
servers before actually starting to poll. Default is |
blocking |
(Optional). Determines whether the method blocks whilst listening
for updates from Telegram.
Default is |
## Not run: # Start webhook example start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } webhook <- Webhook("https://example.com/webhook", "TOKEN") + CommandHandler("start", start) webhook$start_server() ## End(Not run)
## Not run: # Start webhook example start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } webhook <- Webhook("https://example.com/webhook", "TOKEN") + CommandHandler("start", start) webhook$start_server() ## End(Not run)
Stops the polling. Requires no parameters.
stop_polling()
stop_polling()
## Not run: # Example of a 'kill' command kill <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = "Bye!" ) # Clean 'kill' update bot$getUpdates(offset = update$update_id + 1) # Stop the updater polling updater$stop_polling() } updater <<- updater + CommandHandler("kill", kill) updater$start_polling(verbose = TRUE) # Send '/kill' to the bot ## End(Not run)
## Not run: # Example of a 'kill' command kill <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = "Bye!" ) # Clean 'kill' update bot$getUpdates(offset = update$update_id + 1) # Stop the updater polling updater$stop_polling() } updater <<- updater + CommandHandler("kill", kill) updater$start_polling(verbose = TRUE) # Send '/kill' to the bot ## End(Not run)
Stops listening on the webhook. Requires no parameters.
stop_server()
stop_server()
## Not run: # Example of a 'kill' command kill <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = "Bye!" ) # Stop the webhook webhook$stop_server() } webhook <- Webhook("https://example.com/webhook", "TOKEN") + CommandHandler("start", start) webhook$start_server() ## End(Not run)
## Not run: # Example of a 'kill' command kill <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = "Bye!" ) # Stop the webhook webhook$stop_server() } webhook <- Webhook("https://example.com/webhook", "TOKEN") + CommandHandler("start", start) webhook$start_server() ## End(Not run)
Base class for most telegram objects.
is.TelegramObject(x)
is.TelegramObject(x)
x |
Object to be tested. |
An R6Class
generator object.
clone()
The objects of this class are cloneable with this method.
TelegramObject$clone(deep = FALSE)
deep
Whether to make a deep clone.
This object represents an incoming Update.
Update(data) is.Update(x)
Update(data) is.Update(x)
data |
Data of the update. |
x |
Object to be tested. |
An R6Class
object.
from_chat_id
To get the id
from the update's
effective chat.
from_user_id
To get the id
from the update's
effective user.
effective_chat
To get the chat that this update was sent in, no matter what kind of update this is.
effective_user
To get the user that sent this update, no matter what kind of update this is.
effective_message
To get the message included in this update, no matter what kind of update this is.
This class, which employs the class Dispatcher
, provides a
front-end to class Bot
to the programmer, so you can focus on
coding the bot. Its purpose is to receive the updates from Telegram and to
deliver them to said dispatcher. The dispatcher supports
Handler
classes for different kinds of data: Updates from
Telegram, basic text commands and even arbitrary types. See
add
(+
) to learn more about building your
Updater
.
Updater( token = NULL, base_url = NULL, base_file_url = NULL, request_config = NULL, bot = NULL ) is.Updater(x)
Updater( token = NULL, base_url = NULL, base_file_url = NULL, request_config = NULL, bot = NULL ) is.Updater(x)
token |
(Optional). The bot's token given by the BotFather. |
base_url |
(Optional). Telegram Bot API service URL. |
base_file_url |
(Optional). Telegram Bot API file URL. |
request_config |
(Optional). Additional configuration settings
to be passed to the bot's POST requests. See the The |
bot |
(Optional). A pre-initialized |
x |
Object to be tested. |
An R6Class
object.
Note: You must supply either a bot
or a
token
argument.
start_polling
Starts polling updates from Telegram.
stop_polling
Stops the polling.
Bots: An introduction for developers and Telegram Bot API
## Not run: updater <- Updater(token = "TOKEN") # In case you want to set a proxy (see ?httr:use_proxy) updater <- Updater( token = "TOKEN", request_config = httr::use_proxy(...) ) # Add a handler start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } updater <- updater + CommandHandler("start", start) # Start polling updater$start_polling(verbose = TRUE) # Send '/start' to the bot ## End(Not run)
## Not run: updater <- Updater(token = "TOKEN") # In case you want to set a proxy (see ?httr:use_proxy) updater <- Updater( token = "TOKEN", request_config = httr::use_proxy(...) ) # Add a handler start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } updater <- updater + CommandHandler("start", start) # Start polling updater$start_polling(verbose = TRUE) # Send '/start' to the bot ## End(Not run)
Obtain Telegram user id from system variables (in .Renviron
) set
according to the naming convention R_TELEGRAM_USER_X
where X
is the user's name.
user_id(user_name)
user_id(user_name)
user_name |
The user's name. |
## Not run: # Open the `.Renviron` file file.edit(path.expand(file.path("~", ".Renviron"))) # Add the line (uncomment and replace <user-id> by your Telegram user ID): # R_TELEGRAM_USER_Me=<user-id> # Save and restart R user_id("Me") ## End(Not run)
## Not run: # Open the `.Renviron` file file.edit(path.expand(file.path("~", ".Renviron"))) # Add the line (uncomment and replace <user-id> by your Telegram user ID): # R_TELEGRAM_USER_Me=<user-id> # Save and restart R user_id("Me") ## End(Not run)
This class, which employs the class Dispatcher
, provides a
front-end to class Bot
to the programmer, so you can focus on
coding the bot. Its purpose is to receive updates via webhook from Telegram and
to deliver them to said dispatcher. The dispatcher supports
Handler
classes for different kinds of data: Updates from
Telegram, basic text commands and even arbitrary types. See
add
(+
) to learn more about building your Webhook
.
Webhook( webhook_url, token = NULL, base_url = NULL, base_file_url = NULL, request_config = NULL, certificate = NULL, max_connections = NULL, allowed_updates = NULL, ip_address = NULL, drop_pending_updates = FALSE, verbose = FALSE, bot = NULL ) is.Webhook(x)
Webhook( webhook_url, token = NULL, base_url = NULL, base_file_url = NULL, request_config = NULL, certificate = NULL, max_connections = NULL, allowed_updates = NULL, ip_address = NULL, drop_pending_updates = FALSE, verbose = FALSE, bot = NULL ) is.Webhook(x)
webhook_url |
Webhook HTTPS url to send updates to. The url is conventionally
suffixed with the Note: The url must be publicly accessible, since Telegram will need to make
HTTP For example, if you are deploying to Heroku, you can use the app's hostname,
such as |
token |
(Optional). The bot's token given by the BotFather. |
base_url |
(Optional). Telegram Bot API service URL. |
base_file_url |
(Optional). Telegram Bot API file URL. |
request_config |
(Optional). Additional configuration settings
to be passed to the bot's POST requests. See the The |
certificate |
(Optional). Upload your public key certificate so that the root certificate in use can be checked. See Telegram's self-signed guide for details. |
max_connections |
(Optional). Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput. |
allowed_updates |
(Optional). String or vector of strings with the
types of updates you want your bot to receive. For example, specify
Please note that this parameter doesn't affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time. |
ip_address |
(Optional). The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS. |
drop_pending_updates |
(Optional). Pass True to drop all pending updates. |
verbose |
(Optional). If |
bot |
(Optional). A pre-initialized |
x |
Object to be tested. |
An R6Class
object.
You must supply the webhook_url
and either a bot
or a token
argument.
The webhook_url
must be publicly accessible, since Telegram will
need to make HTTP POST
requests to the end-point for each update.
Security Note: Webhook
encapsulates generating a secret_token
which
is used to validate that the request comes from a webhook set by you.
start_server
Starts listening for updates from Telegram.
stop_server
Stops listening for updates.
running
Returns TRUE
when listening for updates.
Bots: An introduction for developers, Telegram Bot API and Marvin's Marvellous Guide to All Things Webhook
## Not run: webhook <- Webhook("https://example.com/webhook", "TOKEN") # In case you want to set a proxy webhook <- Webhook( webhook_url = "https://example.com/webhook", token = "TOKEN", request_config = httr::use_proxy(...), verbose = TRUE ) # Add a handler start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } webhook <- webhook + CommandHandler("start", start) # Start polling webhook$start_server() # Send '/start' to the bot ## End(Not run)
## Not run: webhook <- Webhook("https://example.com/webhook", "TOKEN") # In case you want to set a proxy webhook <- Webhook( webhook_url = "https://example.com/webhook", token = "TOKEN", request_config = httr::use_proxy(...), verbose = TRUE ) # Add a handler start <- function(bot, update) { bot$sendMessage( chat_id = update$message$chat_id, text = sprintf( "Hello %s!", update$message$from$first_name ) ) } webhook <- webhook + CommandHandler("start", start) # Start polling webhook$start_server() # Send '/start' to the bot ## End(Not run)