【问题标题】:Syntax error when trying to send message via telegram bot尝试通过电报机器人发送消息时出现语法错误
【发布时间】:2023-12-21 16:27:01
【问题描述】:

Syntax Error

我正在尝试使用运动传感器制作一个 Raspberry Pi 项目,该项目将通过机器人向我发送电报消息。 “现在房间很安静……” “ 4.81 秒后检测到运动” 我在https://medium.com/@ManHay_Hong/how-to-create-a-telegram-bot-and-send-messages-with-python-4cf314d9fa3e [Medium website] 找到了一个参考,我在其中编辑了我的代码。但它没有提供所需的输出。

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()

我已经尝试过 str(bot_message)。

通过 cmd 提示输出的工作代码

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...") 

【问题讨论】:

    标签: python raspberry-pi python-telegram-bot motion-detection


    【解决方案1】:

    检查了附加的图像。

    /bot 之后的 BOT-API-TOKEN 值以及 URL 中的 chat_id 值应该是 String。用单个或两个 quotes 将它们括起来。

    像这样:

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

    您也可以为BOT-API-TOKEN和chat_id定义两个变量,直接在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
    

    【讨论】:

      最近更新 更多