Add support for local files in .cat

This commit is contained in:
blank X 2020-12-03 17:57:25 +07:00
parent eebaeef2f5
commit 5727eaea20
1 changed files with 29 additions and 14 deletions

View File

@ -1,3 +1,4 @@
import os
import html import html
import tempfile import tempfile
from pyrogram import Client, filters from pyrogram import Client, filters
@ -7,26 +8,40 @@ from .. import config, help_dict, log_errors, session, progress_callback, public
@log_errors @log_errors
@public_log_errors @public_log_errors
async def cat(client, message): async def cat(client, message):
media = message.document media = (message.text or message.caption).markdown.split(' ', 1)[1:]
if not media and not getattr(message.reply_to_message, 'empty', True): if media:
media = message.reply_to_message.document media = os.path.expanduser(media[0])
if not media: else:
await message.reply_text('Document required') media = message.document
return if not media and not getattr(message.reply_to_message, 'empty', True):
media = message.reply_to_message.document
if not media:
await message.reply_text('Document or local file path required')
return
done = False done = False
with tempfile.NamedTemporaryFile() as file: reply = rfile = None
reply = await message.reply_text('Downloading...') try:
await client.download_media(media, file_name=file.name, progress=progress_callback, progress_args=(reply, 'Downloading...', False)) if not isinstance(media, str):
with open(file.name) as nfile: rfile = tempfile.NamedTemporaryFile()
reply = await message.reply_text('Downloading...')
await client.download_media(media, file_name=rfile.name, progress=progress_callback, progress_args=(reply, 'Downloading...', False))
media = rfile.name
with open(media, 'rb') as file:
while True: while True:
chunk = nfile.read(4096) chunk = file.read(4096)
if not chunk: if not chunk:
break break
chunk = f'<code>{html.escape(chunk)}</code>' if not chunk.strip():
continue
chunk = f'<code>{html.escape(chunk.decode())}</code>'
if done: if done:
await message.reply_text(chunk, quote=False) await message.reply_text(chunk, quote=False)
else: else:
await reply.edit_text(chunk) await getattr(reply, 'edit_text', message.reply_text)(chunk)
done = True done = True
finally:
if rfile:
rfile.close()
help_dict['cat'] = ('cat', '{prefix}cat <i>(as caption of text file or reply)</i> - Outputs file\'s text to Telegram') help_dict['cat'] = ('cat', '''{prefix}cat <i>(as caption of text file or reply)</i> - Outputs file's text to Telegram
{prefix}cat <i>&lt;path to local file&gt;</i> - Outputs file's text to Telegram''')