Send Media by File Extension with Telethon

  • Share this:

Code introduction


This function uses the Telethon library to send a random type of media file (such as image, PDF, Word, etc.) to a specified chat. It determines the file type based on the file extension and creates the corresponding input media object.


Technology Stack : Telethon

Code Type : The type of code

Code Difficulty : Advanced


                
                    
def send_random_media_message(chat, file_path):
    from telethon.tl.functions.messages import SendMediaRequest
    from telethon.tl.types import InputPeerUser, InputMediaPhoto, InputMediaDocument

    # Check the file extension to determine the type of media to send
    file_extension = file_path.split('.')[-1].lower()
    
    # Create an input media object based on the file type
    if file_extension == 'jpg' or file_extension == 'jpeg':
        media = InputMediaPhoto(InputPeerUser(chat.id), open(file_path, 'rb'))
    elif file_extension in ['pdf', 'docx', 'txt']:
        media = InputMediaDocument(InputPeerUser(chat.id), open(file_path, 'rb'))
    else:
        raise ValueError("Unsupported file type")

    # Send the media to the chat
    chat.send_message(f"Sending a {file_extension} file...", requests=[SendMediaRequest(chat.to_id, [media])])                
              
Tags: