Writing a telegram bot in R (part 1): Creating a bot and sending messages through it to telegram

The audience of telegram is growing exponentially every day, thanks to the convenience of the messenger, the presence of channels, chats, and of course, the ability to create bots.

Bots can be used for various purposes, from automating communication with your clients to managing your own tasks.

Essentially, through a bot, you can perform any operations using telegram: send or request data, launch tasks on a server, collect information in a database, send emails, and so on.

I plan to write a series of articles about how to work with the telegram bot API, and create bots for your needs.

Writing a telegram bot in R (part 1): Creating a bot and sending messages through it to telegram

In this first article, we'll figure out how to create a telegram bot and send notifications through it in telegram.

As a result, we will have a bot that checks the status of the last execution of all tasks in the Windows task scheduler and sends you notifications if any have failed.

However, the goal of this series of articles is not to teach you how to write a bot for a specific, narrow task, but to familiarize you with the syntax of the telegram.botpackage, along with code examples that will help you write bots for your own needs.

Content

If you're interested in data analysis, you might find my telegram and youtube channels interesting. Most of their content is devoted to the R language.

  1. Creating a telegram bot
  2. Installing the package to work with the telegram bot in R
  3. Sending messages from R to Telegram
  4. Setting up a schedule for task checking
  5. Conclusion

Creating a telegram bot

To begin with, we need to create a bot. This is done using a special bot BotFather, go to this link and message the bot /start.

After which you will receive a message with a list of commands:

Message from BotFather

I can help you create and manage Telegram bots. If you're new to the Bot API, please see the manual (https://core.telegram.org/bots). You can control me by sending these commands: /newbot - create a new bot /mybots - edit your bots [beta] Edit Bots /setname - change a bot's name /setdescription - change bot description /setabouttext - change bot about info /setuserpic - change bot profile photo /setcommands - change the list of commands /deletebot - delete a bot Bot Settings /token - generate authorization token /revoke - revoke bot access token /setinline - toggle inline mode (https://core.telegram.org/bots/inline) /setinlinegeo - toggle inline location requests (https://core.telegram.org/bots/inline#location-based-results) /setinlinefeedback - change inline feedback (https://core.telegram.org/bots/inline#collecting-feedback) settings /setjoingroups - can your bot be added to groups? /setprivacy - toggle privacy mode (https://core.telegram.org/bots#privacy-mode) in groups Games /mygames - edit your games (https://core.telegram.org/bots/games) [beta] /newgame - create a new game (https://core.telegram.org/bots/games) /listgames - get a list of your games /editgame - edit a game /deletegame - delete an existing game

To create a new bot, send the command /newbot.

BotFather will ask you to enter the name and username of the bot.

BotFather, [25.07.20 09:39] Alright, a new bot. How are we going to call it? Please choose a name for your bot. Alexey Seleznev, [25.07.20 09:40] My Test Bot BotFather, [25.07.20 09:40] Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot. Alexey Seleznev, [25.07.20 09:40] @my_test_bot

You can enter any name, but the username must end with bot.

If you did everything correctly, you will receive the following message:

Done! Congratulations on your new bot. You will find it at t.me/my_test_bot. You can now add a description, about section, and profile picture for your bot; see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this. Use this token to access the HTTP API: 123456789:abcdefghijklmnopqrstuvwxyz For a description of the Bot API, see this page: https://core.telegram.org/bots/api

Next, you will need the API token you received; in my example, this is 123456789:abcdefghijklmnopqrstuvwxyz.

At this stage, the preparatory work for creating the bot is complete.

Installing the package to work with the telegram bot in R

I assume you already have the R language installed, and the RStudio development environment. If not, you can watch this video tutorial on how to install them.

To work with the Telegram Bot API, we will use the R package telegram.bot.

Packages in R are installed using the function install.packages(), so to install the necessary package, use the command install.packages("telegram.bot").

To learn more about installing various packages, you can refer to this video.

After installing the package, it needs to be loaded:

library(telegram.bot)

Sending messages from R to Telegram

Your created bot can be found on Telegram by the username you assigned during creation; in my case, it is @my_test_bot.

Send any message to the bot, for example, "Hello bot". At this point, we need this to get the ID of your chat with the bot.

Now we write the following code in R.

library(telegram.bot)

# create an instance of the bot
bot <- Bot(token = "123456789:abcdefghijklmnopqrstuvwxyz")

# Requesting information about the bot
print(bot$getMe())

# Getting updates from the bot, i.e., the list of messages sent to it
updates <- bot$getUpdates()

# Request the chat ID
# Note: Before requesting updates, you must send a message to the bot
chat_id <- updates[[1L]]$from_chat_id()

Initially, we create an instance of our bot using the function Bot(), passing the previously obtained token as an argument.

Storing the token in code is not considered best practice, so you can store it in an environment variable and read it from there. By default, the package telegram.bot supports environment variables with the following names: R_TELEGRAM_BOT_YOUR_BOT_NAME. Instead of YOUR_BOT_NAME replace it with the name you specified when creating it; in my case, the variable will be R_TELEGRAM_BOT_My Test Bot.

You can create an environment variable in several ways; I will tell you about the most universal and cross-platform method. Create a text file in your home directory (you can find out its location using the command path.expand("~")) with the name .Renviron. This can also be done using the command file.edit(path.expand(file.path("~", ".Renviron"))).

And add the following line to it.

R_TELEGRAM_BOT_YOUR_BOT_NAME=123456789:abcdefghijklmnopqrstuvwxyz

Next, you can use the token saved in the environment variable with the function bot_token(), that is, like this:

bot <- Bot(token = bot_token("My Test Bot"))

Element.getAnimations() getUpdates()allows us to get updates from the bot, i.e., the messages that were sent to it. The method from_chat_id(), allows us to get the chat ID from which the message was sent. This ID is necessary for sending messages from the bot.

In addition to the chat ID, the object obtained from the method getUpdates() also provides some other useful information. For example, information about the user who sent the message.

updates[[1L]]$message$from

$id
[1] 000000000

$is_bot
[1] FALSE

$first_name
[1] "Alexey"

$last_name
[1] "Seleznev"

$username
[1] "AlexeySeleznev"

$language_code
[1] "ru"

So, at this stage, we already have everything we need to send a message from the bot in Telegram. We will use the method sendMessage(), which must provide the chat identifier, the message text, and the message text formatting type. The formatting type can be Markdown or HTML and is set by an argument parse_mode.

# Отправка сообщения
bot$sendMessage(chat_id,
                text = "Привет, *жирный текст* _курсив_",
                parse_mode = "Markdown"
)

Basics of Markdown formatting:

  • Bold text is highlighted using the * sign:
    • example: *bold text*
    • result: bold text
  • Italic is defined using an underscore:
    • example: _italic_
    • result: italic
  • Monospace font, which is typically used for programming code, is defined using backticks — `:
    • example: `monospace font`
    • result: monospace font

Basics of HTML formatting:
In HTML, you wrap the part of the text that needs to be highlighted in tags, for example text.

  • — opening tag
  • — closing tag

HTML formatting tags

  • <b> — bold text
    • example: <b>bold text</b>
    • result bold text
  • — italic
    • example: italic
    • result: italic
  • — monospace font
    • example: monospace font
    • result: monospace font

In addition to text, you can send other content using special methods:

# Отправить изображение
bot$sendPhoto(chat_id,
  photo = "https://telegram.org/img/t_logo.png"
)

# Отправка голосового сообщения
bot$sendAudio(chat_id,
  audio = "http://www.largesound.com/ashborytour/sound/brobob.mp3"
)

# Отправить документ
bot$sendDocument(chat_id,
  document = "https://github.com/ebeneditos/telegram.bot/raw/gh-pages/docs/telegram.bot.pdf"
)

# Отправить стикер
bot$sendSticker(chat_id,
  sticker = "https://www.gstatic.com/webp/gallery/1.webp"
)

# Отправить видео
bot$sendVideo(chat_id,
  video = "http://techslides.com/demos/sample-videos/small.mp4"
)

# Отправить gif анимацию
bot$sendAnimation(chat_id,
  animation = "https://media.giphy.com/media/sIIhZliB2McAo/giphy.gif"
)

# Отправить локацию
bot$sendLocation(chat_id,
  latitude = 51.521727,
  longitude = -0.117255
)

# Имитация действия в чате
bot$sendChatAction(chat_id,
  action = "typing"
)

That is, for example, using the method sendPhoto() you can send a chart saved as an image that you created using the package ggplot2.

Checking the Windows task scheduler and sending notifications about tasks that were completed unexpectedly

To work with the Windows task scheduler, you need to install the package taskscheduleR, and for convenience in working with data, we will install the package dplyr.

# Установка пакетов
install.packages(c('taskscheduleR', 'dplyr'))
# Подключение пакетов
library(taskscheduleR)
library(dplyr)

Next, using the function taskscheduler_ls() we request information about tasks from our scheduler. Using the function filter() from the package dplyr we remove from the list of tasks those that were successfully completed and have a last result status of 0, as well as those that have never been run and have a status of 267011, disabled tasks, and tasks that are currently running.

# запрашиваем список задач
task <- task <- taskscheduler_ls() %>%
        filter(! `Last Result`  %in% c("0", "267011") & 
               `Scheduled Task State` == "Enabled" & 
               Status != "Running") %>%
        select(TaskName) %>%
        unique() %>%
        unlist() %>%
        paste0(., collapse = "n")

In the object task we now have a list of tasks that finished with errors, which we need to send to Telegram.

If we consider each command in more detail, then:

  • filter() — filters the list of tasks according to the conditions described above
  • select() — leaves only one field in the table with the task names
  • unique() — removes duplicate names
  • unlist() — converts the selected column of the table into a vector
  • paste0() — combines the task names into one string, and sets the line break as the separator, i.e. n.

All we have to do is send this result to Telegram.

bot$sendMessage(chat_id,
                text = task,
                parse_mode = "Markdown"
)

So, at the moment, the bot code looks like this:

Code for the task-checking bot

# Подключение пакета
library(telegram.bot)
library(taskscheduleR)
library(dplyr)

# инициализируем бота
bot <- Bot(token = "123456789:abcdefghijklmnopqrstuvwxyz")

# идентификатор чата
chat_id <- 123456789

# запрашиваем список задач
task <- taskscheduler_ls() %>%
        filter(! `Last Result`  %in% c("0", "267011")  &
               `Scheduled Task State` == "Enabled" & 
               Status != "Running") %>%
        select(TaskName) %>%
        unique() %>%
        unlist() %>%
        paste0(., collapse = "n")

# если есть проблемные задачи отправляем сообщение
if ( task != "" ) {

  bot$sendMessage(chat_id,
                  text = task,
                  parse_mode = "Markdown"
  )

}

When using the example above, substitute your bot's token and your chat ID into the code.

You can add task filtering conditions, for example, checking only those tasks that were created by you, excluding system tasks.

You can also move various settings to a separate configuration file, storing the chat ID and token there. You can read the config using a package such as configr.

Example ini config

[telegram_bot]
;settings for the Telegram bot and the chat where notifications will be sent
chat_id=12345678
bot_token=123456789:abcdefghijklmnopqrstuvwxyz"

Example of reading variables from the config in R

library(configr)

# reading the config
config <- read.config('C:/path_to_config/config.cfg', rcmd.parse = TRUE)

bot_token <- config$telegram_bot$bot_token
chat_id     <- config$telegram_bot$chat_id

Setting up the task-checking schedule

The process of scheduling script execution is described in the most detail in this article. Here, I will only outline the steps you need to take. If any of the steps are unclear, please refer to the linked article.

Let's assume we've saved our bot's code in a file check_bot.R. To schedule the regular execution of this file, follow these steps:

  1. Add the path to the folder where R is installed to the system PATH variable; in Windows, the path will look something like this: C:Program FilesRR-4.0.2bin.
  2. Create an executable bat file that contains only one line R CMD BATCH C:rscriptscheck_botcheck_bot.R. Replace C:rscriptscheck_botcheck_bot.R with the full path to your R file.
  3. Next, set up a schedule in the Windows Task Scheduler to run the script, for example, every half hour.

Conclusion

In this article, we covered how to create a bot and send various notifications through it on Telegram.

I described the task of monitoring the Windows Task Scheduler, but you can use the material in this article to send any notifications, from weather forecasts to stock quotes, as R allows you to connect to an enormous number of data sources.

In the next article, we will explore how to add commands and a keyboard to the bot, so that it can not only send notifications but also perform more complex actions.

Source: habr.com

Buy reliable website hosting with DDoS protection, VPS VDS servers 🔥 Buy reliable website hosting with DDoS protection, VPS VDS servers | ProHoster