Random Media Message Sender

  • Share this:

Code introduction


This function uses the Telethon library to send a random photo or document message to a specified chat ID, and automatically deletes the media file after sending.


Technology Stack : Telethon, Python

Code Type : Telethon API call

Code Difficulty : Intermediate


                
                    
def send_random_media_message(client, chat_id):
    from telethon.tl.functions.messages import SendMediaRequest
    from telethon.tl.types import InputPeerUser, InputMediaPhoto, InputMediaDocument
    import random

    # Randomly choose between a photo and a document
    media_type = random.choice(['photo', 'document'])
    
    # Generate a random media file name
    media_name = f"random_{media_type}.jpg" if media_type == 'photo' else f"random_{media_type}.pdf"
    
    # Send the media to the chat
    if media_type == 'photo':
        client(SendMediaRequest(chat_id, InputPeerUser(client.id, 0), InputMediaPhoto(open(media_name, 'rb')), 0))
    else:
        client(SendMediaRequest(chat_id, InputPeerUser(client.id, 0), InputMediaDocument(open(media_name, 'rb')), 0))

    # Clean up the media file after sending
    import os
    os.remove(media_name)