Microcontroller

Telegram Controlled Led

We will be using an ESP32 running Micropython to talk to Telegram via its API and a bot.

Telegram is like SMS and email combined 

The ESP32 is a powerfull microcontroller with build in wifi

Setting up Telegram

First you’ll need to install Telegram https://telegram.org/

BotFather

Search for the user BotFather

Type /newbot and follow the prompts

Take note of the API token it gives you

Get User Id

Search for the user userinfobot and take note of your user id

ESP32 Setup

Add a file called config.json and save it to the device

{
    "wifi": {
        "ssid": ""
        "password": ""
    },
    "token": "",
    "recipient": ""
}

Add your wifi details, Telegram API token and id

Add a file called boot.py and save it to the device

# This file is executed on every boot (including wake-boot from deepsleep)
import esp
esp.osdebug(None)

import network
import json

with open("config.json", 'r') as f:
    config = json.load(f)
    
print(config)

sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
    print('connecting to network...')
    sta_if.active(True)
    sta_if.connect(config["wifi"]["ssid"], config["wifi"]["password"])
   
while not sta_if.isconnected():
    pass

print('network config:', sta_if.ifconfig())

Add a file called telegram.py and save it to the device

try:
    import urequests as requests #For MicroPython
except :
    import requests
import json

with open("config.json", 'r') as f:
    config = json.load(f)

offset = "0"
while True:
    #long poll for response
    querry = 'limit=1&offset={}&timeout=10'.format(offset)
    try:
        resp = requests.get(url='https://api.telegram.org/bot{}/{}?{}'.format(config["token"], "getUpdates", querry))
        json = resp.json()
        resp.close()
        if json.get("result"):
            #get latest message
            offset = json.get("result")[0].get("update_id") + 1
            text = json["result"][0]["message"]["text"]
            print(text)
            #echo message
            querry = 'chat_id={}&text={}'.format(config["recipient"], text)
            requests.get(url='https://api.telegram.org/bot{}/{}?{}'.format(config["token"], "sendMessage", querry))
    except Exception as e:
        print(e)
        resp.close() 

Now run it, and send a message to the bot you created, it should echo what ever you sent.

If you type /on it’ll turn the led on. /off will turn it off.

Code can be found here