ProHoster > Blog > Administration > We write a telegram bot in the R language (part 1): Create a bot and send messages to telegram using it
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.
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.
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.
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"))).
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.
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.
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.
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.
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.
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:
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.
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.
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.