Simple Telegram bot for receiving information via MQTT

This bot was designed to view information on the mqtt server inside the local network. It can work on the same computer with the mqtt server (including Raspberry PI or similar) or separately. The task of remote control was not set, only the provision of access to data.





The MQTT protocol is designed specifically for use in various automation devices, it is very easy to organize telemetry and data collection on it. This protocol is supported by both smart home devices and many industrial controllers. There are also many projects on ESP8266, ESP32 or similar platforms.





Telemetry data from various sensors is published on the mqtt server - for example, this is a weather station and thermometers in greenhouses. To view them on a desktop, I used to make a widget, -, . , , . - ICQ , ICQRemote AutoIt Winamp . , - . . , -, .





, -. Python. Windows, - python-telegram-bot paho-mqtt .





ini . TELEGRAM , MQTT / mqtt , ( - , ). mqtt . . alldata, :





{
'greenhouse/1/temp': '24.76',
'greenhouse/1/upd': '22.04 18:20:30',
'greenhouse/2/temp': '22.95',
'greenhouse/3/temp': '28.91',
'air/outdoor/1/temp': '17.32',
'air/outdoor/1/upd': '22.04 18:21:25',
'air/outdoor/1/pressure': '739',
'air/outdoor/1/humidity': '58.3'
}
      
      



tree - . maketree.





def maketree(group, items, path):
    def sep(s):
        return s.split('/', 1)

    head = [i for i in items if len(sep(i)) == 2]
    tail = [i for i in items if len(sep(i)) == 1]
    if len(tail) == 1:
        return group, tail[0]
    gv = groupby(sorted(head), lambda i: sep(i)[0])
    return group, dict([(i, path) for i in tail] + [maketree(g, [sep(i)[1] for i in v], '') for g, v in gv])

      
      



:





{
    "air": {
        "outdoor": {
            "1": {
                "humidity": "58.3",
                "pressure": "739",
                "temp": "17.32",
                "upd": "22.04 18:21:25"
            }
        }
    },
    "greenhouse": {
        "1": {
            "temp": "24.76",
            "upd": "22.04 18:20:30"
        },
        "2": {
            "temp": "22.95"
        },
        "3": {
            "temp": "28.91"
        }
    }
}

      
      



. , 1 tree[greenhouse][1][temp]. , , . .





. - , Long Polling . python-telegram-bot 12.8, 13 - . pip3 install python-telegram-bot==12.8





: , . , get_keyb:





def get_keyb():
    return [[InlineKeyboardButton('', callback_data='1'),
            InlineKeyboardButton('', callback_data='2')]]
 
      
      



, :





keys = {'': '1', '': '2', '': '3'}
      
      



"" , "40"





Dialogue option

.





In principle, such a bot can be used to control something, for example, by publishing commands in the same mqtt topics - this is limited only by your imagination. But then you will need to add authorization and a contact list. Full bot code on GitHub








All Articles