0

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

1 Answers1

1

I think the problem is that when you call sendNotification() before handle() has been called then chat_id has not been set by anything so is undefined.

If you change your main loop code to the following, then you shouldn't get the error, since chat_id will be defined to a value at the beginning of the program.

    try:
    chat_id=999999999
    while True:
        main()

However, I'm not sure what you want chat_id to be set to when you call sendNotification() from the main() function since you don't have a message to take it from? Do you really need chat_id to be a global. It may be better to pass the chat id into sendNotification() as a parameter.

cguk70
  • 611
  • 3
  • 7
  • The problem is like you said I might add, if I were you, that he re-defined the variable once again into the codebase. – Istorn Feb 09 '22 at 09:57