Raspberry Pi Telegram Bot

May 16, 2026 · View on GitHub

Python Raspberry Pi License: MIT

A versatile Telegram bot that runs on a Raspberry Pi, allowing you to control your Pi and interact with it remotely via Telegram. Monitor system health, control GPIO pins, manage files, run shell commands, take camera snapshots, and much more — all from Telegram.


Table of Contents


Features

  • System Monitoring — CPU, RAM, disk, temperature, uptime, and an overall health score
  • Interactive Dashboard — Inline keyboard control panel with live stats
  • Remote Shell — Execute shell commands with blacklist/whitelist safety filters
  • File Manager — List, read, download, and upload files
  • GPIO Control — Digital on/off, PWM duty cycle, servo motor angles, I2C bus scanner
  • Camera — Take snapshots and run motion detection with auto-capture
  • Network Tools — IP info, WiFi scan, ping, port scanner, speed test
  • Process Manager — List top processes and kill by PID
  • Metrics & Alerts — Background metrics collection with plotted graphs and threshold alerts
  • AI Assistant — Ask questions via Anthropic Claude or OpenAI GPT
  • Task Scheduler — Schedule commands to run daily at a set time; manage cron jobs
  • Package Manager — Search, install, and remove APT packages
  • Backup — Create and send .tar.gz backups of Pi directories to Telegram
  • Weather — Current weather via OpenWeatherMap
  • Sensor Hub — Read DHT11/DHT22, BMP280, and PIR sensors
  • Notes — Per-user SQLite-backed notes
  • Authorization & Rate Limiting — Only whitelisted user IDs can use the bot
  • Audit Log — Every command logged to SQLite with timestamp and user info

Requirements

  • Raspberry Pi running Raspberry Pi OS (Debian-based)
  • Python 3.11+
  • A Telegram account and bot token from @BotFather

Installation

1. Clone the repository

git clone https://github.com/GraveEaterMadison/Raspberry_pi_telegram_bot.git
cd Raspberry_pi_telegram_bot

2. Create a virtual environment

python3 -m venv venv
source venv/bin/activate

3. Install dependencies

pip install -r requirements.txt

For optional hardware support, uncomment the relevant lines in requirements.txt first, then re-run the above. Or install manually:

# GPIO
pip install RPi.GPIO

# Camera (Pi 4 and newer)
pip install picamera2

# DHT11 / DHT22 sensors
pip install adafruit-circuitpython-dht adafruit-blinka

# BMP280 pressure/temperature sensor
pip install bmp280 smbus2

# I2C tools (via apt, not pip)
sudo apt install i2c-tools python3-smbus

# Internet speed test
pip install speedtest-cli

4. Create your bot on Telegram

  • Message @BotFather and run /newbot
  • Follow the prompts and copy the API token it gives you

5. Set up your environment file

cp .env.example .env
nano .env

At minimum set these two values:

TELEGRAM_BOT_TOKEN=your_token_here
AUTHORIZED_USERS=123456789

To find your Telegram user ID, message @userinfobot.

6. Run the bot

python main.py

Configuration

All configuration is done through the .env file. Copy .env.example to .env and fill in your values.

VariableRequiredDefaultDescription
TELEGRAM_BOT_TOKENToken from @BotFather
AUTHORIZED_USERSComma-separated Telegram user IDs, e.g. 123456789,987654321
AI_PROVIDERNoanthropicanthropic or openai
ANTHROPIC_API_KEYNoFor /ai command (get at console.anthropic.com)
OPENAI_API_KEYNoFor /ai command via OpenAI
OPENWEATHER_API_KEYNoFor /weather (free key at openweathermap.org)
CAMERA_BACKENDNopicamera2picamera2, opencv, or dummy
GPIO_MODENoBCMBCM or BOARD
DHT_SENSOR_TYPENoDHT22DHT11 or DHT22
DHT_PINNo4GPIO pin number for DHT sensor
BMP280_ADDRESSNo0x76I2C address of BMP280 sensor
PIR_PINNo17GPIO pin number for PIR motion sensor
BACKUP_PATHSNo/home/pi,/etcComma-separated paths to back up
MAX_EXEC_OUTPUTNo4000Max characters of shell command output
RATE_LIMIT_PER_MINUTENo20Max commands per user per minute
METRICS_HISTORY_SIZENo60Number of metric data points kept in memory
METRICS_INTERVALNo10Seconds between metric collections
LOG_LEVELNoINFODEBUG, INFO, WARNING, or ERROR
DB_PATHNodata/bot.dbPath to SQLite database
EXEC_WHITELISTNo(empty)Comma-separated allowed commands. Empty = allow all
EXEC_BLACKLISTNorm -rf /,mkfs,dd if=/dev/zeroAlways-blocked command patterns

Running as a Service

To run the bot automatically on boot using systemd:

1. Copy the service file

sudo cp pibot.service /etc/systemd/system/pibot.service

2. Edit paths if needed

sudo nano /etc/systemd/system/pibot.service

Make sure WorkingDirectory, ExecStart, and EnvironmentFile all point to your actual install location.

3. Enable and start

sudo systemctl daemon-reload
sudo systemctl enable pibot
sudo systemctl start pibot

4. Check status and logs

sudo systemctl status pibot
journalctl -u pibot -f

Commands

System

CommandDescription
/startWelcome message
/helpList all commands
/dashboardInteractive control panel
/infoFull system overview
/cpuCPU usage per core and load average
/ramRAM and swap usage
/diskDisk usage per partition
/uptimeSystem uptime
/temperatureCPU temperature with status
/healthscoreOverall Pi health score (0–100)

Network

CommandDescription
/ipIP addresses for all interfaces
/netinfoNetwork interface stats
/ping <host>Ping a host
/wifiScan nearby WiFi networks
/speedtestInternet speed test
/portscan <host> [range]Scan open ports on a host

Power & Services

CommandDescription
/rebootReboot the Pi (asks for confirmation)
/shutdownShut down the Pi (asks for confirmation)
/service <name> <action>start, stop, restart, status, enable, disable a service
/servicesList all running systemd services

Remote Execution

CommandDescription
/exec <command>Run a shell command
/psTop 20 processes by CPU usage
/kill <pid>Send SIGTERM to a process

Files

CommandDescription
/ls [path]List directory (default: /home/pi)
/cat <path>Read a file's contents
/download <path>Send a file to Telegram
(send a file)Upload a file to the Pi at /tmp/telegram_uploads/

GPIO & Hardware

CommandDescription
/gpio <pin> <on|off>Set a GPIO pin HIGH or LOW
/pwm <pin> <0-100>Set PWM duty cycle on a pin
/servo <pin> <0-180>Move a servo to an angle
/i2cScan I2C bus for connected devices
/sensorsRead DHT, BMP280, and CPU thermal sensors

Camera

CommandDescription
/snapshotTake a photo and send it
/motion <on|off>Toggle motion detection with auto-snapshot

Monitoring

CommandDescription
/graph <cpu|ram|temp>Plot a metric history graph
/alert set <metric> <op> <value>Set a resource alert, e.g. /alert set cpu > 85
/alert listList your active alerts
/alert clearClear all your alerts
/metricsTable of last 10 metric readings

AI

CommandDescription
/ai <question>Ask the AI assistant anything

Scheduler

CommandDescription
/schedule <HH:MM> <command>Schedule a command to run daily at a time
/cron listList scheduled tasks
/cron del <id>Delete a scheduled task

Notes

CommandDescription
/note add <text>Save a note
/note listList your notes
/note del <id>Delete a note

Packages

CommandDescription
/pkg search <name>Search APT packages
/pkg install <name>Install a package
/pkg remove <name>Remove a package
/pkg updateRun apt update

Misc

CommandDescription
/backup [paths...]Create a .tar.gz backup and send it
/weather [city]Current weather (auto-detects city from IP if omitted)

File Structure

Raspberry_pi_telegram_bot/

├── main.py                  # Entry point — registers all handlers
├── config.py                # Loads all settings from .env
├── requirements.txt         # Python dependencies
├── pibot.service            # systemd service file
├── .env.example             # Environment variable template
├── .env                     # Your local config (never commit this)

├── handlers/
│   ├── core.py              # /start, /help, /dashboard
│   ├── system.py            # /info, /cpu, /ram, /disk, /uptime, /temperature, /healthscore
│   ├── network.py           # /ip, /netinfo, /ping, /wifi, /speedtest, /portscan
│   ├── power.py             # /reboot, /shutdown, /service, /services
│   ├── exec_handler.py      # /exec
│   ├── files.py             # /ls, /cat, /download, upload handler
│   ├── gpio_handler.py      # /gpio, /pwm, /servo, /i2c
│   ├── camera.py            # /snapshot, /motion
│   ├── monitoring.py        # /graph, /alert, /metrics
│   ├── ai_handler.py        # /ai
│   ├── scheduler.py         # /schedule, /cron, background scheduler loop
│   ├── notes.py             # /note
│   ├── packages.py          # /pkg
│   ├── backup.py            # /backup
│   ├── weather.py           # /weather
│   ├── sensors.py           # /sensors
│   ├── process.py           # /ps, /kill
│   └── callbacks.py         # Inline keyboard callback router

├── utils/
│   ├── auth.py              # Authorization middleware and rate limiter
│   ├── logger.py            # SQLite audit logger
│   ├── metrics.py           # Background metrics collector
│   └── pi_info.py           # Legacy system utility functions

└── data/                    # Created at runtime
    ├── bot.db               # SQLite database (audit log, notes, scheduler)
    └── bot.log              # Log file

Security

  • AuthorizationAUTHORIZED_USERS in .env is a whitelist of Telegram user IDs. Anyone not on the list gets an "Access denied" message.
  • Rate limiting — Each authorized user is limited to RATE_LIMIT_PER_MINUTE commands per minute (default 20).
  • Exec safety/exec checks every command against EXEC_BLACKLIST. You can also set EXEC_WHITELIST to only allow specific commands.
  • File access/ls, /cat, /download only allow access under /home, /var/log, /etc, /tmp, and /opt.
  • Secrets — Keep your .env file private. It is gitignored by default and should never be committed.
  • Reboot / shutdown — Both commands require an inline confirmation button before executing.

Contributing

Contributions are welcome! Please fork this repository and submit a pull request with your improvements or bug fixes.


License

This project is licensed under the MIT License — see the LICENSE file for details.


Developed with ❤️ by GraveEaterMadison