Code explanation - Part 2

Send message via Telegram

Previously we have learnt how to get the sensor value from the Bolt device. In this part, we will write the code to send a Telegram message.

We 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.

Remember that this not the final code. It is only a part of the final program.

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 URL")
        print(url)
        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

In the above code, we have created a function to send a message via Telegram. The function `send_telegram_message()` takes one parameter i.e. the message to send.

In the first line, we are building the URL so that Telegram knows which bot it has to send the message to. The telegram_bot_id is required for this purpose.

The data variable is a dictionary which holds the chat ID(Channel ID) so that the Bot knows which channel it has to post the message to. It also contains the text message to be sent as a message.

In the next step, we need to make a HTTP request to the Telegram servers using the URL we have built earlier. The request is a "POST" request which contains all the relevant data like URL and the data to be contained in the request.

Next, we are just printing the response from the request as text form. We also need to convert the text data to a JSON data so that we can find the status of the request to Telegram.

The line `telegram_data = json.loads(response.text)` converts the text response to a JSON object and stores it in telegram_data.

The status of the request is stored in the "ok" field of the telegram_data variable and we are returning it. The "ok" field will always contain a boolean value i.e. True/False and is True if the message has been sent.

The function is encased in a try-except block so that any errors are caught and it returns a False if any error is present in the try block.

To reiterate, the function takes a message parameter to be sent and returns a True/False status depending on the status of the request to Telegram.

Now, we will simply need to call this function inside the block where we will detect that the sensor value has exceeded the threshold.

Head over to the next lesson to actually send messages when the temperature exceeds the threshold.


Complete and Continue