Sending Random Media Messages to Telegram Chats

  • Share this:

Code introduction


This code defines a function to send random media messages (photo or document) to a Telegram chat. The function takes a chat object, a file path of the media, and an optional reply message object as parameters.


Technology Stack : Telethon

Code Type : The type of code

Code Difficulty :


                
                    
def send_random_media_message(chat, media, reply=None):
    from telethon.tl.functions.messages import SendMediaRequest
    from telethon.tl.types import InputMediaPhoto, InputMediaDocument

    # Determine the type of media and create the appropriate InputMedia object
    if media.get('type') == 'photo':
        media_obj = InputMediaPhoto(media['file'])
    elif media.get('type') == 'document':
        media_obj = InputMediaDocument(media['file'])
    else:
        raise ValueError("Unsupported media type")

    # Send the media message to the chat
    chat.send_message(reply, SendMediaRequest(chat, media_obj))                
              
Tags: