Telethon send image with spoiler

Question:

How can I send image with spoiler in telethon?
I use telethon-1.27.0.

This is the code I’m using:
client.send_message(user, file="/something.png")

I tried to use has_spoiler=True but got an error message

send_message() got an unexpected keyword argument ‘has_spoiler’ or ‘spoiler’ and etc.

in sendmessage i found that parameter – Message sent. Return Value Message(id=123, peer_id=PeerUser(user_id=123), date=datetime.datetime(2023, 2, 5, 23, 11, 49, tzinfo=datetime.timezone.utc), message=’123′, out=True, mentioned=False, media_unread=False, silent=False, post=False, from_scheduled=False, legacy=False, edit_hide=False, pinned=False, noforwards=False, from_id=None, fwd_from=None, via_bot_id=None, reply_to=None, media=MessageMediaPhoto(spoiler=False, photo=Photo(id=5982148115249082446

Asked By: s0rry

||

Answers:

The documentation explains how to send spoilers.

https://docs.telethon.dev/en/stable/examples/working-with-messages.html#sending-spoilers-hidden-text

The current markdown and HTML parsers do not offer a way to send spoilers yet. You need to use MessageEntitySpoiler so that parts of the message text are shown under a spoiler.

The simplest way to do this is to modify the builtin parsers to support sending these new message entities with the features they already provide.

The cited
recipe
shows how to define parse / unparse methods in class CustomMarkdown.
When it sees [hidden text](spoiler) and finds a literal
match on "spoiler" it edits in a MessageEntitySpoiler
object that will produce the desired effect.

Answered By: J_H

You will need to use Telethon v1.27 or greater, and then manually construct the correct media (in this case, InputMediaUploadedPhoto):

from telethon import TelegramClient, types

...

file = ...  # path to your file 'photo.png' or file object

uploaded = await client.upload_file(file)
await client.send_file(chat, types.InputMediaUploadedPhoto(
    uploaded,
    spoiler=True,
))
Answered By: Lonami
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.