2
0
mirror of https://github.com/pyrogram/pyrogram synced 2025-08-28 21:07:59 +00:00

Make all send_* methods dealing with files aware of StopTransmission

This commit is contained in:
Dan 2019-01-11 14:13:23 +01:00
parent 2791600926
commit 4e02cd23a8
8 changed files with 524 additions and 492 deletions

View File

@ -45,7 +45,7 @@ class SendAnimation(BaseClient):
"pyrogram.ReplyKeyboardRemove", "pyrogram.ReplyKeyboardRemove",
"pyrogram.ForceReply"] = None, "pyrogram.ForceReply"] = None,
progress: callable = None, progress: callable = None,
progress_args: tuple = ()) -> "pyrogram.Message": progress_args: tuple = ()) -> Union["pyrogram.Message", None]:
"""Use this method to send animation files (animation or H.264/MPEG-4 AVC video without sound). """Use this method to send animation files (animation or H.264/MPEG-4 AVC video without sound).
Args: Args:
@ -119,6 +119,7 @@ class SendAnimation(BaseClient):
Returns: Returns:
On success, the sent :obj:`Message <pyrogram.Message>` is returned. On success, the sent :obj:`Message <pyrogram.Message>` is returned.
In case the upload is deliberately stopped with :meth:`stop_transmission`, None is returned instead.
Raises: Raises:
:class:`Error <pyrogram.Error>` in case of a Telegram RPC error. :class:`Error <pyrogram.Error>` in case of a Telegram RPC error.
@ -126,72 +127,75 @@ class SendAnimation(BaseClient):
file = None file = None
style = self.html if parse_mode.lower() == "html" else self.markdown style = self.html if parse_mode.lower() == "html" else self.markdown
if os.path.exists(animation): try:
thumb = None if thumb is None else self.save_file(thumb) if os.path.exists(animation):
file = self.save_file(animation, progress=progress, progress_args=progress_args) thumb = None if thumb is None else self.save_file(thumb)
media = types.InputMediaUploadedDocument( file = self.save_file(animation, progress=progress, progress_args=progress_args)
mime_type=mimetypes.types_map[".mp4"], media = types.InputMediaUploadedDocument(
file=file, mime_type=mimetypes.types_map[".mp4"],
thumb=thumb, file=file,
attributes=[ thumb=thumb,
types.DocumentAttributeVideo( attributes=[
supports_streaming=True, types.DocumentAttributeVideo(
duration=duration, supports_streaming=True,
w=width, duration=duration,
h=height w=width,
), h=height
types.DocumentAttributeFilename(os.path.basename(animation)), ),
types.DocumentAttributeAnimated() types.DocumentAttributeFilename(os.path.basename(animation)),
] types.DocumentAttributeAnimated()
) ]
elif animation.startswith("http"):
media = types.InputMediaDocumentExternal(
url=animation
)
else:
try:
decoded = utils.decode(animation)
fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
unpacked = struct.unpack(fmt, decoded)
except (AssertionError, binascii.Error, struct.error):
raise FileIdInvalid from None
else:
if unpacked[0] != 10:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
)
) )
elif animation.startswith("http"):
while True: media = types.InputMediaDocumentExternal(
try: url=animation
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
**style.parse(caption)
)
) )
except FilePartMissing as e:
self.save_file(animation, file_id=file.id, file_part=e.x)
else: else:
for i in r.updates: try:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)): decoded = utils.decode(animation)
return pyrogram.Message._parse( fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
self, i.message, unpacked = struct.unpack(fmt, decoded)
{i.id: i for i in r.users}, except (AssertionError, binascii.Error, struct.error):
{i.id: i for i in r.chats} raise FileIdInvalid from None
else:
if unpacked[0] != 10:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
) )
)
while True:
try:
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
**style.parse(caption)
)
)
except FilePartMissing as e:
self.save_file(animation, file_id=file.id, file_part=e.x)
else:
for i in r.updates:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)):
return pyrogram.Message._parse(
self, i.message,
{i.id: i for i in r.users},
{i.id: i for i in r.chats}
)
except BaseClient.StopTransmission:
return None

View File

@ -45,7 +45,7 @@ class SendAudio(BaseClient):
"pyrogram.ReplyKeyboardRemove", "pyrogram.ReplyKeyboardRemove",
"pyrogram.ForceReply"] = None, "pyrogram.ForceReply"] = None,
progress: callable = None, progress: callable = None,
progress_args: tuple = ()) -> "pyrogram.Message": progress_args: tuple = ()) -> Union["pyrogram.Message", None]:
"""Use this method to send audio files. """Use this method to send audio files.
For sending voice messages, use the :obj:`send_voice()` method instead. For sending voice messages, use the :obj:`send_voice()` method instead.
@ -121,6 +121,7 @@ class SendAudio(BaseClient):
Returns: Returns:
On success, the sent :obj:`Message <pyrogram.Message>` is returned. On success, the sent :obj:`Message <pyrogram.Message>` is returned.
In case the upload is deliberately stopped with :meth:`stop_transmission`, None is returned instead.
Raises: Raises:
:class:`Error <pyrogram.Error>` in case of a Telegram RPC error. :class:`Error <pyrogram.Error>` in case of a Telegram RPC error.
@ -128,70 +129,73 @@ class SendAudio(BaseClient):
file = None file = None
style = self.html if parse_mode.lower() == "html" else self.markdown style = self.html if parse_mode.lower() == "html" else self.markdown
if os.path.exists(audio): try:
thumb = None if thumb is None else self.save_file(thumb) if os.path.exists(audio):
file = self.save_file(audio, progress=progress, progress_args=progress_args) thumb = None if thumb is None else self.save_file(thumb)
media = types.InputMediaUploadedDocument( file = self.save_file(audio, progress=progress, progress_args=progress_args)
mime_type=mimetypes.types_map.get("." + audio.split(".")[-1], "audio/mpeg"), media = types.InputMediaUploadedDocument(
file=file, mime_type=mimetypes.types_map.get("." + audio.split(".")[-1], "audio/mpeg"),
thumb=thumb, file=file,
attributes=[ thumb=thumb,
types.DocumentAttributeAudio( attributes=[
duration=duration, types.DocumentAttributeAudio(
performer=performer, duration=duration,
title=title performer=performer,
), title=title
types.DocumentAttributeFilename(os.path.basename(audio)) ),
] types.DocumentAttributeFilename(os.path.basename(audio))
) ]
elif audio.startswith("http"):
media = types.InputMediaDocumentExternal(
url=audio
)
else:
try:
decoded = utils.decode(audio)
fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
unpacked = struct.unpack(fmt, decoded)
except (AssertionError, binascii.Error, struct.error):
raise FileIdInvalid from None
else:
if unpacked[0] != 9:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
)
) )
elif audio.startswith("http"):
while True: media = types.InputMediaDocumentExternal(
try: url=audio
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
**style.parse(caption)
)
) )
except FilePartMissing as e:
self.save_file(audio, file_id=file.id, file_part=e.x)
else: else:
for i in r.updates: try:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)): decoded = utils.decode(audio)
return pyrogram.Message._parse( fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
self, i.message, unpacked = struct.unpack(fmt, decoded)
{i.id: i for i in r.users}, except (AssertionError, binascii.Error, struct.error):
{i.id: i for i in r.chats} raise FileIdInvalid from None
else:
if unpacked[0] != 9:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
) )
)
while True:
try:
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
**style.parse(caption)
)
)
except FilePartMissing as e:
self.save_file(audio, file_id=file.id, file_part=e.x)
else:
for i in r.updates:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)):
return pyrogram.Message._parse(
self, i.message,
{i.id: i for i in r.users},
{i.id: i for i in r.chats}
)
except BaseClient.StopTransmission:
return None

View File

@ -42,7 +42,7 @@ class SendDocument(BaseClient):
"pyrogram.ReplyKeyboardRemove", "pyrogram.ReplyKeyboardRemove",
"pyrogram.ForceReply"] = None, "pyrogram.ForceReply"] = None,
progress: callable = None, progress: callable = None,
progress_args: tuple = ()) -> "pyrogram.Message": progress_args: tuple = ()) -> Union["pyrogram.Message", None]:
"""Use this method to send general files. """Use this method to send general files.
Args: Args:
@ -107,6 +107,7 @@ class SendDocument(BaseClient):
Returns: Returns:
On success, the sent :obj:`Message <pyrogram.Message>` is returned. On success, the sent :obj:`Message <pyrogram.Message>` is returned.
In case the upload is deliberately stopped with :meth:`stop_transmission`, None is returned instead.
Raises: Raises:
:class:`Error <pyrogram.Error>` in case of a Telegram RPC error. :class:`Error <pyrogram.Error>` in case of a Telegram RPC error.
@ -114,65 +115,68 @@ class SendDocument(BaseClient):
file = None file = None
style = self.html if parse_mode.lower() == "html" else self.markdown style = self.html if parse_mode.lower() == "html" else self.markdown
if os.path.exists(document): try:
thumb = None if thumb is None else self.save_file(thumb) if os.path.exists(document):
file = self.save_file(document, progress=progress, progress_args=progress_args) thumb = None if thumb is None else self.save_file(thumb)
media = types.InputMediaUploadedDocument( file = self.save_file(document, progress=progress, progress_args=progress_args)
mime_type=mimetypes.types_map.get("." + document.split(".")[-1], "text/plain"), media = types.InputMediaUploadedDocument(
file=file, mime_type=mimetypes.types_map.get("." + document.split(".")[-1], "text/plain"),
thumb=thumb, file=file,
attributes=[ thumb=thumb,
types.DocumentAttributeFilename(os.path.basename(document)) attributes=[
] types.DocumentAttributeFilename(os.path.basename(document))
) ]
elif document.startswith("http"):
media = types.InputMediaDocumentExternal(
url=document
)
else:
try:
decoded = utils.decode(document)
fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
unpacked = struct.unpack(fmt, decoded)
except (AssertionError, binascii.Error, struct.error):
raise FileIdInvalid from None
else:
if unpacked[0] not in (5, 10):
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
)
) )
elif document.startswith("http"):
while True: media = types.InputMediaDocumentExternal(
try: url=document
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
**style.parse(caption)
)
) )
except FilePartMissing as e:
self.save_file(document, file_id=file.id, file_part=e.x)
else: else:
for i in r.updates: try:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)): decoded = utils.decode(document)
return pyrogram.Message._parse( fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
self, i.message, unpacked = struct.unpack(fmt, decoded)
{i.id: i for i in r.users}, except (AssertionError, binascii.Error, struct.error):
{i.id: i for i in r.chats} raise FileIdInvalid from None
else:
if unpacked[0] not in (5, 10):
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
) )
)
while True:
try:
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
**style.parse(caption)
)
)
except FilePartMissing as e:
self.save_file(document, file_id=file.id, file_part=e.x)
else:
for i in r.updates:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)):
return pyrogram.Message._parse(
self, i.message,
{i.id: i for i in r.users},
{i.id: i for i in r.chats}
)
except BaseClient.StopTransmission:
return None

View File

@ -41,7 +41,7 @@ class SendPhoto(BaseClient):
"pyrogram.ReplyKeyboardRemove", "pyrogram.ReplyKeyboardRemove",
"pyrogram.ForceReply"] = None, "pyrogram.ForceReply"] = None,
progress: callable = None, progress: callable = None,
progress_args: tuple = ()) -> "pyrogram.Message": progress_args: tuple = ()) -> Union["pyrogram.Message", None]:
"""Use this method to send photos. """Use this method to send photos.
Args: Args:
@ -105,6 +105,7 @@ class SendPhoto(BaseClient):
Returns: Returns:
On success, the sent :obj:`Message <pyrogram.Message>` is returned. On success, the sent :obj:`Message <pyrogram.Message>` is returned.
In case the upload is deliberately stopped with :meth:`stop_transmission`, None is returned instead.
Raises: Raises:
:class:`Error <pyrogram.Error>` in case of a Telegram RPC error. :class:`Error <pyrogram.Error>` in case of a Telegram RPC error.
@ -112,62 +113,65 @@ class SendPhoto(BaseClient):
file = None file = None
style = self.html if parse_mode.lower() == "html" else self.markdown style = self.html if parse_mode.lower() == "html" else self.markdown
if os.path.exists(photo): try:
file = self.save_file(photo, progress=progress, progress_args=progress_args) if os.path.exists(photo):
media = types.InputMediaUploadedPhoto( file = self.save_file(photo, progress=progress, progress_args=progress_args)
file=file, media = types.InputMediaUploadedPhoto(
ttl_seconds=ttl_seconds file=file,
)
elif photo.startswith("http"):
media = types.InputMediaPhotoExternal(
url=photo,
ttl_seconds=ttl_seconds
)
else:
try:
decoded = utils.decode(photo)
fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
unpacked = struct.unpack(fmt, decoded)
except (AssertionError, binascii.Error, struct.error):
raise FileIdInvalid from None
else:
if unpacked[0] != 2:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaPhoto(
id=types.InputPhoto(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
),
ttl_seconds=ttl_seconds ttl_seconds=ttl_seconds
) )
elif photo.startswith("http"):
while True: media = types.InputMediaPhotoExternal(
try: url=photo,
r = self.send( ttl_seconds=ttl_seconds
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
**style.parse(caption)
)
) )
except FilePartMissing as e:
self.save_file(photo, file_id=file.id, file_part=e.x)
else: else:
for i in r.updates: try:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)): decoded = utils.decode(photo)
return pyrogram.Message._parse( fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
self, i.message, unpacked = struct.unpack(fmt, decoded)
{i.id: i for i in r.users}, except (AssertionError, binascii.Error, struct.error):
{i.id: i for i in r.chats} raise FileIdInvalid from None
else:
if unpacked[0] != 2:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaPhoto(
id=types.InputPhoto(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
),
ttl_seconds=ttl_seconds
)
while True:
try:
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
**style.parse(caption)
) )
)
except FilePartMissing as e:
self.save_file(photo, file_id=file.id, file_part=e.x)
else:
for i in r.updates:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)):
return pyrogram.Message._parse(
self, i.message,
{i.id: i for i in r.users},
{i.id: i for i in r.chats}
)
except BaseClient.StopTransmission:
return None

View File

@ -38,7 +38,7 @@ class SendSticker(BaseClient):
"pyrogram.ReplyKeyboardRemove", "pyrogram.ReplyKeyboardRemove",
"pyrogram.ForceReply"] = None, "pyrogram.ForceReply"] = None,
progress: callable = None, progress: callable = None,
progress_args: tuple = ()) -> "pyrogram.Message": progress_args: tuple = ()) -> Union["pyrogram.Message", None]:
"""Use this method to send .webp stickers. """Use this method to send .webp stickers.
Args: Args:
@ -89,69 +89,73 @@ class SendSticker(BaseClient):
Returns: Returns:
On success, the sent :obj:`Message <pyrogram.Message>` is returned. On success, the sent :obj:`Message <pyrogram.Message>` is returned.
In case the upload is deliberately stopped with :meth:`stop_transmission`, None is returned instead.
Raises: Raises:
:class:`Error <pyrogram.Error>` in case of a Telegram RPC error. :class:`Error <pyrogram.Error>` in case of a Telegram RPC error.
""" """
file = None file = None
if os.path.exists(sticker): try:
file = self.save_file(sticker, progress=progress, progress_args=progress_args) if os.path.exists(sticker):
media = types.InputMediaUploadedDocument( file = self.save_file(sticker, progress=progress, progress_args=progress_args)
mime_type="image/webp", media = types.InputMediaUploadedDocument(
file=file, mime_type="image/webp",
attributes=[ file=file,
types.DocumentAttributeFilename(os.path.basename(sticker)) attributes=[
] types.DocumentAttributeFilename(os.path.basename(sticker))
) ]
elif sticker.startswith("http"):
media = types.InputMediaDocumentExternal(
url=sticker
)
else:
try:
decoded = utils.decode(sticker)
fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
unpacked = struct.unpack(fmt, decoded)
except (AssertionError, binascii.Error, struct.error):
raise FileIdInvalid from None
else:
if unpacked[0] != 8:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
)
) )
elif sticker.startswith("http"):
while True: media = types.InputMediaDocumentExternal(
try: url=sticker
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
message=""
)
) )
except FilePartMissing as e:
self.save_file(sticker, file_id=file.id, file_part=e.x)
else: else:
for i in r.updates: try:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)): decoded = utils.decode(sticker)
return pyrogram.Message._parse( fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
self, i.message, unpacked = struct.unpack(fmt, decoded)
{i.id: i for i in r.users}, except (AssertionError, binascii.Error, struct.error):
{i.id: i for i in r.chats} raise FileIdInvalid from None
else:
if unpacked[0] != 8:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
) )
)
while True:
try:
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
message=""
)
)
except FilePartMissing as e:
self.save_file(sticker, file_id=file.id, file_part=e.x)
else:
for i in r.updates:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)):
return pyrogram.Message._parse(
self, i.message,
{i.id: i for i in r.users},
{i.id: i for i in r.chats}
)
except BaseClient.StopTransmission:
return None

View File

@ -46,7 +46,7 @@ class SendVideo(BaseClient):
"pyrogram.ReplyKeyboardRemove", "pyrogram.ReplyKeyboardRemove",
"pyrogram.ForceReply"] = None, "pyrogram.ForceReply"] = None,
progress: callable = None, progress: callable = None,
progress_args: tuple = ()) -> "pyrogram.Message": progress_args: tuple = ()) -> Union["pyrogram.Message", None]:
"""Use this method to send video files. """Use this method to send video files.
Args: Args:
@ -123,6 +123,7 @@ class SendVideo(BaseClient):
Returns: Returns:
On success, the sent :obj:`Message <pyrogram.Message>` is returned. On success, the sent :obj:`Message <pyrogram.Message>` is returned.
In case the upload is deliberately stopped with :meth:`stop_transmission`, None is returned instead.
Raises: Raises:
:class:`Error <pyrogram.Error>` in case of a Telegram RPC error. :class:`Error <pyrogram.Error>` in case of a Telegram RPC error.
@ -130,71 +131,74 @@ class SendVideo(BaseClient):
file = None file = None
style = self.html if parse_mode.lower() == "html" else self.markdown style = self.html if parse_mode.lower() == "html" else self.markdown
if os.path.exists(video): try:
thumb = None if thumb is None else self.save_file(thumb) if os.path.exists(video):
file = self.save_file(video, progress=progress, progress_args=progress_args) thumb = None if thumb is None else self.save_file(thumb)
media = types.InputMediaUploadedDocument( file = self.save_file(video, progress=progress, progress_args=progress_args)
mime_type=mimetypes.types_map[".mp4"], media = types.InputMediaUploadedDocument(
file=file, mime_type=mimetypes.types_map[".mp4"],
thumb=thumb, file=file,
attributes=[ thumb=thumb,
types.DocumentAttributeVideo( attributes=[
supports_streaming=supports_streaming or None, types.DocumentAttributeVideo(
duration=duration, supports_streaming=supports_streaming or None,
w=width, duration=duration,
h=height w=width,
), h=height
types.DocumentAttributeFilename(os.path.basename(video)) ),
] types.DocumentAttributeFilename(os.path.basename(video))
) ]
elif video.startswith("http"):
media = types.InputMediaDocumentExternal(
url=video
)
else:
try:
decoded = utils.decode(video)
fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
unpacked = struct.unpack(fmt, decoded)
except (AssertionError, binascii.Error, struct.error):
raise FileIdInvalid from None
else:
if unpacked[0] != 4:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
)
) )
elif video.startswith("http"):
while True: media = types.InputMediaDocumentExternal(
try: url=video
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
**style.parse(caption)
)
) )
except FilePartMissing as e:
self.save_file(video, file_id=file.id, file_part=e.x)
else: else:
for i in r.updates: try:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)): decoded = utils.decode(video)
return pyrogram.Message._parse( fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
self, i.message, unpacked = struct.unpack(fmt, decoded)
{i.id: i for i in r.users}, except (AssertionError, binascii.Error, struct.error):
{i.id: i for i in r.chats} raise FileIdInvalid from None
else:
if unpacked[0] != 4:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
) )
)
while True:
try:
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
**style.parse(caption)
)
)
except FilePartMissing as e:
self.save_file(video, file_id=file.id, file_part=e.x)
else:
for i in r.updates:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)):
return pyrogram.Message._parse(
self, i.message,
{i.id: i for i in r.users},
{i.id: i for i in r.chats}
)
except BaseClient.StopTransmission:
return None

View File

@ -42,7 +42,7 @@ class SendVideoNote(BaseClient):
"pyrogram.ReplyKeyboardRemove", "pyrogram.ReplyKeyboardRemove",
"pyrogram.ForceReply"] = None, "pyrogram.ForceReply"] = None,
progress: callable = None, progress: callable = None,
progress_args: tuple = ()) -> "pyrogram.Message": progress_args: tuple = ()) -> Union["pyrogram.Message", None]:
"""Use this method to send video messages. """Use this method to send video messages.
Args: Args:
@ -105,72 +105,76 @@ class SendVideoNote(BaseClient):
Returns: Returns:
On success, the sent :obj:`Message <pyrogram.Message>` is returned. On success, the sent :obj:`Message <pyrogram.Message>` is returned.
In case the upload is deliberately stopped with :meth:`stop_transmission`, None is returned instead.
Raises: Raises:
:class:`Error <pyrogram.Error>` in case of a Telegram RPC error. :class:`Error <pyrogram.Error>` in case of a Telegram RPC error.
""" """
file = None file = None
if os.path.exists(video_note): try:
thumb = None if thumb is None else self.save_file(thumb) if os.path.exists(video_note):
file = self.save_file(video_note, progress=progress, progress_args=progress_args) thumb = None if thumb is None else self.save_file(thumb)
media = types.InputMediaUploadedDocument( file = self.save_file(video_note, progress=progress, progress_args=progress_args)
mime_type=mimetypes.types_map[".mp4"], media = types.InputMediaUploadedDocument(
file=file, mime_type=mimetypes.types_map[".mp4"],
thumb=thumb, file=file,
attributes=[ thumb=thumb,
types.DocumentAttributeVideo( attributes=[
round_message=True, types.DocumentAttributeVideo(
duration=duration, round_message=True,
w=length, duration=duration,
h=length w=length,
) h=length
]
)
else:
try:
decoded = utils.decode(video_note)
fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
unpacked = struct.unpack(fmt, decoded)
except (AssertionError, binascii.Error, struct.error):
raise FileIdInvalid from None
else:
if unpacked[0] != 13:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
)
)
while True:
try:
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
message=""
)
)
except FilePartMissing as e:
self.save_file(video_note, file_id=file.id, file_part=e.x)
else:
for i in r.updates:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)):
return pyrogram.Message._parse(
self, i.message,
{i.id: i for i in r.users},
{i.id: i for i in r.chats}
) )
]
)
else:
try:
decoded = utils.decode(video_note)
fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
unpacked = struct.unpack(fmt, decoded)
except (AssertionError, binascii.Error, struct.error):
raise FileIdInvalid from None
else:
if unpacked[0] != 13:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
)
)
while True:
try:
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
message=""
)
)
except FilePartMissing as e:
self.save_file(video_note, file_id=file.id, file_part=e.x)
else:
for i in r.updates:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)):
return pyrogram.Message._parse(
self, i.message,
{i.id: i for i in r.users},
{i.id: i for i in r.chats}
)
except BaseClient.StopTransmission:
return None

View File

@ -42,7 +42,7 @@ class SendVoice(BaseClient):
"pyrogram.ReplyKeyboardRemove", "pyrogram.ReplyKeyboardRemove",
"pyrogram.ForceReply"] = None, "pyrogram.ForceReply"] = None,
progress: callable = None, progress: callable = None,
progress_args: tuple = ()) -> "pyrogram.Message": progress_args: tuple = ()) -> Union["pyrogram.Message", None]:
"""Use this method to send audio files. """Use this method to send audio files.
Args: Args:
@ -104,6 +104,7 @@ class SendVoice(BaseClient):
Returns: Returns:
On success, the sent :obj:`Message <pyrogram.Message>` is returned. On success, the sent :obj:`Message <pyrogram.Message>` is returned.
In case the upload is deliberately stopped with :meth:`stop_transmission`, None is returned instead.
Raises: Raises:
:class:`Error <pyrogram.Error>` in case of a Telegram RPC error. :class:`Error <pyrogram.Error>` in case of a Telegram RPC error.
@ -111,66 +112,69 @@ class SendVoice(BaseClient):
file = None file = None
style = self.html if parse_mode.lower() == "html" else self.markdown style = self.html if parse_mode.lower() == "html" else self.markdown
if os.path.exists(voice): try:
file = self.save_file(voice, progress=progress, progress_args=progress_args) if os.path.exists(voice):
media = types.InputMediaUploadedDocument( file = self.save_file(voice, progress=progress, progress_args=progress_args)
mime_type=mimetypes.types_map.get("." + voice.split(".")[-1], "audio/mpeg"), media = types.InputMediaUploadedDocument(
file=file, mime_type=mimetypes.types_map.get("." + voice.split(".")[-1], "audio/mpeg"),
attributes=[ file=file,
types.DocumentAttributeAudio( attributes=[
voice=True, types.DocumentAttributeAudio(
duration=duration voice=True,
) duration=duration
]
)
elif voice.startswith("http"):
media = types.InputMediaDocumentExternal(
url=voice
)
else:
try:
decoded = utils.decode(voice)
fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
unpacked = struct.unpack(fmt, decoded)
except (AssertionError, binascii.Error, struct.error):
raise FileIdInvalid from None
else:
if unpacked[0] != 3:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
)
)
while True:
try:
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
**style.parse(caption)
)
)
except FilePartMissing as e:
self.save_file(voice, file_id=file.id, file_part=e.x)
else:
for i in r.updates:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)):
return pyrogram.Message._parse(
self, i.message,
{i.id: i for i in r.users},
{i.id: i for i in r.chats}
) )
]
)
elif voice.startswith("http"):
media = types.InputMediaDocumentExternal(
url=voice
)
else:
try:
decoded = utils.decode(voice)
fmt = "<iiqqqqi" if len(decoded) > 24 else "<iiqq"
unpacked = struct.unpack(fmt, decoded)
except (AssertionError, binascii.Error, struct.error):
raise FileIdInvalid from None
else:
if unpacked[0] != 3:
media_type = BaseClient.MEDIA_TYPE_ID.get(unpacked[0], None)
if media_type:
raise FileIdInvalid("The file_id belongs to a {}".format(media_type))
else:
raise FileIdInvalid("Unknown media type: {}".format(unpacked[0]))
media = types.InputMediaDocument(
id=types.InputDocument(
id=unpacked[2],
access_hash=unpacked[3],
file_reference=b""
)
)
while True:
try:
r = self.send(
functions.messages.SendMedia(
peer=self.resolve_peer(chat_id),
media=media,
silent=disable_notification or None,
reply_to_msg_id=reply_to_message_id,
random_id=self.rnd_id(),
reply_markup=reply_markup.write() if reply_markup else None,
**style.parse(caption)
)
)
except FilePartMissing as e:
self.save_file(voice, file_id=file.id, file_part=e.x)
else:
for i in r.updates:
if isinstance(i, (types.UpdateNewMessage, types.UpdateNewChannelMessage)):
return pyrogram.Message._parse(
self, i.message,
{i.id: i for i in r.users},
{i.id: i for i in r.chats}
)
except BaseClient.StopTransmission:
return None