Push live system stats to the cloud
Les Pounder shows us how to create a Telegram bot that will show updates from a Raspberry Pi server and broadcast them to the world. “In this tutorial we shall build a Telegram Bot, code that reacts to commands issued by the user from inside Telegram”.
Telegram is an encrypted, private messaging service with an open API that is really easy to use. In this tutorial we shall build a Telegram Bot, code that reacts to commands issued by the user from inside Telegram. Our bot will give us the latest CPU temperature, CPU usage and current available RAM for a Raspberry Pi.
SOFTWARE SETUP
Before any code can be written, we first need to sign up for a Telegram account. There are many clients for Windows, Linux and mobile devices. For this tutorial it would be prudent to install the desktop client, but if you are completing the tutorial on a Pi, you can use the web version. With the account created and Telegram installed we can now start to create a bot that will react to messages. To do this we need to use The BotFather, an automated script that handles the creation and maintenance of Telegram bots. Open a browser to https://Telegram.me/botfather and then tell The BotFather that we wish to create a new bot. /newbot
Follow the automated instructions and after a short while your new bot will be created. The BotFather will provide a URL to start our bot, and an API key. Copy the API key somewhere safe – we’ll need this later. Click the link to start a conversation with your new bot. You’ll see a start button at the bottom of the screen – click this to start the bot. That is all that we need to do in Telegram for now, but we will come back to it later.
On our Raspberry Pi we now need to install the Python library for this tutorial. Open a terminal and type
$ sudo pip3 install pyTelegramBotAPI
Close the terminal when complete.
CODING THE PROJECT
Open your preferred Python editor (IDLE, Thonny, Mu or similar) and create a new file. Save the file as TelegramBot. py and remember to save often.
We start the code for this project by first importing libraries that will provide the functionality in our
application. The first is the ‘telegram’ library for Python, then we import ‘time’ to control the pace of the code. Finally we import a library to enable Python to investigate system resources. import telebot import time import psutil
The next step is to create an object that will provide a link for our code to the Telegram bot. This is handled via the API key, unique to our bot. The object tb creates the link.
tb = telebot.TeleBot(“Your API KEY HERE”)
With a connection to Telegram created, we now create a handler that will react to a specific message from the user. The message is /stats and in order for it to be identified by the code we need to create a
test. The test is in a function that will check the contents of the message ( msg.text ) to ensure that it is not blank, and that it contains the /stats command.
@tb.message_ handler(func=lambda msg: msg. text is not None and ‘/stats’ in msg.text)
Next is the creation of a function, send_welcome , that will trigger the start of a flurry of activity. First a variable temperature is created and in there we store the output of the command to read all of the sensors on the Pi. But the output from this command is quite densely packed, so on the next line we update the contents of the variable so that it targets only the CPU temperature sensor. For the final step we convert the returned variable into a list, so that the contents can be easily selected. def send_welcome(message):
temperature = psutil. sensors_temperatures()
temperature = (temperature[‘cpu-thermal’][0])
temperature = list(temperature)
As well as showing the CPU temp, we also want to show the CPU usage as a percentage, and the amount of free RAM available. It’s just one line of code to get the CPU usage and store it in a variable called cpu . But for the memory we first need to save all of the memory information to a variable called memory and then extract the current available memory, which is stored in a list with an index of 1. This makes it the second item in the list. Then we use some maths to convert bytes to megabytes and the round() command to produce an easily readable value.
cpu = psutil.cpu_ percent(interval=1)
memory = psutil.virtual_ memory() memory = memory[1] memory = round(memory / 1024 / 1024)
Still inside the function, the next three lines handle replying to the user with the details of the server. First will be the CPU temperature. Using the tb.reply_to function we reply to the original message via a string. The string contains a sentence that will tell the user what the data is, and inserted into that sentence is the contents of the list temperature that we created earlier. But we only need a specific piece of information which is stored in index 1 of the list – this is the CPU temperature in Celsius. At the end of the sentence we add the letter ‘C’ to identify that we are using the Celsius temperature scale.
tb.reply_to(message, ‘CPU Temperature is ‘+str(temperature[1])+’C’)
The next two lines provide the data for the CPU usage and the amount of free memory. They work in a simpler manner to the temperature line.
tb.reply_to(message, ‘CPU Usage is ‘+str(cpu)+’%’)
tb.reply_to(message, ‘Free RAM is ‘+str(memory)+’MB’)
This is the end of the function and we now move on to the final section of code, which is a loop to continually check Telegram for updates ( polling ) and to handle any error messages and the user exiting the code. Using exception handling we first try polling Telegram, but if the user requests to exit, an exception is raised and the code will end. Another exception is when an error is raised; this typically happens after an hour of use. If so, the code will pause for 15 seconds before the loop repeats. while True: try:
tb.polling() except KeyboardInterrupt: print(“EXIT”) break except Exception:
time.sleep(15)
The code is now complete and is ready to run. Start the code and then go to the Telegram application and send the / stats message to your bot. This will trigger the bot code to run and give us live stats from our Pi. It’s as easy as that!