Why is my telegram bot not able to answer?

Viewed 74

I would like to use my Raspberry Pi as a weather station. Therefore I bought a "Debo Sen Rain" and a "Debo Sens BME680". Because I've never worked with Python before, I copied two scripts out of the Internet. They do both work very well. Yesterday I created a telegram bot, which should send me the current measured data, when sending "/data" or "/rain". So I copied the original scripts in a new python script and embedded the bot. Unfortunately, It doesn't work but I can't locate the error.

Here's my code:

#!/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)

(I tried to run the script with the Python editor "Mu".)

Thanks a lot for your help.

1 Answers

Lets take a closer look at this part of your code:

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

Sinde the while True will never quit, the Telegram code below will never be reached.

You'd need to rework you loopings, update the regen variable in the same loop as you'd send your Telegram messages

Related