Skip to content

Instantly share code, notes, and snippets.

@v1dhun
Created February 28, 2025 18:01
Show Gist options
  • Save v1dhun/b574f25449ad61e8e46378a315e4dce8 to your computer and use it in GitHub Desktop.
Save v1dhun/b574f25449ad61e8e46378a315e4dce8 to your computer and use it in GitHub Desktop.

Revisions

  1. v1dhun created this gist Feb 28, 2025.
    53 changes: 53 additions & 0 deletions monitor_temperatures.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    #!/bin/bash

    # Configuration
    LOG_FILE="/var/log/temperature_monitor.log" # Log file location
    ALERT_THRESHOLD=60 # Temperature alert threshold (°C)
    CHECK_INTERVAL=30 # Interval between checks (seconds)

    # Telegram Bot Configuration
    TELEGRAM_BOT_TOKEN="YOUR_BOT_API_TOKEN" # Replace with your Telegram Bot Token
    TELEGRAM_CHAT_ID="YOUR_CHAT_ID" # Replace with your Telegram Chat ID

    # Function to log messages
    log_message() {
    local message="$1"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" | tee -a "$LOG_FILE"
    }

    # Function to send alerts via Telegram
    send_telegram_alert() {
    local name="$1"
    local temp="$2"
    local alert_message="🚨 Temperature Alert: $name is at $temp°C!"

    log_message "$alert_message"

    # Send the message to Telegram
    curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
    -d chat_id="${TELEGRAM_CHAT_ID}" \
    -d text="$alert_message" > /dev/null
    }

    # Function to check temperatures
    check_temperatures() {
    for zone in /sys/class/thermal/thermal_zone*; do
    name=$(cat "$zone/type")
    temp=$(cat "$zone/temp")
    temp_c=$(bc <<< "scale=1; $temp/1000")

    log_message "Sensor: $name, Temperature: $temp_c°C"

    # Alert if temperature exceeds threshold
    if (( $(echo "$temp_c > $ALERT_THRESHOLD" | bc -l) )); then
    send_telegram_alert "$name" "$temp_c"
    fi
    done
    }

    # Main monitoring loop
    log_message "Starting temperature monitor..."
    while true; do
    check_temperatures
    sleep "$CHECK_INTERVAL"
    done