You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求树莓派与Telegram Bot交互代码:按钮触发拍照并自动发送

Hey there! Let's walk through building this Raspberry Pi + Telegram Bot setup where pressing a button snaps a photo and sends it straight to your bot. I’ve tinkered with similar projects before, so here’s a step-by-step guide that should get you up and running smoothly.

1. What You’ll Need
  • A Raspberry Pi (any model with camera support, like Pi 3/4/Zero W)
  • Pi Camera module (v2 or newer works great)
  • A physical button, jumper wires, and optionally a breadboard
  • A Telegram account (to create your bot and receive photos)
  • Your Pi connected to the internet, with camera functionality enabled
2. Set Up Your Telegram Bot

First, we need a bot to handle sending photos:

  • Open Telegram, search for @BotFather
  • Send /newbot and follow the prompts to name your bot and pick a unique username. When you’re done, BotFather will give you an API Token—save this somewhere, you’ll need it later.
  • Send a quick message to your new bot (anything works!) so it registers your chat. To get your chat ID, run this command in your Pi’s terminal (replace <YOUR_TOKEN> with your API token):
    curl https://api.telegram.org/bot<YOUR_TOKEN>/getUpdates
    
    Look for the chat.id value in the JSON response—note that down too.
3. Wire Up the Button

Let’s connect the button to your Pi’s GPIO:

  • Connect one leg of the button to GPIO pin 17 (using BCM numbering)
  • Connect the other leg to a GND pin on the Pi
  • Pro tip: You can enable the Pi’s internal pull-up resistor in code instead of using an external one, so no extra parts needed!
4. Install Required Libraries

Before writing code, install the tools we’ll use:

  • First, make sure your camera is enabled: Run sudo raspi-config, go to Interfacing Options → Camera → select Enable, then reboot your Pi.
  • Install the Python libraries:
    pip install python-telegram-bot==13.7  # Stable version that plays nice with Python 3
    pip install picamera2  # For newer Pi OS versions (Bullseye+)—use `picamera` for older versions
    pip install RPi.GPIO
    
5. The Full Code

Here’s a complete, commented script that ties everything together. Save it as telegram_camera_bot.py:

import RPi.GPIO as GPIO
from picamera2 import Picamera2
import time
from telegram import Bot
from telegram.error import TelegramError

# Configure your settings here
TELEGRAM_TOKEN = "YOUR_API_TOKEN_HERE"
CHAT_ID = "YOUR_CHAT_ID_HERE"
BUTTON_PIN = 17  # GPIO pin connected to your button
IMAGE_SAVE_PATH = "/home/pi/captured_photo.jpg"  # Where to save the photo temporarily

# Set up GPIO for the button
GPIO.setmode(GPIO.BCM)
# Enable internal pull-up resistor so button reads HIGH until pressed
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# Initialize the camera
picam2 = Picamera2()
# Configure camera for still photos (1080p resolution)
camera_config = picam2.create_still_configuration(main={"size": (1920, 1080)})
picam2.configure(camera_config)

# Initialize Telegram Bot
bot = Bot(token=TELEGRAM_TOKEN)

def snap_and_send():
    try:
        print("Button pressed—capturing photo...")
        # Start camera and give it a moment to warm up
        picam2.start()
        time.sleep(2)
        # Capture photo to the specified path
        picam2.capture_file(IMAGE_SAVE_PATH)
        picam2.stop()
        print("Photo captured!")

        # Send the photo to Telegram
        print("Sending photo to your bot...")
        with open(IMAGE_SAVE_PATH, 'rb') as photo_file:
            bot.send_photo(chat_id=CHAT_ID, photo=photo_file)
        print("Photo sent successfully!")
    except TelegramError as te:
        print(f"Oops, Telegram error: {te}")
    except Exception as e:
        print(f"Something went wrong: {e}")

try:
    print("Ready! Press the button to take and send a photo.")
    while True:
        # Check if button is pressed (reads LOW when pressed)
        if GPIO.input(BUTTON_PIN) == GPIO.LOW:
            snap_and_send()
            # Debounce: Wait for button to be released to avoid multiple triggers
            while GPIO.input(BUTTON_PIN) == GPIO.LOW:
                time.sleep(0.1)
        time.sleep(0.1)
except KeyboardInterrupt:
    print("\nProgram stopped by you.")
finally:
    # Clean up GPIO settings when done
    GPIO.cleanup()
6. Run and Test
  • Run the script with: python3 telegram_camera_bot.py
  • Press the button—wait 2-3 seconds for the camera to warm up, and you should see the photo pop up in your Telegram chat with the bot!
7. Quick Troubleshooting
  • Camera not working? Double-check it’s plugged in correctly, enabled in raspi-config, and try running sudo chmod 777 /dev/video0 to fix permission issues.
  • Photos not sending? Verify your API token and chat ID are correct, and make sure your Pi has a stable internet connection.
  • Button triggers multiple times? Adjust the debounce delay in the code (the time.sleep(0.1) in the while loop) to be longer.

内容的提问来源于stack exchange,提问作者cpp24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:54:51