You can download this code by clicking the button below.
This code is now available for download.
This function uses the Telethon library to randomly fetch a photo from a specified chat. It first retrieves the last 100 messages, then filters out messages containing photos, and finally randomly selects one photo to return.
Technology Stack : Telethon, Python
Code Type : Telethon third-party library functions
Code Difficulty : Intermediate
def get_random_chat_photo(client, chat):
"""
Fetches a random photo from a chat using Telethon.
Args:
client (telethon.client.client.Session): The client instance.
chat (telethon.tl.types.InputPeerChat): The chat from which to fetch the photo.
Returns:
telethon.tl.types.PhotoSize: The photo size object.
"""
messages = client.get_messages(chat, limit=100) # Fetch the last 100 messages
photos = [msg.photo for msg in messages if msg.photo] # Filter messages with photos
if photos:
random_photo = random.choice(photos) # Select a random photo
return random_photo
else:
return None