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.text or message.caption).markdown.split(' ', 1)[1:]
if media:
media = os.path.expanduser(media[0])
else:
media = message.document media = message.document
if not media and not getattr(message.reply_to_message, 'empty', True): if not media and not getattr(message.reply_to_message, 'empty', True):
media = message.reply_to_message.document media = message.reply_to_message.document
if not media: if not media:
await message.reply_text('Document required') await message.reply_text('Document or local file path required')
return return
done = False done = False
with tempfile.NamedTemporaryFile() as file: reply = rfile = None
try:
if not isinstance(media, str):
rfile = tempfile.NamedTemporaryFile()
reply = await message.reply_text('Downloading...') reply = await message.reply_text('Downloading...')
await client.download_media(media, file_name=file.name, progress=progress_callback, progress_args=(reply, 'Downloading...', False)) await client.download_media(media, file_name=rfile.name, progress=progress_callback, progress_args=(reply, 'Downloading...', False))
with open(file.name) as nfile: 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''')