【问题标题】:Why is my telegram bot not able to answer?为什么我的电报机器人无法接听?
【发布时间】:2022-01-07 06:03:47
【问题描述】:

我想将我的 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”运行脚本。)

非常感谢您的帮助。

【问题讨论】:

    标签: python raspberry-pi telegram-bot


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-21
      • 2017-09-16
      • 2015-02-21
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      相关资源
      最近更新 更多