How to add a local push button to a Telegram bot

Adding a local push button to a Telegram bot

That example is meant to demonstrate a simple telegram Bot able to read in real time a local GPIO input and send a message into the opened chat. Two prerequisite have to be fulfilled:

Two classes are defined in the following:

  • BotButton for the input management
  • PushButtonBot that is the bot

BotButton

Constructor of BotButton has two parameter:

  • the input pin label
  • the bot object associated

in the pressed () method a message is sent over the chat

PushButtonBot

Is a simplified bot that just echoes back the message received

Example program

After the bot is instantiated and the usual message loop initialization has been completed, the associated push button object is created.

After the first message arrives to the bot, the global variable my_chat_id assume a valid value and is used (inside the BotButton instance) in case the local push button is pressed.

Of course multiple push buttons object can be instantiated in case multiple inputs are present.


#
# read from environment the Telegram Bot key
#
import os

try: 
    if len(os.environ['SSH_BOT_KEY']) == 0: 
        raise
except:
    print "Invalid or missing TG key."
    exit (255)

# helpers
import time
from pprint import pprint


# telepot
import telepot
from telepot.delegate import pave_event_space, per_chat_id, create_open
from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove, ForceReply


my_chat_id = -1

#
# Push Button
#
from gpio_classes import PushButton
from time import sleep
import datetime

class BotButton(PushButton):
    
    def __init__(self, name, bx):
        PushButton.__init__(self, name)
        self.bot = bx
        
    def pressed (self):
        global my_chat_id
        print ">>>> Button pressed"
        if my_chat_id >= 0:
            self.bot.sendMessage(my_chat_id,'BUTTON PRESSED at %s' % datetime.datetime.utcnow())
        else:
            print ("error: no chat open")
        
    def released (self):
        print ">>>> Button released"
        


#
# main Bot class
#
class PushButtonBot(telepot.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(PushButtonBot, self).__init__(*args, **kwargs)
        self._count = 0

    def on_chat_message(self, msg):
        global my_chat_id

        pprint (msg)
        my_chat_id = msg['chat']['id']
        command = msg['text']
        self._count += 1
        self.sender.sendMessage("count: %d chat id: %s command: %s" 
                                %
                                (self._count, my_chat_id, command))



#
# register the bot and start it
#

bot = telepot.DelegatorBot(os.environ['SSH_BOT_KEY'], [
    pave_event_space()(
        per_chat_id(), create_open, PushButtonBot, timeout=1000
    ),
])

bot.message_loop(run_forever=False, timeout=2)

print "Message loop started"


button = BotButton('PC17', bot)


while True:
    time.sleep(100000)

Andrea Montefusco
Currently employed as network architect, always Internet working man, real programmer in the past, Unix system engineer as needed, HAM Radio enthusiast (IW0HDV), aeromodeller since 1976.
http://www.montefusco.com - https://github.com/amontefusco -

The TanzoLab Project

Il TanzoLab è una iniziativa senza fini di lucro, nata da un'idea di Sergio Tanzilli socio fondatore di Acme Systems srl nel Novembre 2015, per trasferire ad appassionati di elettronica e informatica, professionisti e aziende nel settore, le conoscenze necessarie per poter creare prodotti embedded adatti per la produzione industriale.

Le attività del TanzoLab si svolgono ogni lunedi sera, salvo casi speciali, dalle ore 18:30 presso i locali della Acme Systems srl e consistono in:

  • Talk monotematici a cura di professionisti in vari settori tecnologici
  • Workshop pratici su elettronica embedded, produzione e informatica
  • Progettazione e realizzazione di nuovi prodotti embedded per l'IT

Le attività vengono coordinate tramite questo sito, in cui vengono pubblicati tutti i lavori svolti o in via di sviluppo, e tramite un gruppo Telegram con cui per interagire direttamente via chat con gli altri membri.