Telegram Bot to monitor a Web page – Demo


A quick entry about creating a Telegram Bot using an R library. I tested that already some time ago, but I came up with a new use case yesterday, and I had a bit of time this morning, so…

We’ll use it to create a very simple monitor for our Webpage. This very Blog website was down a couple of days ago (and I wasn’t aware until I checked manually). Some issue with the database, I’m just happy there was a backup available. I’ll have to look further into it, thankfully this website has nothing critical about it.

 

Now every 10 minutes (for example) I can get messages from Telegram like so:

Edited: Important missing piece of information, sorry for that: I’m using Telegram and more precisely BotFather to help with the setting of the Bot on the messaging app side… Otherwise the following wouldn’t do much 🙂

The code

As is often the case, there is a library for this too. 🙂

library(telegram.bot)
library(httr)

my_token <- readLines("/mnt/R/.telegram_token.conf") # Never put sensitive data directly in the script
start <- function(bot, update) {
  bot$sendMessage(
    chat_id = update$message$chat$id,
    text = sprintf("Hello %s!", update$message$from$first_name)
  )
}
updater <- Updater(my_token) + CommandHandler("start", start)

# Initialize bot
bot <- Bot(token = my_token)

# Get bot info:
print(bot$getMe())
Sys.sleep(10) # Give time to send a message to the bot
# Get updates
updates <- bot$getUpdates()
# Retrieve your chat id
# Note: you should text the bot BEFORE calling `getUpdates`
chat_id <- updates[[1L]]$from_chat_id()


repeat {
 # Get updated check
 to_be_validated <- GET("https://www.kaizen-r.com/2021/02/before-ml/") 
 # Send message
 bot$sendMessage(chat_id,
                text = paste("https://www.kaizen-r.com/2021/02/before-ml/","\nResponse Code: ",to_be_validated$status_code)
 )
 Sys.sleep(600) # Wait for 10 minutes
}

And that’s it. Now every 10 minutes we’ll get a check for one of our web pages status. We can run the script in a container, and/or from a command line, using something like the following:

$ Rscript monitor_kaizen.R &

That way one can have it run in an infinite loop (unless purposefully stopped).

Why do it

Well this is just another way (not at all the best) to do some web monitoring. We could parse the response further (beyond this demo, but quite relevant for a valid check, as a 200 Response Code is quite insufficient)

References

As usual, my own code in my GitHub Repository.

Also VERY important: https://github.com/ebeneditos/telegram.bot, I would have had a much harder time without that package.