You can download this code by clicking the button below.
This code is now available for download.
This code defines a function to fetch a random number of media messages from a specified Telegram chat. The function uses the Telethon library to send network requests, get historical messages, and filter out media messages.
Technology Stack : Telethon library
Code Type : The type of code
Code Difficulty : Advanced
def fetch_random_media_messages(chat, limit=10):
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.tl.types import InputPeerUser, InputPeerChat
from telethon.tl.functions.users import GetUsersRequest
# Determine if the chat is a user or a group chat
if isinstance(chat, str):
peer = InputPeerUser(int(chat))
else:
peer = InputPeerChat(chat)
# Fetch the history of messages
async def fetch_history():
async for message in client.iter_messages(peer, limit=limit):
yield message
# Convert the generator to a list
return list(fetch_history())