Created
April 13, 2026 15:22
-
-
Save kujirahand/80222cb3a6a53accdc4359b55188ad6d to your computer and use it in GitHub Desktop.
ラズパイで画像を撮影してTelegramに送信するプログラム
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import os | |
| import subprocess | |
| import sys | |
| import requests | |
| from dotenv import load_dotenv | |
| load_dotenv() # .envファイルを読み込む | |
| PHOTO_PATH = "photo.jpg" | |
| BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") | |
| CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID") | |
| CAPTION = os.environ.get("TELEGRAM_CAPTION", "ラズパイから送信した写真です") | |
| def take_photo(photo_path: str) -> None: | |
| """写真を撮影する""" | |
| cmd = ["fswebcam", "--no-banner", photo_path] | |
| try: | |
| subprocess.run(cmd, check=True) | |
| except FileNotFoundError: | |
| raise RuntimeError("fswebcam が見つかりません。先にインストールしてください。") | |
| except subprocess.CalledProcessError as e: | |
| raise RuntimeError(f"fswebcam の実行に失敗しました: {e}") | |
| def send_photo(bot_token: str, chat_id: str, photo_path: str, caption: str = "") -> dict: | |
| """写真を送信する""" | |
| url = f"https://api.telegram.org/bot{bot_token}/sendPhoto" | |
| data = {"chat_id": chat_id} | |
| if caption: | |
| data["caption"] = caption | |
| try: | |
| with open(photo_path, "rb") as f: | |
| files = {"photo": f} | |
| res = requests.post(url, data=data, files=files, timeout=30) | |
| res.raise_for_status() | |
| payload = res.json() | |
| if not payload.get("ok"): | |
| raise RuntimeError(f"Telegram API 失敗: {payload}") | |
| return payload | |
| except requests.exceptions.RequestException as e: | |
| error_msg = str(e) | |
| if hasattr(e, "response") and e.response is not None: | |
| error_msg += f" {e.response.text}" | |
| raise RuntimeError(f"Telegram API エラー: {error_msg}") | |
| def main() -> int: | |
| if not BOT_TOKEN: | |
| print("環境変数 TELEGRAM_BOT_TOKEN が設定されていません。", file=sys.stderr) | |
| return 1 | |
| try: | |
| print("写真を撮影しています...") | |
| take_photo(PHOTO_PATH) | |
| print("Telegram に送信しています...") | |
| result = send_photo(BOT_TOKEN, CHAT_ID, PHOTO_PATH, CAPTION) | |
| message_id = result.get("result", {}).get("message_id") | |
| print(f"送信成功: message_id={message_id}") | |
| return 0 | |
| except Exception as e: | |
| print(f"エラー: {e}", file=sys.stderr) | |
| return 1 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment