Raspberry Pi Telegram bot: Temperature alerts with cooldown period

I’m working on a Raspberry Pi project that monitors CPU temperature using a Telegram bot. The bot checks the temperature every minute and sends an alert if it goes above a certain level. I want to add a 10-minute cooldown after each alert to avoid spamming.

Here’s what I’ve tried:

import telepot
import time

bot = telepot.Bot('YOUR_BOT_TOKEN')

def check_temp():
    while True:
        temp = get_cpu_temp()
        if temp > 30.0 and can_send_alert():
            message = f'CPU Temperature: {temp}°C'
            bot.sendMessage(USER_ID, message)
            set_cooldown()
        time.sleep(60)

def get_cpu_temp():
    # Your temperature reading code here
    pass

def can_send_alert():
    # Check if cooldown period has passed
    pass

def set_cooldown():
    # Set cooldown timer
    pass

check_temp()

The code runs fine at first, but after a while, I get a timeout error when trying to send messages. Any ideas on how to fix this or improve the overall structure? I couldn’t find much help in the telepot docs. Thanks!

hey there! i’ve had similar issues. try adding some error handling around the bot.sendMessage() call. like:

try:
bot.sendMessage(USER_ID, message)
except telepot.exception.TelegramError as e:
print(f’Error sending message: {e}')
time.sleep(5) # wait a bit before retrying

this should help with those pesky timeouts. also, maybe increase the sleep time a bit to reduce api calls. good luck!

I’ve been working with Raspberry Pi temperature monitoring for a while, and I can share some insights. First, consider using asyncio instead of threading for better performance. It’s more efficient for I/O-bound operations like network requests.

For the cooldown, a simple approach is to use a global variable to store the last alert time:

import time

last_alert_time = 0

def can_send_alert():
    global last_alert_time
    current_time = time.time()
    if current_time - last_alert_time > 600:  # 10 minutes in seconds
        last_alert_time = current_time
        return True
    return False

This avoids the need for complex timer management. Also, make sure you’re handling network errors properly. Telegram’s servers can be flaky sometimes, so implement a retry mechanism with increasing delays between attempts.

Lastly, consider adding some hysteresis to your temperature checks. This means only sending an alert when the temperature rises above the threshold and then falls below a lower threshold. It helps prevent alert spam when the temperature is fluctuating around the threshold.

I’ve implemented a similar system and found it beneficial to use a more robust approach for temperature monitoring. Consider leveraging the ‘schedule’ library instead of a continuous while loop. It offers better control and reliability.

For the cooldown mechanism, you could use a simple timestamp comparison. Store the last alert time and check against it before sending a new one. This approach is more efficient than managing separate timers.

Regarding the timeout issue, it’s often caused by network instability. Implementing a retry mechanism with exponential backoff can significantly improve reliability. Also, ensure you’re not exceeding Telegram’s rate limits for bot messages.

Lastly, consider logging temperature data to a file or database. It’ll help you analyze trends and optimize your alert thresholds over time.