Quick answer: an ESP32-CAM can talk to Telegram by itself, with no server and no port forwarding. Create a bot with @BotFather, install the UniversalTelegramBot and ArduinoJson libraries, and flash a sketch that checks Telegram for new messages every second. When the allowed chat sends /photo, it captures a JPEG and uploads it with sendPhoto. Add an HC-SR501 PIR on GPIO13 and the same sketch sends a "Motion detected" photo on its own. The two things that trip most people up are power (use a solid 5 V, 2 A supply) and security (the sketch must ignore every chat ID except yours).
This project gives you one complete sketch with these commands:
| Command | What it does |
|---|---|
/photo | Takes a fresh photo and sends it to your chat |
/flash | Toggles the onboard flash LED for the next photos |
/arm / /disarm | Turns PIR motion alerts on or off |
/status | Replies with armed state, flash state, Wi-Fi signal and uptime |
/help | Lists the commands |
It also covers a second design, a small Python gateway on a PC or Raspberry Pi. That design keeps the bot token off the camera, which suits shared or exposed installs.
How it works (and why no port forwarding is needed)
The ESP32-CAM never waits for incoming connections. It repeatedly asks Telegram's servers "are there new messages for my bot?" using the Bot API's getUpdates method over HTTPS. When a /photo message arrives, the board checks which chat it came from, captures a frame, and uploads it with sendPhoto. Telegram then delivers the photo to your phone.
Because every connection goes out from your network, the camera works behind an ordinary home router and even on mobile hotspots or CGNAT connections, with nothing exposed to the internet. Compare that with the CameraWebServer stream, which only works on your LAN unless you open a port.
| Approach | Where the bot token lives | Extra hardware | Best for |
|---|---|---|---|
| A. Direct on ESP32-CAM (main build below) | In the ESP32 firmware | None | Home projects, one owner, quick setup |
| B. Python gateway | On a PC / Raspberry Pi | Always-on computer | Shared spaces, several cameras, logging, stricter security |
Components
6 itemsNeed these parts? Get this build sheet by email
Parts list with buy links, plus new builds as they're published. By subscribing you agree to our Privacy Policy. Unsubscribe anytime.
💡 Tip
The bot token works like a password: anyone who has it can read your bot's messages and send photos as your bot. Keep it out of GitHub, screenshots and forum posts, and revoke it with BotFather's /revoke if it ever leaks.
Step 1: Create the Telegram bot
- In Telegram, search for @BotFather (the official one has a blue check mark) and send
/newbot. - Give the bot a display name (e.g. Garage Cam) and a username ending in
bot(e.g.garage_cam_8421_bot). - BotFather replies with a token that looks like
123456789:AAE.... Copy it somewhere private. Anyone with this token controls your bot. - Open a chat with your new bot and press Start. A bot can't message you until you have done this.
- Optional but tidy: send BotFather
/setcommands, pick your bot, and paste the list below. Telegram then shows the commands as a menu in the chat.
photo - Take a photo now
flash - Toggle the flash LED
arm - Turn motion alerts on
disarm - Turn motion alerts off
status - Camera status
help - List commandsFind your chat ID
The sketch only obeys one chat ID, so you need yours. There are two easy ways:
- From the sketch itself (no extra tools): flash the sketch with
ALLOWED_CHAT_IDleft as"0", send/startto the bot, and the Serial Monitor printsIgnored message from chat 123456789. That number is your ID. Put it in the sketch and flash again. - From the Bot API: send any message to the bot, then open
https://api.telegram.org/bot<TOKEN>/getUpdatesin a browser and look for"chat":{"id":123456789. That URL contains your token, so don't paste it in screenshots or forums.
A private chat ID is a positive number. Group chat IDs are negative (supergroups start with -100).
Step 2: Prepare the Arduino IDE
| Setting | Value |
|---|---|
| Boards package | esp32 by Espressif Systems (Boards Manager), version 2.0.x or 3.x |
| Board | AI Thinker ESP32-CAM |
| Libraries (Library Manager) | UniversalTelegramBot by Brian Lough, ArduinoJson by Benoit Blanchon |
| Upload speed | 115200 if uploads fail at higher speeds |
If you have never flashed an ESP32-CAM before, follow the wiring and the "GPIO0 to GND" boot-mode steps in the ESP32-CAM web server setup guide first, and confirm the CameraWebServer example works. If that works, the camera, power and upload method are all proven, and any later problem is in the Telegram part.
With an ESP32-CAM-MB board you just plug in USB. With an FTDI adapter: 5V → 5V, GND → GND, adapter TX → U0R, adapter RX → U0T, and a jumper from GPIO0 to GND while uploading (remove it and press RESET to run).
Step 3: Wire the PIR sensor (optional)
Skip this step if you only want photos on request. The sketch works without a PIR connected.
| HC-SR501 pin | ESP32-CAM pin | Note |
|---|---|---|
| VCC | 5V | The module has its own 3.3 V regulator |
| OUT | GPIO13 | Output is 3.3 V logic, safe for the ESP32 |
| GND | GND |
Set the HC-SR501 time-delay pot fully anticlockwise (shortest pulse) and the trigger jumper to H (repeat). The sketch handles repeats with its own cooldown. The module needs up to a minute after power-up to settle and may trigger randomly during that time, so the sketch ignores it for the first 60 seconds.
Why GPIO13? On the AI-Thinker board most pins are taken by the camera. GPIO13 is free as long as no microSD card is used, and it is not a boot strapping pin. Avoid GPIO12: if it is pulled HIGH at reset, the flash voltage is set wrong and the board won't boot. GPIO4 drives the bright flash LED. For the full map, see the ESP32-CAM pinout guide.
Step 4: The sketch
Fill in your Wi-Fi details, bot token and chat ID at the top, then upload. Open the Serial Monitor at 115200 baud: you should see the IP address, and your phone gets a "camera online" message.
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include "esp_camera.h"
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
// ---------- Your settings ----------
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";
#define BOT_TOKEN "123456789:AAE_your_token_from_BotFather"
const String ALLOWED_CHAT_ID = "0"; // your chat ID; "0" = just log who writes
// ---------- Pins (AI-Thinker ESP32-CAM) ----------
#define FLASH_LED_PIN 4
#define PIR_PIN 13
const unsigned long BOT_POLL_MS = 1000; // check Telegram every second
const unsigned long PIR_WARMUP_MS = 60000; // ignore the PIR for 60 s after boot
const unsigned long MOTION_COOLDOWN_MS = 60000; // at most one motion alert per minute
WiFiClientSecure client;
UniversalTelegramBot bot(BOT_TOKEN, client);
unsigned long lastPoll = 0, lastMotionAlert = 0, lastWifiTry = 0;
bool flashOn = false;
bool armed = false;
int lastPir = LOW;
// sendPhotoByBinary() pulls the JPEG through these callbacks
camera_fb_t* fb = nullptr;
bool dataAvailable = false;
bool isMoreDataAvailable() { if (dataAvailable) { dataAvailable = false; return true; } return false; }
byte* getNextBuffer() { return fb ? fb->buf : nullptr; }
int getNextBufferLen() { return fb ? fb->len : 0; }
bool initCamera() {
camera_config_t c = {};
c.ledc_channel = LEDC_CHANNEL_0;
c.ledc_timer = LEDC_TIMER_0;
c.pin_d0 = 5; c.pin_d1 = 18; c.pin_d2 = 19; c.pin_d3 = 21;
c.pin_d4 = 36; c.pin_d5 = 39; c.pin_d6 = 34; c.pin_d7 = 35;
c.pin_xclk = 0; c.pin_pclk = 22; c.pin_vsync = 25; c.pin_href = 23;
c.pin_sccb_sda = 26; c.pin_sccb_scl = 27;
c.pin_pwdn = 32; c.pin_reset = -1;
c.xclk_freq_hz = 20000000;
c.pixel_format = PIXFORMAT_JPEG;
if (psramFound()) {
c.frame_size = FRAMESIZE_SVGA; // 800x600
c.jpeg_quality = 12; // 10-63, lower = better quality, bigger file
c.fb_count = 2;
c.fb_location = CAMERA_FB_IN_PSRAM;
c.grab_mode = CAMERA_GRAB_LATEST;
} else {
c.frame_size = FRAMESIZE_VGA;
c.jpeg_quality = 14;
c.fb_count = 1;
c.fb_location = CAMERA_FB_IN_DRAM;
c.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
}
esp_err_t err = esp_camera_init(&c);
if (err != ESP_OK) {
Serial.printf("Camera init failed: 0x%x\n", err);
return false;
}
return true;
}
void sendPhoto(const String& chatId) {
if (flashOn) { digitalWrite(FLASH_LED_PIN, HIGH); delay(150); }
// Throw one frame away so the photo is taken now, not a frame buffered earlier
fb = esp_camera_fb_get();
if (fb) esp_camera_fb_return(fb);
fb = esp_camera_fb_get();
digitalWrite(FLASH_LED_PIN, LOW);
if (!fb) {
bot.sendMessage(chatId, "Camera capture failed.", "");
return;
}
Serial.printf("Sending photo, %u bytes\n", fb->len);
dataAvailable = true;
String reply = bot.sendPhotoByBinary(chatId, "image/jpeg", fb->len,
isMoreDataAvailable, nullptr,
getNextBuffer, getNextBufferLen);
esp_camera_fb_return(fb);
fb = nullptr;
if (reply.length() == 0) Serial.println("No reply from Telegram to sendPhoto");
}
void sendStatus(const String& chatId) {
String s = "Motion alerts: " + String(armed ? "ON" : "OFF");
s += "\nFlash: " + String(flashOn ? "ON" : "OFF");
s += "\nWi-Fi signal: " + String(WiFi.RSSI()) + " dBm";
s += "\nUptime: " + String(millis() / 60000) + " min";
bot.sendMessage(chatId, s, "");
}
void handleMessages(int count) {
for (int i = 0; i < count; i++) {
String chatId = bot.messages[i].chat_id;
if (chatId != ALLOWED_CHAT_ID) {
Serial.println("Ignored message from chat " + chatId);
continue; // never reply to, or photograph for, unknown chats
}
String cmd = bot.messages[i].text;
int at = cmd.indexOf('@'); // "/photo@my_bot" in group chats
if (at > 0) cmd = cmd.substring(0, at);
cmd.trim();
cmd.toLowerCase();
if (cmd == "/photo") {
sendPhoto(chatId);
} else if (cmd == "/flash") {
flashOn = !flashOn;
bot.sendMessage(chatId, flashOn ? "Flash ON for photos" : "Flash OFF", "");
} else if (cmd == "/arm") {
armed = true;
bot.sendMessage(chatId, "Motion alerts ON", "");
} else if (cmd == "/disarm") {
armed = false;
bot.sendMessage(chatId, "Motion alerts OFF", "");
} else if (cmd == "/status") {
sendStatus(chatId);
} else {
bot.sendMessage(chatId,
"/photo - take a photo\n/flash - toggle flash\n/arm - motion alerts on\n"
"/disarm - motion alerts off\n/status - camera status", "");
}
}
}
void setup() {
Serial.begin(115200);
pinMode(FLASH_LED_PIN, OUTPUT);
digitalWrite(FLASH_LED_PIN, LOW);
pinMode(PIR_PIN, INPUT);
if (!initCamera()) { delay(3000); ESP.restart(); }
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // verify api.telegram.org
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
Serial.println("\nConnected, IP: " + WiFi.localIP().toString());
if (ALLOWED_CHAT_ID != "0") {
bot.sendMessage(ALLOWED_CHAT_ID, "ESP32-CAM online. Send /help for commands.", "");
}
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
if (millis() - lastWifiTry > 10000) { WiFi.reconnect(); lastWifiTry = millis(); }
return;
}
if (millis() - lastPoll > BOT_POLL_MS) {
int n = bot.getUpdates(bot.last_message_received + 1);
while (n) {
handleMessages(n);
n = bot.getUpdates(bot.last_message_received + 1);
}
lastPoll = millis();
}
int pir = digitalRead(PIR_PIN);
bool risingEdge = (pir == HIGH && lastPir == LOW);
lastPir = pir;
if (armed && risingEdge && millis() > PIR_WARMUP_MS &&
millis() - lastMotionAlert > MOTION_COOLDOWN_MS) {
lastMotionAlert = millis();
bot.sendMessage(ALLOWED_CHAT_ID, "Motion detected!", "");
sendPhoto(ALLOWED_CHAT_ID);
}
}How the sketch works
| Part | What it does | Why it matters |
|---|---|---|
client.setCACert(TELEGRAM_CERTIFICATE_ROOT) | Checks that the server really is api.telegram.org | Without a certificate check, anyone on the network path could impersonate Telegram and read your token |
bot.getUpdates(last_message_received + 1) | Asks only for messages newer than the last one handled | Each command runs once. Old commands aren't repeated on the next poll |
chatId != ALLOWED_CHAT_ID | Drops messages from anyone else | A bot's username is easy to find. Without this check, any Telegram user could request photos of your room |
| Discarding one frame | Grabs and returns a frame before the real capture | The camera keeps buffered frames; without this the "new" photo can be seconds old |
sendPhotoByBinary(...) | Streams the JPEG from the frame buffer as a multipart upload | No SD card and no extra copy of the image in RAM |
| Rising edge + 60 s cooldown | Alerts only on a LOW→HIGH PIR change, at most once a minute | Stops one person walking past from sending a dozen photos |
Photo size: SVGA (800×600) at quality 12 is usually 30–80 KB, which uploads in a second or two. You can raise frame_size to FRAMESIZE_UXGA (1600×1200) for more detail, but uploads get slower and the chance of a failed send on a weak Wi-Fi link goes up. Telegram accepts photos up to 10 MB, so size is limited by your Wi-Fi, not by Telegram.
Step 5: Test it
- Power the ESP32-CAM from the 5 V 2 A supply (not a laptop USB port) and wait for the "ESP32-CAM online" message.
- Send
/photo. A photo should arrive within about 2–4 seconds. - Send
/flash, then/photoin a dark room. The flash fires during capture. - Send
/arm, wait for the 60-second PIR warm-up, then walk past the sensor. You get "Motion detected!" followed by a photo, and no second alert for a minute. - Ask a friend to message the bot. Nothing should happen on their side, and the Serial Monitor logs "Ignored message from chat ...".
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Brownout detector was triggered, endless reboots | Supply can't handle the Wi-Fi + camera current peaks | Use a 5 V 2 A supply and a short, thick cable. Add a 470–1000 µF capacitor across 5V/GND. Don't disable the brownout detector: it is warning you about a real problem |
Camera init failed: 0x105 or 0x20001 | Camera ribbon loose, wrong board selected, or a pin conflict | Reseat the ribbon, select AI Thinker ESP32-CAM, and keep GPIO0/GPIO12 free |
| Board connects to Wi-Fi but the bot never replies | Wrong token, wrong chat ID, or you never pressed Start in the bot chat | Watch the Serial Monitor: "Ignored message from chat X" means the ID is wrong. No output at all means the token or TLS connection is failing |
getUpdates fails after it used to work | The library's built-in Telegram root certificate is out of date | Update UniversalTelegramBot. Only for a short test, client.setInsecure() shows whether the certificate is the problem; don't leave it in |
| Error 409 Conflict in the response | Two programs are polling with the same token, or a webhook is set | Run only one copy of the bot per token (not the ESP32 and a gateway at once). Clear webhooks with deleteWebhook |
| Photo is dark, green or purple | Auto-exposure hasn't settled, or the ribbon is loose | The discarded frame helps; in very dark rooms use /flash. Reseat the ribbon if colours are wrong |
| Photo arrives but is old | Buffered frame was sent | Keep the "throw one frame away" lines in sendPhoto() |
| Motion alerts fire with nobody there | PIR warm-up, heat sources, or Wi-Fi interference near the PIR | Wait out the warm-up. Aim the PIR away from heaters, vents and windows, and move it a few cm from the antenna |
| Compile errors in ArduinoJson | Library version mismatch | Update both libraries to their latest versions together |
| Sketch too big to upload | Camera + TLS + JSON code is large | If the board menu offers a partition scheme, pick Huge APP |
Option B: Python gateway (token stays off the camera)
If several people share the space, or the camera sits somewhere it could be stolen, keep the bot token on a computer instead. Anyone who reads the ESP32's flash can recover a token compiled into it. In this design the ESP32-CAM runs the standard CameraWebServer example, which serves a still image at http://<camera-ip>/capture. A small Python script on a PC or Raspberry Pi on the same network polls Telegram, fetches the JPEG and sends it to your chat.
Install requests, set three environment variables (TELEGRAM_BOT_TOKEN, TELEGRAM_ALLOWED_CHAT_ID, CAMERA_IP) and run the script:
import os
import time
import logging
import requests
TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
ALLOWED_CHAT_ID = os.environ.get("TELEGRAM_ALLOWED_CHAT_ID")
CAMERA_IP = os.environ.get("CAMERA_IP", "192.168.1.50")
COOLDOWN_SECONDS = 10
if not TOKEN or not ALLOWED_CHAT_ID:
raise RuntimeError("Set TELEGRAM_BOT_TOKEN and TELEGRAM_ALLOWED_CHAT_ID")
API = "https://api.telegram.org/bot" + TOKEN + "/"
CAPTURE_URL = "http://" + CAMERA_IP + "/capture"
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
session = requests.Session()
offset = 0
last_photo = 0.0
def call(method, **kwargs):
r = session.post(API + method, timeout=30, **kwargs)
r.raise_for_status()
if r.json().get("ok") is not True:
raise RuntimeError(method + " returned ok=false")
def send_photo(chat_id):
r = session.get(CAPTURE_URL, timeout=(3, 10))
r.raise_for_status()
if "image/jpeg" not in r.headers.get("Content-Type", "") or not r.content:
raise ValueError("Camera did not return a JPEG")
call("sendPhoto", data={"chat_id": chat_id},
files={"photo": ("esp32cam.jpg", r.content, "image/jpeg")})
while True:
try:
r = session.get(API + "getUpdates",
params={"timeout": 20, "offset": offset,
"allowed_updates": '["message"]'},
timeout=25)
r.raise_for_status()
for update in r.json().get("result", []):
offset = update["update_id"] + 1
# advance even for ignored updates
msg = update.get("message") or {}
chat_id = str((msg.get("chat") or {}).get("id", ""))
if chat_id != ALLOWED_CHAT_ID:
logging.warning("Ignored chat %s", chat_id)
continue
text = msg.get("text", "").strip()
cmd = text.split(maxsplit=1)[0].split("@", 1)[0].lower() if text else ""
if cmd == "/photo":
if time.monotonic() - last_photo < COOLDOWN_SECONDS:
call("sendMessage", data={"chat_id": chat_id, "text": "Wait a few seconds."})
continue
last_photo = time.monotonic()
try:
send_photo(chat_id)
except (requests.RequestException, ValueError, RuntimeError) as exc:
logging.error("Photo failed: %s", exc)
call("sendMessage", data={"chat_id": chat_id, "text": "Camera unavailable."})
else:
call("sendMessage", data={"chat_id": chat_id, "text": "Send /photo for a snapshot."})
except (requests.RequestException, ValueError, RuntimeError, KeyError) as exc:
logging.error("Polling error: %s", exc)
time.sleep(3)This uses long polling (timeout=20): Telegram holds the request open until a message arrives, so the bot reacts instantly without hammering the API. For unattended use, run it as a systemd service on a Raspberry Pi so it restarts after crashes and reboots. Keep the camera's /capture endpoint on your LAN only: it has no password, so never port-forward it.
| Direct on ESP32-CAM | Python gateway | |
|---|---|---|
| Parts | ESP32-CAM only | ESP32-CAM + always-on computer |
| Token exposure if the camera is stolen | Token can be read from flash | Token not on the camera |
| Motion alerts | Built in (PIR on GPIO13) | Needs extra code (e.g. the gateway polls a PIR endpoint) |
| Several cameras, one bot | One bot per camera (one poller per token) | One bot can serve many cameras |
| Logs and history | Serial Monitor only | Full logs, easy to save photos |
Security and privacy checklist
- Keep the token secret. Don't commit the sketch with the token to GitHub, and don't show it in screenshots. If it leaks, send BotFather
/revokeand flash the new token. - Never remove the chat ID check. Anyone can find and message a bot by its username.
- Groups widen the audience. If you allow a group chat ID, every member of that group sees every photo, and so does anyone added later.
- Photos go through Telegram's servers. Bot chats are not end-to-end encrypted. Point the camera only where everyone affected knows about it, and avoid bathrooms, bedrooms and neighbours' property.
- It isn't an alarm system. If Wi-Fi, power or Telegram is down, no alert arrives, and the bot doesn't tell you it missed anything. The startup message at least tells you when the camera has rebooted.
Frequently asked questions
Can the ESP32-CAM send video to Telegram? Not in a practical way. Telegram's sendVideo expects an encoded file such as MP4, and the ESP32 has no video encoder. Options that work: send a burst of 3–5 photos on motion, record an MJPEG/AVI clip to the microSD card and send it as a document (slow, and the SD card uses GPIO13 and GPIO4), or use the Python gateway to grab the stream and encode the clip on the computer.
Can more than one person use the bot? Yes. Either put everyone in a group and use the group's (negative) chat ID, or change the check to compare against a short list of allowed IDs. Keep the list explicit; never accept all chats.
Does it work without a PIR sensor? Yes. /photo, /flash and /status work with GPIO13 unconnected. Just don't send /arm, because a floating input can trigger random alerts. Add pinMode(PIR_PIN, INPUT_PULLDOWN) if you want to be safe.
Can I detect motion without a PIR, from the camera image? It is possible by comparing frames, but it is less reliable: lighting changes and auto-exposure cause false triggers, and constant frame comparison uses a lot of CPU. A PIR costs very little and is much more dependable.
Can I run it on batteries with deep sleep? Yes, with a different structure: the PIR wakes the ESP32 from deep sleep (esp_sleep_enable_ext0_wakeup on GPIO13), the sketch connects to Wi-Fi, sends one photo, and sleeps again. You lose the /photo command while it sleeps, and each wake takes a few seconds. The ESP32-CAM PIR motion camera shows the deep-sleep wake pattern.
Why use polling instead of a webhook? A webhook needs a public HTTPS server that Telegram can call. The ESP32-CAM can't be that without port forwarding and a valid certificate. Polling every second costs little and works on any network.
Will Telegram rate-limit my bot? Not at this level of traffic. Telegram's own guidance is to avoid sending more than about one message per second to the same chat, which the 60-second motion cooldown keeps you well under.
Where to go next
- ESP32-CAM pinout guide: which pins are free for sensors and relays
- ESP32 smart home relay control with a Telegram bot: the same bot pattern switching mains loads
- Node-RED PIR motion alerts to Telegram and email: alerts handled on a Node-RED server instead of on the board
- ESP32-CAM time-lapse recorder: scheduled photos saved to microSD
References: Telegram Bot API, UniversalTelegramBot library, Espressif esp32-camera driver.
Steps
- 1Create a bot with @BotFather, copy the token and press Start in the bot chat.
- 2Install the esp32 boards package plus the UniversalTelegramBot and ArduinoJson libraries.
- 3Optionally wire an HC-SR501 PIR: VCC to 5V, OUT to GPIO13, GND to GND.
- 4Fill in Wi-Fi, token and chat ID, upload the sketch, and power the board from a 5 V 2 A supply.
- 5Send /photo, then /arm and walk past the PIR to test motion alerts.



