-2

Syntax Error

I'm trying to make a Raspberry Pi Project with Motion sensor which would send me a telegram message via a bot. "Room is Quiet now..." " Motion detected after 4.81 seconds" I found a reference at https://medium.com/@ManHay_Hong/how-to-create-a-telegram-bot-and-send-messages-with-python-4cf314d9fa3e [Medium website] in which i edited my code. But it doesn't give desired output.

from gpiozero import MotionSensor
from time import time
from time import sleep
import requests

def telegram_bot_sendtext(bot_message):

    bot_token = ''
    bot_chatID = ''
    send_text = 'https://api.telegram.org/bot' + ***api code*** + '/sendMessage?chat_id=' + ***chatid*** + '&parse_mode=Markdown&text=' + bot_message

    response = requests.get(send_text)

    return response.json()

pir = MotionSensor(26, sample_rate=5,queue_len=1)
bz = Buzzer(5)

while True:
   bz.off()
   old_time = time()
   pir.wait_for_motion()
   new_time = time()
   if new_time - old_time > 1:
      print("Motion detected after {:.2f} seconds".format(new_time-
            old_time))
      test = telegram_bot_sendtext("Motion detected after {:.2f} seconds".format(new_time-
            old_time)")
      print(test)
      bz.on()
      sleep(1)
      bz.off()
   old_time = new_time
   pir.wait_for_no_motion()
   new_time = time()

I have tried str(bot_message).

working code with output through cmd prompt

from gpiozero import Buzzer
from gpiozero import MotionSensor
from time import time
from time import sleep

pir = MotionSensor(26, sample_rate=5,queue_len=1)
bz = Buzzer(5)

while True:
   bz.off()
   old_time = time()
   pir.wait_for_motion()
   new_time = time()
   if new_time - old_time > 1:
      print("Motion detected after {:.2f} seconds".format(new_time-
            old_time))
      bz.on()
      sleep(1)
      bz.off()
   old_time = new_time
   pir.wait_for_no_motion()
   new_time = time()
   print("Room is quiet now...") 

1 Answers1

0

Checked the image attached.

The BOT-API-TOKEN value after /bot, and also chat_id value in URL should be a String. Enclose them with single or double quotes.

Like this:

send_text = 'https://api.telegram.org/bot' + '12345678:ABCDEFGHIJKLMN' + '/sendMessage?chat_id=' + '12345678' + '&parse_mode=Markdown&text=' + bot_message

You can also define two variables for BOT-API-TOKEN and chat_id, and use them directly in the URL.

bot_api_token = '12345678:ABCDEFGHIJKLMN'
chat_id = '12345678'
send_text = 'https://api.telegram.org/bot' + bot_api_token + '/sendMessage?chat_id=' + chat_id + '&parse_mode=Markdown&text=' + bot_message
Gagan T K
  • 588
  • 2
  • 13