You can download this code by clicking the button below.
This code is now available for download.
This function uses the Telethon library to send a random message to a randomly selected user in a chat.
Technology Stack : Telethon
Code Type : Function
Code Difficulty : Intermediate
def send_random_message(session, chat_id):
from telethon.tl.functions.messages import SendMessageRequest
from telethon.tl.types import InputPeerUser
import random
# Randomly select a user from the chat
chat = session.get_entity(chat_id)
users = chat.users
selected_user = random.choice(list(users))
# Create an InputPeerUser object for the selected user
input PeerUser = InputPeerUser(selected_user.id, selected_user.access_hash)
# Send a random message to the selected user
message = f"Hello {selected_user.first_name}! This is a random message."
session.send_message(request=SendMessageRequest(input PeerUser, message))