I'm new to python and raspberry, I would like to make a smart doorbell controlled by a bot on telegram. The doorbell in question has a pir sensor that sends a video over telegram every time its triggered. I would like to have the messages I send to the bot read through the speakers. But I have a problem with the while true loop of the sensor and the handle (msg) function of telepot, I need to take the chat_id variable out of the handle function to use it in the other functions but I can't. I am attaching the complete code:
import telepot
from picamera import PiCamera
import RPi.GPIO as GPIO
import time
from time import sleep
import datetime
from telepot.loop import MessageLoop
from subprocess import call
import sys
import random
import pyttsx3
# setup sensori
PIR = 4
camera = PiCamera()
camera.resolution = (680, 480)
camera.framerate = 25
camera.rotation = 180
# setup pin
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR, GPIO.IN)
# variabili movimento
motion = 0
motionNew = 0
# telegram bot
def handle(msg):
global telegramText
global chat_id
chat_id = msg['chat']['id']
telegramText = msg['text']
print('Messaggio ricevuto! ' + str(chat_id) + telegramText)
# start engine per leggere i messaggi
engine = pyttsx3.init()
rate = engine.getProperty('rate') # variabile per cambiare velocita
engine.setProperty('rate', rate-50) # velocita voce
voice_id = 'italian'
engine.setProperty('voice', voice_id)
engine.say(telegramText)
engine.runAndWait()
if telegramText == '/start':
bot.sendMessage(chat_id, 'Sicurezza del perimetro attiva, sei protetto!')
# connessione bot telegram
bot = telepot.Bot('####')
bot.message_loop(handle)
# definizione funzione principale movimento
def main():
global chat_id
global motion
global motionNew
if GPIO.input(PIR) == 1:
print("Movimento rilevato!")
motion = 1
if motionNew != motion:
motionNew = motion
sendNotification()
elif GPIO.input(PIR) == 0:
motion = 0
if motionNew != motion:
motionNew = motion
def sendNotification():
global chat_id
bot.sendMessage(chat_id, 'ATTENZIONE! Qualcuno è alla porta!')
filename = "./video_" + (time.strftime("%y%b%d_%H%M%S"))
camera.start_recording(filename + ".h264")
sleep(10)
camera.stop_recording()
command = "MP4Box -add " + filename + '.h264' + " " + filename + '.mp4'
print(command)
call([command], shell=True)
bot.sendVideo(chat_id, video=open(filename + '.mp4', 'rb'))
print('Attendo 20 secondi')
time.sleep(20)
# definizione interrupt
def end_security():
print('End')
# check continuo sensore pir
try:
while True:
main()
except KeyboardInterrupt:
end_security()
I get an error in this line:
bot.sendMessage(chat_id, 'ATTENZIONE! Qualcuno è alla porta!')
error:
NameError: name 'chat_id' is not defined
How can I manage it? Thank you