Table of Contents
Motivation
In my project Mailbox IoT ESP 32 Project I needed a Telegram bot to relay the messages.
So here is a short tutorial
Create TG bot
- Open Telegram
- Search for @botfather
- Start chat
- Send /newbot
- Pick a name
- Pick a username (must be unique)
- Receive credentials
Chat with your bot
Now you can search for your bot’s name and send a message
Python test Program
Telegram has a nice python package which you can pip install
pip install python-telegram-bot --upgrade
import telegram
bot = telegram.Bot(token='<your_token>')
if __name__ == '__main__':
print(bot.get_me())
bot.send_message(chat_id="<your_chat_id>", text="Post ist da")
This program is just to used to test the connectivity of your bot.
Because we don’t have access to the telegram package inside the ESP / MicroPython environment we use urequests.
urequests
The telegram package isn’t available on the ESP32 / microPython, so we send our requests with the microPython port of the requests package called urequests.
Sending messages
import urequests
requests.get("https://api.telegram.org/bot<your_token>/sendMessage?text=hallo&chat_id=<your_chat_id>")
Lets clean up the code a bit:
try:
import urequests as requests
except ModuleNotFoundError:
import requests
TOKEN = "<your_token"
URL = f"https://api.telegram.org/bot{TOKEN}/"
CHAT_ID = "<your_chat_id"
def send_message(text, chat_id):
url = f"{URL}sendMessage?text={text}&chat_id={chat_id}"
response = requests.get(url)
content = response.text
return content
if __name__ == '__main__':
print(send_message("Your parcel arrived", CHAT_ID))