Retrieve Recent Telegram Chat Message Using Telethon

  • Share this:

Code introduction


This function uses the Telethon library to retrieve the most recent message from a specified Telegram chat


Technology Stack : Telethon, Telegram

Code Type : Function

Code Difficulty : Intermediate


                
                    
def get_random_chat_message(chat_id, bot_token):
    from telethon import TelegramClient, errors
    from telethon.tl.functions.messages import GetHistoryRequest
    from telethon.tl.types import InputPeerUser

    api_id = '123456'  # Replace with your API ID
    api_hash = 'abcdef'  # Replace with your API Hash
    phone_number = '1234567890'  # Replace with your phone number

    client = TelegramClient('session_name', api_id, api_hash)
    client.start(phone_number)

    try:
        with client:
            messages = client(GetHistoryRequest(chat_id, limit=1, add_stickers=True))
            message = messages.messages[0]
            return message.text
    except errors.RPCError as e:
        return f"An error occurred: {e}"
    finally:
        client.stop()