Skip to content

Instantly share code, notes, and snippets.

@manix84
Last active February 8, 2025 18:12
Show Gist options
  • Save manix84/234c18f3e9ae09265679801e05e870f6 to your computer and use it in GitHub Desktop.
Save manix84/234c18f3e9ae09265679801e05e870f6 to your computer and use it in GitHub Desktop.
A python script for fetching images from Telegram to display on an Inky Frame
# This code is licensed under the terms of the MIT license
import os
import time
import random
import urequests as requests
import upytelegram as telegram
from inky_frame import InkyFrame
from machine import Pin
# --- Constants ---
BOT_TOKEN = 'your_bot_token'
CHANNEL_USERNAME = '@your_channel_name'
CHECK_INTERVAL_HOURS = 1
IMAGE_DIR = '/images' # SD Card path
# Set up Telegram Bot
bot = telegram.Bot(BOT_TOKEN)
# Initialize Inky Frame
inky = InkyFrame()
# Create the image directory if it doesn't exist
if not os.path.exists(IMAGE_DIR):
os.mkdir(IMAGE_DIR)
# Fetch the latest image from the Telegram channel
def get_latest_image():
try:
# Get updates from Telegram
updates = bot.get_updates()
for update in updates:
if update['message']['photo']:
# Get the largest image
file_id = update['message']['photo'][-1]['file_id']
image_url = bot.get_file(file_id)['file_path']
# Download the image
response = requests.get(image_url)
if response.status_code == 200:
image_filename = f"{IMAGE_DIR}/{file_id}.png"
with open(image_filename, 'wb') as f:
f.write(response.content)
print(f"New image saved: {image_filename}")
return image_filename
else:
print(f"Failed to download image: {response.status_code}")
return None
except Exception as e:
print(f"Error: {e}")
return None
# Display an image on the Inky Frame
def display_image(image_path):
try:
img = inky.load_image(image_path)
inky.display_image(img)
print(f"Displayed image: {image_path}")
except Exception as e:
print(f"Error displaying image: {e}")
# Choose a random image from the SD card if no new image is found
def choose_random_image():
try:
images = os.listdir(IMAGE_DIR)
if images:
selected_image = random.choice(images)
print(f"Selected random image: {selected_image}")
return f"{IMAGE_DIR}/{selected_image}"
else:
print("No images found in the SD card.")
return None
except Exception as e:
print(f"Error selecting random image: {e}")
return None
# Main loop to check for new images every N hours
def main():
while True:
latest_image = get_latest_image()
if not latest_image:
latest_image = choose_random_image()
if latest_image:
display_image(latest_image)
time.sleep(CHECK_INTERVAL_HOURS * 3600)
# Run the main loop
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment