Learn R Programming

⚠️There's a newer version (3.0.0) of this package.Take me there.

telegram.bot

Develop a Telegram Bot with R

This package provides a pure R interface for the Telegram Bot 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.

Installation

You can install telegram.bot from CRAN:

install.packages("telegram.bot")

Or the development version from GitHub:

# install.packages("devtools")
devtools::install_github("ebeneditos/telegram.bot")

Usage

You can quickly build a chatbot with a few lines:

library(telegram.bot)

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() # Send '/start' to the bot

If you don't have a TOKEN, you can follow the steps explained below to generate one.

Telegram API Methods

One of the core instances from the package is Bot, which represents a Telegram Bot. You can find a full list of the Telegram API methods implemented in its documentation (?Bot), but here there are some examples:

# Initialize bot
bot <- Bot(token = "TOKEN")
chat_id <- "CHAT_ID" # you can retrieve it from bot$getUpdates() after sending a message to the bot

# Get bot info
print(bot$getMe())

# Get updates
updates <- bot$getUpdates()

# Send message
bot$sendMessage(chat_id = chat_id,
                text = "foo *bold* _italic_",
                parse_mode = "Markdown")

# Send photo
bot$sendPhoto(chat_id = chat_id,
               photo = "https://telegram.org/img/t_logo.png")

# Send audio
bot$sendAudio(chat_id = chat_id,
              audio = "http://www.largesound.com/ashborytour/sound/brobob.mp3")

# Send document
bot$sendDocument(chat_id = chat_id,
                 document = "https://github.com/ebeneditos/telegram.bot/raw/gh-pages/docs/telegram.bot.pdf")

# Send sticker
bot$sendSticker(chat_id = chat_id,
                sticker = "https://www.gstatic.com/webp/gallery/1.webp")

# Send video
bot$sendVideo(chat_id = chat_id,
              video = "http://techslides.com/demos/sample-videos/small.mp4")

# Send gif
bot$sendAnimation(chat_id = chat_id,
                  animation = "https://media.giphy.com/media/sIIhZliB2McAo/giphy.gif")

# Send location
bot$sendLocation(chat_id = chat_id,
                 latitude = 51.521727,
                 longitude = -0.117255)

# Send chat action
bot$sendChatAction(chat_id = chat_id,
                   action = "typing")

# Get user profile photos
photos <- bot$getUserProfilePhotos(user_id = chat_id)

# Download user profile photo
file_id <- photos$photos[[1L]][[1L]]$file_id
bot$getFile(file_id, destfile = "photo.jpg")

Note that you can also send local files by passing their path instead of an URL. Additionaly, all methods accept their equivalent snake_case syntax (e.g. bot$get_me() is equivalent to bot$getMe()).

Generating an Access Token

To make it work, you'll need an access TOKEN (it should look something like 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11). If you don't have it, you have to talk to @BotFather and follow a few simple steps (described here).

Recommendation: Following Hadley's API guidelines it's unsafe to type the TOKEN just in the R script. It's better to use enviroment variables set in .Renviron file.

So let's say you have named your bot RTelegramBot; you can open the .Renviron file with the R command:

file.edit(path.expand(file.path("~", ".Renviron")))

And put the following line with your TOKEN in your .Renviron:

R_TELEGRAM_BOT_RTelegramBot=TOKEN

If you follow the suggested R_TELEGRAM_BOT_ prefix convention you'll be able to use the bot_token function (otherwise you'll have to get these variable from Sys.getenv). Finally, restart R and you can then create the Updater object as:

updater <- Updater(token = bot_token("RTelegramBot"))

Getting Started

To get you started with telegram.bot, we recommend to take a look at its Wiki:

You can also check these other resources:

If you have any other doubt about the package, you can post a question on Stack Overflow under the r-telegram-bot tag or directly e-mail the package's maintainer.

Contributing

The package is in a starting phase, so contributions of all sizes are very welcome. Please:

Attribution

This package is inspired by Python's library python-telegram-bot, specially by its submodule telegram.ext.

Copy Link

Version

Install

install.packages('telegram.bot')

Monthly Downloads

404

Version

2.2.0

License

GPL-3

Issues

Pull Requests

Stars

Forks

Maintainer

Ernest Benedito

Last Published

December 1st, 2018

Functions in telegram.bot (2.2.0)

BaseFilter

The base of all filters
CallbackQueryHandler

Handling callback queries
ForceReply

Display a reply
CommandHandler

Handling commands
MessageHandler

Handling messages
bot_token

Get a token from environment
forwardMessage

Forward messages of any kind
leaveChat

Leave a chat
check_update

Check an update
from_chat_id

Get an update's chat ID
handle_update

Handle an update
MessageFilters

Filter message updates
set_token

Change your bot's auth token
start_polling

Start polling
ReplyKeyboardMarkup

Create a keyboard markup
Dispatcher

The dispatcher of all updates
ErrorHandler

Handling errors
ReplyKeyboardRemove

Remove a keyboard
Bot

Creating a Bot
Handler

The base of all handlers
Update

Represent an update
deleteWebhook

Remove webhook integration
Updater

Building a Telegram Bot
+.TelegramObject

Constructing an Updater
add_error_handler

Add an error handler
TelegramObject

The base of telegram.bot objects
answerCallbackQuery

Send answers to callback queries
InlineKeyboardButton

Create an inline keyboard button
answerInlineQuery

Send answers to an inline query
getMe

Check your bot's information
getUpdates

Receive incoming updates
editMessageReplyMarkup

Edit a reply markup
InlineKeyboardMarkup

Create an inline keyboard markup
sendLocation

Send point on the map
InlineQueryResult

The base of inline query results
KeyboardButton

Create a keyboard button
clean_updates

Clean any pending updates
add_handler

Add a handler
deleteMessage

Delete a message
effective_user

Get the effective user
sendMessage

Send text messages
stop_polling

Stop polling
from_user_id

Get an update's user ID
telegram.bot

Develop a Telegram Bot with R
filtersLogic

Combining filters
sendAnimation

Send animation files
getFile

Prepare a file for downloading
sendAudio

Send audio files
sendPhoto

Send image files
sendSticker

Send a sticker
sendChatAction

Send a chat action
sendDocument

Send general files
sendVoice

Send voice files
effective_chat

Get the effective chat
setWebhook

Set a webhook
effective_message

Get the effective message
getUserProfilePhotos

Get a user's profile photos
getWebhookInfo

Get current webhook status
sendVideo

Send a video
sendVideoNote

Send video messages
user_id

Get a user from environment