We write a telegram bot in the R language (part 1): Create a bot and send messages to telegram using it

The telegram audience is growing exponentially every day, this is facilitated by the convenience of the messenger, the availability of channels, chats, and of course the ability to create bots.

Bots can be used for a wide variety of purposes, from automating communication with your customers to managing your own tasks.

In fact, through the bot, you can use telegram to perform any operation: send or request data, run tasks on the server, collect information in a database, send emails, and so on.

I plan to write a series of articles on how to work with R in R. telegram bot API, and write bots for your needs.

We write a telegram bot in the R language (part 1): Create a bot and send messages to telegram using it

In this first article, we will figure out how to create a telegram bot and send notifications to telegram using it.

As a result, we will have a bot that will check the status of the last execution of all tasks in the Windows Task Scheduler, and send you notifications if any fail.

But the purpose of this series of articles is not to teach you how to write a bot for a specific, narrow task, but to introduce you to the syntax of the package in general. telegram.bot, and code examples with which you can write bots to solve your own problems.

Content

If you are interested in data analysis, you might be interested in my telegram ΠΈ youtube channels. Most of the content of which is devoted to the R language.

  1. Creation of a telegram bot
  2. Installing a package for working with a telegram bot on R
  3. Sending messages from R to Telegram
  4. Configuring the task scan launch schedule
  5. Conclusion

Creation of a telegram bot

First, we need to create a bot. This is done using a special bot Bot Father, go to link and write to the bot /start.

Then 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 login 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 an arbitrary name, and the login 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 received API token, in my example it is 123456789:abcdefghijklmnopqrstuvwxyz.

At this step, the preparatory work for creating the bot is completed.

Installing a package for working with a telegram bot on R

I'm assuming you already have the R language installed and the RStudio development environment. If this is not the case, then you can look at this video tutorial on how to install them.

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

Installing packages in R is done by the function install.packages(), so to install the package we need, use the command install.packages("telegram.bot").

For more information about installing various packages, see this video.

After installing the package, you need to connect it:

library(telegram.bot)

Sending messages from R to Telegram

The bot you created can be found in Telegram using the login specified during creation, in my case it is @my_test_bot.

Send any message to the bot, such as "Hi bot". At the moment, we need this in order to get the id of your chat with the bot.

Now in R we write the following code.

library(telegram.bot)

# создаём экзСмпляр Π±ΠΎΡ‚Π°
bot <- Bot(token = "123456789:abcdefghijklmnopqrstuvwxyz")

# Π—Π°ΠΏΡ€Π°ΡˆΠΈΠ²Π°Π΅ΠΌ ΠΈΠ½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΡŽ ΠΎ Π±ΠΎΡ‚Π΅
print(bot$getMe())

# ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ обновлСния Π±ΠΎΡ‚Π°, Ρ‚.Π΅. список ΠΎΡ‚ΠΏΡ€Π°Π²Π»Π΅Π½Π½Ρ‹Ρ… Π΅ΠΌΡƒ сообщСний
updates <- bot$getUpdates()

# Π—Π°ΠΏΡ€Π°ΡˆΠΈΠ²Π°Π΅ΠΌ ΠΈΠ΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€ Ρ‡Π°Ρ‚Π°
# ΠŸΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΠ΅: ΠΏΠ΅Ρ€Π΅Π΄ запросом ΠΎΠ±Π½ΠΎΠ²Π»Π΅Π½ΠΈΠΉ Π²Ρ‹ Π΄ΠΎΠ»ΠΆΠ½Ρ‹ ΠΎΡ‚ΠΏΡ€Π°Π²ΠΈΡ‚ΡŒ Π±ΠΎΡ‚Ρƒ сообщСниС
chat_id <- updates[[1L]]$from_chat_id()

Initially, we create an instance of our bot with the function Bot(), as an argument, you must pass the previously received token to it.

Storing the token in code is considered bad practice, so you can store it in an environment variable and read it from it. By default in the package telegram.bot implemented support for environment variables of the following name: R_TELEGRAM_BOT_ИМЯ_Π’ΠΠ¨Π•Π“Πž_Π‘ΠžΠ’Π. Instead ИМЯ_Π’ΠΠ¨Π•Π“Πž_Π‘ΠžΠ’Π substitute the name that you set when creating, in my case it will be a variable R_TELEGRAM_BOT_My Test Bot.

You can create an environment variable in several ways, I will talk about the most universal and cross-platform. Create in your home directory (you can find it with the command path.expand("~")) text file with the name .Renviron. You can also do this with the command file.edit(path.expand(file.path("~", ".Renviron"))).

And add the following line to it.

R_TELEGRAM_BOT_ИМЯ_Π’ΠΠ¨Π•Π“Πž_Π‘ΠžΠ’Π=123456789:abcdefghijklmnopqrstuvwxyz

You can then use the token stored in the environment variable with the function bot_token(), i.e. like this:

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

Method getUpdates()allows us to get bot updates, i.e. messages sent to him. Method from_chat_id(), allows you to get the ID of the chat from which the message was sent. We need this identifier to send messages from the bot.

In addition to the chat id from the object received by the method getUpdates() you get some other useful information as well. 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 that is needed to send a message from the bot to telegram. Let's use the method sendMessage(), to which you need to pass the chat ID, message text, and markup type of the message text. The markup type can be Markdown or HTML and is set by the argument parse_mode.

# ΠžΡ‚ΠΏΡ€Π°Π²ΠΊΠ° сообщСния
bot$sendMessage(chat_id,
                text = "ΠŸΡ€ΠΈΠ²Π΅Ρ‚, *ΠΆΠΈΡ€Π½Ρ‹ΠΉ тСкст* _курсив_",
                parse_mode = "Markdown"
)

Markdown Formatting Basics:

  • Bold font is marked with *:
    • example: *ΠΆΠΈΡ€Π½Ρ‹ΠΉ ΡˆΡ€ΠΈΡ‚Ρ„*
    • result: bold script
  • Italics are given by underscores:
    • example: _курсив_
    • result: italics
  • The fixed-space font, which is usually used to highlight program code, is specified using apostrophes - `:
    • example: `monospace font`
    • result: ΠΌΠΎΠ½ΠΎΡˆΠΈΡ€ΠΈΠ½Π½Ρ‹ΠΉ ΡˆΡ€ΠΈΡ„Ρ‚

HTML markup formatting basics:
In HTML, you wrap the part of the text you want to highlight in tags, example <Ρ‚Π΅Π³>тСкст</Ρ‚Π΅Π³>.

  • <tag> β€” opening tag
  • - closing tag

HTML markup tags

  • <b> - bold font
    • example: <b>ΠΆΠΈΡ€Π½Ρ‹ΠΉ ΡˆΡ€ΠΈΡ„Ρ‚</b>
    • result bold font
  • <i> - italics
    • example: <i>курсив</i>
    • result: italics
  • β€” ΠΌΠΎΠ½ΠΎΡˆΠΈΡ€ΠΈΠ½Π½Ρ‹ΠΉ ΡˆΡ€ΠΈΡ„Ρ‚
    • example: ΠΌΠΎΠ½ΠΎΡˆΠΈΡ€ΠΈΠ½Π½Ρ‹ΠΉ ΡˆΡ€ΠΈΡ„Ρ‚
    • result: ΠΌΠΎΠ½ΠΎΡˆΠΈΡ€ΠΈΠ½Π½Ρ‹ΠΉ ΡˆΡ€ΠΈΡ„Ρ‚

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"
)

Those. for example using the method sendPhoto() you can send a plot saved as an image that you built with the package ggplot2.

Checking the Windows Task Scheduler and sending notification of tasks that have crashed

To work with the Windows Task Scheduler, you need to install the package taskscheduleR, and for the convenience of working with data, 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 package dplyr we remove from the list of tasks those that were successfully completed and have a last result status of 0, and those that have never been run yet 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 facility task we now have a list of tasks whose work ended with an error, we need to send this list 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 with the name of the tasks in the table
  • unique() - removes duplicate names
  • unlist() - translates the selected table column into a vector
  • paste0() - connects the names of tasks into one line, and puts a newline character as a separator, i.e. n.

All that remains for us is to send this result to telegram.

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

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

Bot code that checks the task

# ΠŸΠΎΠ΄ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠ΅ ΠΏΠ°ΠΊΠ΅Ρ‚Π°
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 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 ones.

You can also put various settings in a separate configuration file, and store the chat id and token in it. You can read the config, for example, using the package configr.

Example ini config

[telegram_bot]
;настройки Ρ‚Π΅Π»Π΅Π³Ρ€Π°ΠΌ Π±ΠΎΡ‚Π° ΠΈ Ρ‡Π°Ρ‚Π°, Π² ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Π±ΡƒΠ΄ΡƒΡ‚ ΠΏΡ€ΠΈΡ…ΠΎΠ΄ΠΈΡ‚ΡŒ увСдомлСния
chat_id=12345678
bot_token=123456789:abcdefghijklmnopqrstuvwxyz"

Example of reading variables from config in R

library(configr)

# Ρ‡Ρ‚Π΅Π½ΠΈΠ΅ ΠΊΠΎΠ½Ρ„ΠΈΠ½Π°
config <- read.config('C:/ΠΏΡƒΡ‚ΡŒ_ΠΊ_ΠΊΠΎΠ½Ρ„ΠΈΠ³Ρƒ/config.cfg', rcmd.parse = TRUE)

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

Setting up a task scan launch schedule

The process of configuring scheduled script launch is described in more detail in this article. Here I will only describe the steps that must be followed for this. If any of the steps is not clear to you, then refer to the article to which I provided a link.

Let's say we save our bot code to a file check_bot.R. To schedule this file to run regularly, follow these steps:

  1. Write the path to the folder in which R is installed in the Path system variable, on Windows the path will be something like this: C:Program FilesRR-4.0.2bin.
  2. Create an executable bat file with only one line R CMD BATCH C:rscriptscheck_botcheck_bot.R. Replace C:rscriptscheck_botcheck_bot.R to the full path to your R file.
  3. Next, use the Windows Task Scheduler to set a startup schedule, for example, every half hour.

Conclusion

In this article, we figured out how to create a bot and use it to send various notifications to telegram.

I described the task of monitoring the Windows Task Scheduler, but you can use the material in this article to send any notification, from the weather forecast to stock quotes on the stock exchange, because. R allows you to connect to a huge number of data sources.

In the next article, we will figure out 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

Add a comment