Home

Awesome

This code implements a very simple non-blocking Telegram bot library for MicroPython based MCUs such as the ESP32 and similar microcontrollers.

Quick facts about how this can be useful and how it is implemented:

How to test it?

  1. Create your bot using the Telegram @BotFather.

  2. After obtaining your bot API key, edit the example.py file and put there your API key (also called token). Make sure to also put your WiFi credentials, as the microcontroller needs to connect to the Internet for this to work.

  3. Put the telegram.py file into the device flash memory with:

    mp cp telegram.py :

  4. Execute the example with:

    mp run example.y

  5. Talk to your bot. It will echo what you write to it.

  6. If your bot is inside a group, make sure to give it admin privileges, otherwise it will be unable to get messages.

How to use the API?

Run the bot in its own coroutine with:

bot = TelegramBot(Token,mycallback)
bot.connect_wifi(WifiNetwork, WifiPassword)
asyncio.create_task(bot.run())
loop = asyncio.get_event_loop()
loop.run_forever()

The callback looks like that:

def mycallback(bot,msg_type,chat_name,sender_name,chat_id,text,entry):
    print(msg_type,chat_name,sender_name,chat_id,text)
    bot.send(sender_id,"Ehi! "+text)

The arguments it receives are:

The only two methods you can call are:

  1. .send(), with the ID of the recipient and your text message. A third optional argument called glue can be True or False. By default it is False. When it is True, messages having the same target ID as the previous message are glued together, up to 2k of text, so we can avoid sending too many messages via the API.
  2. .stop() that will just terminate the task handling the bot. This should be called before discarding the TelegramBot object.