I was working with Telegram bot provided by Telegram, to create a self-replying order bot. After achieving my ostensible goal, I contemplated using Telegram bot helper to send information to my Telegram channel. So, I wanted to obtain and send Telegram message when temperature cross threshold in every half-minute.
First of all, download the required applications:
For Telegram, click here.
For ubuntu, click here.
now you need to install ubuntu in your pc, or you may you cloud servers, here am installed ubuntu in my pc.So, now update libraries by entering below code:
Step 1: Update the packages on UbuntuExecute the command below so that the packages on Ubuntu are updated to the latest version. If you skip this step, you may encounter an error while installing the Boltiot package
sudo apt-get -y update
pip3 is a package manager for python3 used to install and manage packages and python libraries. It is system independent.
Install pip3 using the following command,
sudo apt install python3-pip
Step 3: Installing Bolt IoT library using pipNow we will install the boltiot python library on your Ubuntu server.
Type the below command in terminal to install boltiot python library.
sudo pip3 install boltiot
Now we are done with boltiot python library installation.
Step 4: Download Telegram on your mobile phoneSteps to sign up/sign in to Telegram
- Go to the Play Store or App Store on your phone and search for Telegram.
- Download and Install the latest version of Telegram app.
- Signup for a new account or sign in to Telegram by providing your mobile number.
- Telegram will call you OR send you a SMS to verify your mobile number.
- Get your account verified and approve any permissions if required.
- You will be logged in to Telegram and will be shown a screen similar to the one below:
Now create Telegram channel:
Steps to create a channel
- Go to the home screen of the Telegram app.
- Swipe from the left side to reveal the menu.
- Click on "New Channel."
It will ask you for a Name and Description for your channel. Give a suitable name and description
- In the next screen, set the channel as Public.
- On the same screen, it will ask you to enter a permanent link for your channel. You can use lowercase letters and numbers 0-9 to create the channel link.
Congratulations! You have created a new channel. You can also view this channel from your app home screen
Next we will need to create and add a Bot to the channel so that it can post alerts for us in this channel
What is a bot?Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands and requests.
We will be using Bots to send alerts on our channel.
Create a new botTelegram allows us to create a new bot with the help of a bot called as "BotFather." It is a single bot to create and manage other bots.
- On the home screen of the app, click on the search icon on the top right and type in "botfather".
The chat will have a few items already and will display you a list of commands to get started.
- Since we need to create a new Bot, go ahead and type in "/newbot" in the window.
- It will ask you to type in few more details like Bot name and Bot username.
- When your bot is created successfully, you will be shown a screen similar to the one below and will contain the Bot Token. This token is used to control your Bot as well as send messages on behalf of it. Please keep this token secure as it will allow anyone to access your Bot.
In the screenshot above, the Bot token is"878190697:AAEvdHM-f6k92hxNEFGtOQikcr1ZFrmhpyU"
Please save it as telegram_bot_id. The telegram_bot_id is saved as "bot" followed by the bot token. So, in this example, the telegram_bot_id will be
"bot878190697:AAEvdHM-f6k92hxNEFGtOQikcr1ZFrmhpyU"
- The telegram_bot_id will be used in the python code to send messages. The python code will be taught in the later lessons.
- Also, please be careful when saving the Bot ID. You may get confused between 0 and O, I and 1 etc. as they are similar looking.
- Congratulations, you have created a new Bot.
- From the App home screen, open the channel we have created earlier.
- In the screen, click on the channel name on the top to open the information for the Channel.
*Click on the Administrators button so that we can add the newly created bot to the channel.
*Search for the bot that we have created using the Bot's username. Once you have found the correct Bot click on it to add it to the channel.
*Please make sure you have clicked on the Administrators button in the previous step as this will allow our bot to post to the channel.
*You will be asked to confirm the rights for the bot. Press on the tick mark on the top right to continue adding the bot to the channel.
*Make sure that the bot has the rights to "Post Messages".
*You will now see the newly created Bot in the list of administrators for the channel.
*Now we will code for sending messages to the channel via the Bot.
Sending Telegram message when temperature crosses thresholdCircuit connections/hardware required- The Bolt WiFi module
- 3 female to male wires
- LM35 temperature sensor
Step 1: Hold the sensor in a manner such that you can read LM35 written on it.
Step 2: In this position, identify the pins of the sensor as VCC, Output and Gnd from your left to right.
In the above image, VCC is connected to the red wire, Output is connected to the orange wire and Gnd is connected to the brown wire.Step 3: Using male to female wire connect the 3 pins of the LM35 to the Bolt Wifi Module as follows:
- VCC pin of the LM35 connects to 5v of the Bolt Wifi module.
- Output pin of the LM35 connects to A0 (Analog input pin) of the Bolt Wifi module.
- Gnd pin of the LM35 connects to the Gnd.
The final circuit should look like the image below:
The code can be basically divided into three major parts. They are:
- Reading values from the Bolt device.
- Comparing the sensor value with the threshold.
- Sending a message via Telegram if the threshold has been breached.
The above steps are put in a while loop so that it reads the sensor value every 10 seconds and sends the alert if required.
We will be building the system functionally as:
- Reading the sensor value from the device.
- Sending a Telegram message.
- Checking if sensor value is valid and sending a message if it exceeds the threshold.
Telegram is a third-party messaging service which is similar to WhatsApp. It is free of cost and simple to use.
Telegram has a feature called as Bots which are just customized applications which you can build in order to send messages to a particular channel or group.
So, if we want to send a message to a channel, we will need to send a request to Telegram instructing the bot to send a message to a particular group.
Reading sensor values from the Bolt deviceWe will start by creating a new Python file to hold our configurations. Connect to your Ubuntu OS and type in the command `sudo mkdir temp_alert` in your shell to create a new folder for our project.
Then type `cd temp_alert` to move into that folder.
Create a config file to hold the configuration variables for Boltiot and Telegram. Type the command `sudo nano conf.py` to create a new file and edit it in the shell.
Paste the following lines of code into the conf file and press CTRL + X followed by ENTER key to save it.
"""Configurations for telegram_alert.py"""
bolt_api_key = "XXXX" # This is your Bolt Cloud API Key
device_id = "XXXX" # This is the device ID and will be similar to BOLTXXXX
telegram_chat_id = "@XXXX" # this is channel id of telegram paste after symbol@
telegram_bot_id = "botXXXX" # this is bot id of created telegram bot paste after bot
threshold = 250 # Threshold beyond which the alert should be sent
- bolt_api_key -> This is your API key for the Bolt Cloud. Visit this link to find your API key. Paste the API key inside the double inverted commas.
- device_id -> This is the ID of your Bolt device. It will be something like BOLT12345. Paste the device ID inside the double inverted commas.
- telegram_chat_id -> This is the channel ID which we have got when creating the channel on Telegram. It will be under the permanent link name of the channel. Paste the channel id after the @ symbol. Do not keep any spaces.
- telegram_bot_id -> This is the ID of the Telegram bot we have got when creating the Bot. It will be mentioned under the "BotFather" channel as token. Paste the token after the "bot" text. Do not keep any spaces.
- threshold -> This is the threshold beyond which the alert should be sent. Configure this value to receive alerts accordingly.
Add the configurations to your conf.py file and save it.
Now we will need to create a new python file using the command `sudo nano telegram_alert.py`.
Add the following code and save it using CTRL + X followed by ENTER key.
import requests # for making HTTP requestsimport json # library for handling JSON dataimport time # module for sleep operationfrom boltiot import Bolt # importing Bolt from boltiot moduleimport conf # config filemybolt = Bolt(conf.bolt_api_key, conf.device_id)def get_sensor_value_from_pin(pin): """Returns the sensor value. Returns -999 if request fails""" try: response = mybolt.analogRead(pin) data = json.loads(response) if data["success"] != 1: print("Request not successfull") print("This is the response->", data) return -999 sensor_value = int(data["value"]) return sensor_value except Exception as e: print("Something went wrong when returning the sensor value") print(e) return -999
Send message via TelegramWe will need to write a function to send a request to Telegram to send a message to the Telegram channel we have created earlier.
Add the function below inside the file "telegram_alert.py" and save it
def send_telegram_message(message): """Sends message via Telegram""" url = "https://api.telegram.org/" + conf.telegram_bot_id + "/sendMessage" data = { "chat_id": conf.telegram_chat_id, "text": message } try: response = requests.request( "POST", url, params=data ) print("This is the Telegram response") print(response.text) telegram_data = json.loads(response.text) return telegram_data["ok"] except Exception as e: print("An error occurred in sending the alert message via Telegram") print(e) return False
Open the telegram_alert.py file using the command `sudo nano telegram_alert.py`. Add the code below and save it.
In this code, we will be comparing the sensor value we have received against our set threshold value to check if the sensor value is a valid one or not and if an alert needs to be sent.
This can be broken down into the following steps -
- Get the sensor value from the Bolt device.
- Check if the sensor value is valid or not.
- Check if the sensor value exceeds the threshold and if a message needs to be sent.
- Wait for 10 seconds.
- Repeat from step 1.
while True: # Step 1 sensor_value = get_sensor_value_from_pin("A0") print("The current sensor value is:", sensor_value) # Step 2 if sensor_value == -999: print("Request was unsuccessfull. Skipping.") time.sleep(10) continue # Step 3 if sensor_value >= conf.threshold: print("Sensor value has exceeded threshold") message = "Alert! Sensor value has exceeded " + str(conf.threshold) + \ ". The current value is " + str(sensor_value) telegram_status = send_telegram_message(message) print("This is the Telegram status:", telegram_status) # Step 4 time.sleep(10)
NOTE - To exit from a While loop, press CTRL + C on your keyboard.
Note: The above "sensor_value" is the raw temperature reading, obtained from the LM35 sensor. In case you want to convert this value to the temperature in degree Celsius, use the formula
Temperature=(100*sensor_value)/1024
now finally we get alerts to telegram
Running the scriptBy entering the "sudo python3 telegram_alert.py"
I have provided complete code in the attachments.
Comments