为什么我的电报机器人无法回答?

Why is my telegram bot not able to answer?

我想将我的 Raspberry Pi 用作气象站。因此我买了一个“Debo Sen Rain”和一个“Debo Sens BME680”。因为之前没用过Python,所以从网上复制了两个脚本。他们都做得很好。昨天我创建了一个电报机器人,它应该在发送“/data”或“/rain”时向我发送当前测量数据。所以我将原始脚本复制到一个新的 python 脚本中并嵌入了机器人。不幸的是,它不起作用,但我找不到错误。

这是我的代码:

#!/usr/bin/python3
#coding: utf8

# telegram import
import time, datetime
import telepot
from telepot.loop import MessageLoop
# import os

# bme680 import
import board
from busio import I2C
import adafruit_bme680

i2c = I2C(board.SCL, board.SDA)
bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, debug = False)
bme680.sea_level_pressure = 971.91
temperature_offset = 0

temperatur = "Temperatur: %0.1f C" % (bme680.temperature + temperature_offset)
gas = "Gas: %d ohm" % bme680.gas
luftfeuchtigkeit = "Luftfeuchtigkeit: %0.1f %%" % bme680.relative_humidity
luftdruck = "Luftdruck: %0.3f hPa" % bme680.pressure

messdaten = temperatur + "\n" + gas + "\n" + luftfeuchtigkeit + "\n" +  luftdruck

#rain import
from time import sleep
from gpiozero import InputDevice

rain = InputDevice(18)

while True:
    if rain.is_active:
        regen = "Es regnet. Fenster zu!"
    else:
        regen = "Es regnet nicht"


now = datetime.datetime.now()

def action(msg):
    chat_id=msg['chat']['id']
    command = msg['text']
    
    print ('Received: %s' % command)
    
    if command == '/hi':
        telegram_bot.sendMessage (chat_id, str("Kuckuck"))
    
    elif command == '/data':
        telegram_bot.sendMessage (chat_id, str(messdaten))
        
    elif command == '/rain':
        telegram_bot.sendMessage (chat_id, str(regen))

telegram_bot = telepot.Bot('XXX:XXXXXXX')
print (telegram_bot.getMe())

MessageLoop(telegram_bot, action).run_as_thread()
print ('Up and Running...')

# Keep the program running.
while 1:
    time.sleep(10)

(我尝试使用 Python 编辑器“Mu”运行 脚本。)

非常感谢您的帮助。

让我们仔细看看这部分代码:

while True:
    if rain.is_active:
        regen = "Es regnet. Fenster zu!"
    else:
        regen = "Es regnet nicht"

因为 while True 永远不会 退出,下面的 Telegram 代码将永远无法到达。

您需要修改循环,在发送 Telegram 消息的同一循环中更新 regen 变量