This tutorial will guide you through an efficient and hands-free way to monitor your surroundings or projects by capturing images with a USB camera connected to a Raspberry Pi and sending them to your Telegram account. This setup has a range of practical applications, including:
By the end of this tutorial, you'll have a fully automated system that integrates image capturing, messaging, and scheduling, all customizable to your specific needs.
sudo apt update
sudo apt upgrade
fswebcam
package:
sudo apt install fswebcam
fswebcam test_image.jpg
To send images via Telegram, you'll need a Telegram bot and its API token, as well as your chat ID.
/start
to begin interacting with BotFather./newbot
to create a new bot, then follow the instructions to name your bot.API token
. Save this token, as you'll need it to authenticate your bot.from telegram import Bot
API_TOKEN = 'YOUR_BOT_API_TOKEN' # Replace with your actual bot API token
bot = Bot(token=API_TOKEN)
updates = bot.get_updates()
for update in updates:
print(update.message.chat_id)
Replace YOUR_BOT_API_TOKEN
with the actual token from BotFather, then run this script on your Raspberry Pi:
python3 get_chat_id.py
from telegram import Bot
API_TOKEN = 'YOUR_BOT_API_TOKEN'
CHAT_ID = 'YOUR_CHAT_ID'
bot = Bot(token=API_TOKEN)
bot.send_message(chat_id=CHAT_ID, text="Hello from your Raspberry Pi!")
We’ll now automate capturing an image and sending it to Telegram using cron jobs.
capture_and_send.py
to capture an image and send it to Telegram:
from telegram import Bot
import subprocess
import time
API_TOKEN = 'YOUR_BOT_API_TOKEN'
CHAT_ID = 'YOUR_CHAT_ID'
IMAGE_PATH = '/home/pi/captured_image.jpg'
# Capture image
subprocess.run(['fswebcam', IMAGE_PATH])
# Send image
bot = Bot(token=API_TOKEN)
with open(IMAGE_PATH, 'rb') as image_file:
bot.send_photo(chat_id=CHAT_ID, photo=image_file)
crontab -e
0 * * * * /usr/bin/python3 /home/pi/capture_and_send.py