Building a Telegram Bot for Raspberry Pi Monitoring and Remote Control

How I leveraged Claude Code to rapidly develop a comprehensive Telegram bot that monitors my Raspberry Pi's vital stats and allows remote system administration through push notifications and natural language commands.

The Problem: Monitoring Without Constant SSH

Running a Raspberry Pi as a home server comes with its own set of challenges. You need to monitor system health, check if services are running, and sometimes perform maintenance tasks—all while being away from your computer. Traditional monitoring solutions often require complex setups, web dashboards, or constant SSH access.

I wanted something simpler: push notifications when things go wrong and the ability to run commands remotely through a familiar interface. That's where Telegram bots come in.

Why Telegram Bots are Perfect for IoT Monitoring

Telegram bots offer several advantages over traditional monitoring solutions:

  • Push Notifications: Instant alerts delivered to your phone anywhere in the world
  • Simple API: Just HTTP POST requests - no complex frameworks needed
  • Bidirectional Communication: Not just monitoring, but remote control too
  • Mobile-First: Perfect for quick checks and emergency responses
  • Free: No monthly fees for monitoring services
  • Secure: Built-in user authentication and encrypted messages

The Solution: A Comprehensive Monitoring Bot

I built a two-part system that runs via cron jobs every minute:

  1. Monitoring Script - Continuously checks system vitals and sends alerts
  2. Command Handler - Processes incoming Telegram messages for remote control

System Monitoring Features

The monitoring script tracks multiple system metrics with intelligent alerting:

  • Temperature: Critical for Pi longevity (alerts above 75°C)
  • CPU Usage: Detects runaway processes (alerts above 90%)
  • Memory Usage: Prevents out-of-memory crashes (alerts above 85%)
  • Disk Space: Early warning for full drives (alerts below 10% free)
  • Web Services: Monitors nginx and application health
  • Security Events: Tracks failed SSH attempts and suspicious activity

Each metric uses sustained monitoring - issues must persist for 5+ minutes before triggering alerts, preventing spam from temporary spikes.

Remote Control Commands

The command handler transforms your phone into a remote terminal with over 20 built-in commands:

System Information

/status    - Complete system health report
/temp      - Current CPU temperature  
/uptime    - System uptime and load
/processes - Top running processes
/disk      - Disk usage breakdown
/network   - Network interface status

Service Management

/nginx status   - Check web server status
/nginx restart  - Restart nginx service
/pidash restart - Restart custom dashboard
/update         - System package updates

Claude Code Integration

/claude read [file]      - View file contents
/claude grep [term]      - Search within files
/claude search [term]    - Find files containing term
/claude analyze [file]   - Get file statistics

Claude Code: The Development Game-Changer

The most impressive part of this project was how quickly I built it using Claude Code. What typically would take days of research, coding, and debugging was completed in a few hours:

Rapid Prototyping

Claude Code helped me quickly iterate on the monitoring logic. I could describe what I wanted ("monitor temperature with sustained alerts") and get working Python code instantly, then refine it through natural language.

Error Handling and Edge Cases

Security and reliability were crucial. Claude Code helped implement proper error handling, input validation, and security measures like path restrictions for file operations.

Integration and Testing

Setting up cron jobs, testing the Telegram API integration, and handling different message formats was streamlined with Claude Code's understanding of system administration tasks.

Technical Implementation

Core Architecture

# Monitoring Script (runs every minute via cron)
*/1 * * * * python3 /home/pi/pi_monitor_comprehensive.py

# Command Handler (runs every minute via cron)  
*/1 * * * * python3 /home/pi/telegram_command_handler.py

Key Libraries Used

  • requests - Telegram API communication
  • psutil - System statistics and process monitoring
  • subprocess - System command execution
  • json - State persistence and API responses

Security Considerations

Security was paramount since this provides remote access to my system:

  • User Authentication: Only authorized Telegram user IDs can execute commands
  • Path Restrictions: File operations limited to safe directories
  • Command Timeouts: 30-second limits prevent hanging processes
  • Restart Confirmation: Dangerous operations require explicit confirmation
  • Log Monitoring: Track unauthorized access attempts

Real-World Usage Examples

Emergency Response

Last week, I received a temperature alert at 2 AM showing my Pi was running at 82°C. Using the bot, I quickly checked running processes, identified a runaway Python script, and killed it - all from my phone while half-asleep.

Proactive Maintenance

Daily status checks help me spot trends before they become problems. I noticed memory usage slowly climbing over several days and discovered a memory leak in a custom service.

Remote Troubleshooting

When someone reported my website was down, I used the bot to restart nginx and check error logs, resolving the issue in under two minutes without needing to boot up my computer.

Lessons Learned

The Power of Push Notifications

Having alerts delivered instantly to my phone has prevented several major issues. The sustained monitoring approach eliminates false alarms while ensuring real problems get attention quickly.

Mobile-First Administration

80% of my Pi administration now happens through Telegram. The convenience of handling issues immediately, regardless of location, has been transformative.

Claude Code as a Force Multiplier

This project showcased how AI-assisted development can accelerate everything from initial prototyping to production deployment. Complex system administration tasks became approachable and implementable in hours rather than days.

Future Enhancements

I'm planning several improvements:

  • Historical Data: Store metrics in a lightweight database for trend analysis
  • Automated Responses: Self-healing for common issues like high memory usage
  • Multi-Pi Support: Extend to monitor multiple Raspberry Pis
  • Integration Hub: Connect with other home automation systems
  • Custom Dashboards: Generate visual reports on demand

Getting Started

If you want to build something similar:

  1. Create a Telegram bot using @BotFather
  2. Get your chat ID by messaging the bot and checking the API
  3. Install required Python packages: pip install requests psutil
  4. Start with basic temperature monitoring and expand from there
  5. Use Claude Code to accelerate development and handle edge cases

Conclusion

This Telegram bot has transformed how I manage my Raspberry Pi infrastructure. The combination of proactive monitoring, instant notifications, and remote control capabilities provides peace of mind and rapid response capabilities.

More importantly, this project demonstrated the incredible productivity gains possible with AI-assisted development. Claude Code didn't just help me write code - it helped me think through architecture decisions, implement security measures, and handle edge cases I might have missed.

For anyone running IoT devices or home servers, I highly recommend exploring Telegram bots as a monitoring and control solution. They're simple to implement, powerful in practice, and with tools like Claude Code, surprisingly quick to build.