Markdown source

#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:

* <a HREF=""></a>
* <a HREF="">telepot library</a>
* the module as described in @article='debounce_pushbutton'

Two classes are defined in the following:

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

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 

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.

<pre class="prettyprint">

# read from environment the Telegram Bot key
import os

	if len(os.environ['SSH_BOT_KEY']) == 0: 
	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) = bx
	def pressed (self):
		global my_chat_id
		print ">>>> Button pressed"
		if my_chat_id >= 0:,'BUTTON PRESSED at %s' % datetime.datetime.utcnow())
			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'], [
        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:


Le attività del TanzoLab si svolgono ogni mercoledi 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.