Python Snippets

Automatic Screenshot Taker with Timestamp and Upload Capability

import pyautogui
import datetime
import os
import time
import requests
from pathlib import Path

class ScreenshotTaker:
    def __init__(self, save_directory="screenshots"):
        """
        Initialize the screenshot taker with a save directory.
        
        Args:
            save_directory (str): Directory to save screenshots
        """
        self.save_directory = Path(save_directory)
        self.save_directory.mkdir(exist_ok=True)
    
    def take_screenshot(self, filename=None):
        """
        Take a screenshot with an optional custom filename.
        
        Args:
            filename (str, optional): Custom filename for the screenshot
            
        Returns:
            Path: Path to the saved screenshot
        """
        # Generate timestamp if no filename provided
        if not filename:
            timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"screenshot_{timestamp}.png"
        
        # Full path to save the screenshot
        filepath = self.save_directory / filename
        
        # Take the screenshot
        screenshot = pyautogui.screenshot()
        screenshot.save(filepath)
        
        print(f"Screenshot saved: {filepath}")
        return filepath
    
    def take_scheduled_screenshots(self, interval_minutes=5, count=10):
        """
        Take multiple screenshots at scheduled intervals.
        
        Args:
            interval_minutes (int): Minutes between screenshots
            count (int): Number of screenshots to take
        """
        print(f"Taking {count} screenshots every {interval_minutes} minutes...")
        
        for i in range(count):
            self.take_screenshot()
            if i < count - 1:  # Don't sleep after the last screenshot
                print(f"Waiting {interval_minutes} minutes for next screenshot...")
                time.sleep(interval_minutes * 60)
    
    def upload_to_imgur(self, image_path, client_id):
        """
        Upload a screenshot to Imgur (requires Imgur API client ID).
        
        Args:
            image_path (Path): Path to the image file
            client_id (str): Imgur API client ID
            
        Returns:
            str: URL of the uploaded image or None if failed
        """
        try:
            url = "https://api.imgur.com/3/image"
            headers = {"Authorization": f"Client-ID {client_id}"}
            
            with open(image_path, "rb") as image_file:
                files = {"image": image_file}
                response = requests.post(url, headers=headers, files=files)
                
            if response.status_code == 200:
                data = response.json()
                image_url = data["data"]["link"]
                print(f"Image uploaded: {image_url}")
                return image_url
            else:
                print(f"Upload failed: {response.status_code} - {response.text}")
                return None
                
        except Exception as e:
            print(f"Error uploading image: {e}")
            return None

# Example usage
if __name__ == "__main__":
    # Initialize the screenshot taker
    screenshot_taker = ScreenshotTaker("my_screenshots")
    
    # Take a single screenshot
    screenshot_path = screenshot_taker.take_screenshot()
    
    # For scheduled screenshots, uncomment the following line:
    # screenshot_taker.take_scheduled_screenshots(interval_minutes=1, count=3)
    
    # For Imgur upload, you need an Imgur API client ID
    # upload_url = screenshot_taker.upload_to_imgur(screenshot_path, "YOUR_IMGUR_CLIENT_ID")

What This Code Does

This Python snippet provides a comprehensive screenshot utility that can:

  1. Take individual screenshots with timestamped filenames
  2. Schedule multiple screenshots at specified intervals
  3. Save screenshots to a designated directory
  4. Upload screenshots to Imgur (with API credentials)

The code uses pyautogui for taking screenshots, Python’s standard libraries for time management and file operations, and requests for uploading capabilities.

Why This Is Useful

This utility solves several common problems:

How to Run

  1. Install required packages:
    pip install pyautogui requests
    
  2. Run the script as-is to take a single screenshot:
    python screenshot_tool.py
    
  3. For scheduled screenshots, uncomment the relevant lines in the if __name__ == "__main__": section

  4. For Imgur uploads:
    • Register at Imgur API to get a client ID
    • Replace "YOUR_IMGUR_CLIENT_ID" with your actual client ID
    • Uncomment the upload line

Features

The tool is especially useful for developers documenting bugs, creating tutorials, or monitoring long-running processes.