- Better Downloads: Add Progress Args to urldl for better UI

- File Deletion Safety: Before deleting the file, the code checks if the file exists to avoid any FileNotFoundError exceptions.
This commit is contained in:
Abhi
2024-04-20 16:04:37 +00:00
committed by GitHub
parent 80642a1fa3
commit 2de0e32199
5 changed files with 55 additions and 27 deletions

View File

@@ -111,7 +111,8 @@ async def rmbg(client: Client, message: Message):
allow_redirects=True, allow_redirects=True,
stream=True, stream=True,
) )
os.remove(cool) if os.path.exists(cool):
os.remove(cool)
output_file_name = r output_file_name = r
contentType = output_file_name.headers.get("content-type") contentType = output_file_name.headers.get("content-type")
if "image" in contentType: if "image" in contentType:
@@ -126,7 +127,8 @@ async def rmbg(client: Client, message: Message):
await pablo.edit( await pablo.edit(
"<code>Removed image's Background in {} seconds, powered by </code> <b>@moonuserbot</b>".format(ms) "<code>Removed image's Background in {} seconds, powered by </code> <b>@moonuserbot</b>".format(ms)
) )
os.remove("BG_rem.png") if os.path.exists("BG_rem.png"):
os.remove("BG_rem.png")
else: else:
await pablo.edit( await pablo.edit(
"ReMove.BG API returned Errors. Please report to @moonub_chat\n`{}".format( "ReMove.BG API returned Errors. Please report to @moonub_chat\n`{}".format(
@@ -159,7 +161,8 @@ async def rembg(client: Client, message: Message):
except Exception as e: except Exception as e:
await message.reply_text(f"An error occurred: {format_exc(e)}") await message.reply_text(f"An error occurred: {format_exc(e)}")
finally: finally:
os.remove(photo_data) if os.path.exists(photo_data):
os.remove(photo_data)
modules_help["removebg"] = { modules_help["removebg"] = {

View File

@@ -73,7 +73,8 @@ async def kang(client: Client, message: types.Message):
return return
resized = resize_image(path) resized = resize_image(path)
os.remove(path) if os.path.exists(path):
os.remove(path)
await interact_with(await client.send_document("@stickers", resized, parse_mode=enums.ParseMode.MARKDOWN)) await interact_with(await client.send_document("@stickers", resized, parse_mode=enums.ParseMode.MARKDOWN))
response = await interact_with(await client.send_message("@stickers", emoji, parse_mode=enums.ParseMode.MARKDOWN)) response = await interact_with(await client.send_message("@stickers", emoji, parse_mode=enums.ParseMode.MARKDOWN))
@@ -99,7 +100,8 @@ async def stick2png(client: Client, message: types.Message):
path = await message.reply_to_message.download() path = await message.reply_to_message.download()
with open(path, "rb") as f: with open(path, "rb") as f:
content = f.read() content = f.read()
os.remove(path) if os.path.exists(path):
os.remove(path)
file_io = BytesIO(content) file_io = BytesIO(content)
file_io.name = "sticker.png" file_io.name = "sticker.png"
@@ -120,7 +122,8 @@ async def resize_cmd(client: Client, message: types.Message):
path = await message.reply_to_message.download() path = await message.reply_to_message.download()
resized = resize_image(path) resized = resize_image(path)
resized.name = "image.png" resized.name = "image.png"
os.remove(path) if os.path.exists(path):
os.remove(path)
await client.send_document(message.chat.id, resized, parse_mode=enums.ParseMode.MARKDOWN) await client.send_document(message.chat.id, resized, parse_mode=enums.ParseMode.MARKDOWN)
except Exception as e: except Exception as e:

View File

@@ -62,7 +62,8 @@ async def uplr(client: Client, message: Message):
except Exception as e: except Exception as e:
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML) await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
finally: finally:
os.remove(link) if os.path.exists(link):
os.remove(link)
modules_help["uplud"] = { modules_help["uplud"] = {
"upl": f"[filepath]/[reply to path]*", "upl": f"[filepath]/[reply to path]*",

View File

@@ -14,15 +14,16 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>. # along with this program. If not, see <https://www.gnu.org/licenses/>.
import os import os
import requests
import time
import traceback
import urllib3 import urllib3
from pyrogram import Client, filters, enums from pyrogram import Client, filters, enums
from pyrogram.types import Message from pyrogram.types import Message
import requests
from utils.misc import modules_help, prefix from utils.misc import modules_help, prefix
from utils.scripts import format_exc from utils.scripts import format_exc, progress, edit_or_reply
from io import BytesIO from io import BytesIO
import requests
from utils.config import apiflash_key from utils.config import apiflash_key
@@ -53,8 +54,6 @@ async def short(_, message: Message):
await message.edit(r.data.decode().replace("https://", "<b>Shortened Url:</b>"), disable_web_page_preview=True, parse_mode=enums.ParseMode.HTML) await message.edit(r.data.decode().replace("https://", "<b>Shortened Url:</b>"), disable_web_page_preview=True, parse_mode=enums.ParseMode.HTML)
@Client.on_message(filters.command("urldl", prefix) & filters.me) @Client.on_message(filters.command("urldl", prefix) & filters.me)
async def urldl(client: Client, message: Message): async def urldl(client: Client, message: Message):
if len(message.command) > 1: if len(message.command) > 1:
@@ -72,21 +71,33 @@ async def urldl(client: Client, message: Message):
file_name = "downloads/" + link.split("/")[-1] file_name = "downloads/" + link.split("/")[-1]
try: try:
resp = requests.get(link) resp = requests.get(link, stream=True)
resp.raise_for_status() resp.raise_for_status()
# Get the total file size
total_size = int(resp.headers.get('content-length', 0))
with open(file_name, "wb") as f: with open(file_name, "wb") as f:
downloaded = 0
chunk_count = 0
update_frequency = 800
for chunk in resp.iter_content(chunk_size=8192): for chunk in resp.iter_content(chunk_size=8192):
f.write(chunk) f.write(chunk)
downloaded += len(chunk)
chunk_count += 1
progress_dl = (downloaded / total_size) * 100
if chunk_count % update_frequency == 0:
await message.edit_text(f"<b>Downloading...</b>\nProgress: {progress_dl:.2f}%")
await message.edit("<b>Uploading...</b>", parse_mode=enums.ParseMode.HTML) ms_ = await message.edit("<b>Uploading...</b>", parse_mode=enums.ParseMode.HTML)
await client.send_document(message.chat.id, file_name, parse_mode=enums.ParseMode.HTML) c_time = time.time()
await client.send_document(message.chat.id, file_name, progress=progress, progress_args=(ms_, c_time, '`Uploading...`'), parse_mode=enums.ParseMode.MARKDOWN)
await message.delete() await message.delete()
except Exception as e: except Exception as e:
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML) await message.edit(f"<b>Error:</b> {traceback.format_exc(e)}", parse_mode=enums.ParseMode.HTML)
finally: finally:
os.remove(file_name) if os.path.exists(file_name):
os.remove(file_name)
@Client.on_message(filters.command("upload", prefix) & filters.me) @Client.on_message(filters.command("upload", prefix) & filters.me)
async def upload_cmd(_, message: Message): async def upload_cmd(_, message: Message):
@@ -96,20 +107,28 @@ async def upload_cmd(_, message: Message):
min_file_age = 31 min_file_age = 31
max_file_age = 180 max_file_age = 180
await message.edit("<b>Downloading...</b>", parse_mode=enums.ParseMode.HTML) ms_ = await message.edit("`Downloading...`", parse_mode=enums.ParseMode.MARKDOWN)
c_time = time.time()
try: try:
file_name = await message.download() file_name = await message.download(
progress=progress,
progress_args=(ms_, c_time, '`Downloading...`')
)
except ValueError: except ValueError:
try: try:
file_name = await message.reply_to_message.download() file_name = await message.reply_to_message.download(
progress=progress,
progress_args=(ms_, c_time, '`Downloading...`')
)
except ValueError: except ValueError:
await message.edit("<b>File to upload not found</b>", parse_mode=enums.ParseMode.HTML) await message.edit("<b>File to upload not found</b>", parse_mode=enums.ParseMode.HTML)
return return
if os.path.getsize(file_name) > max_size: if os.path.getsize(file_name) > max_size:
await message.edit(f"<b>Files longer than {max_size_mb}MB isn't supported</b>", parse_mode=enums.ParseMode.HTML) await message.edit(f"<b>Files longer than {max_size_mb}MB isn't supported</b>", parse_mode=enums.ParseMode.HTML)
os.remove(file_name) if os.path.exists(file_name):
os.remove(file_name)
return return
await message.edit("<b>Uploading...</b>", parse_mode=enums.ParseMode.HTML) await message.edit("<b>Uploading...</b>", parse_mode=enums.ParseMode.HTML)
@@ -135,8 +154,8 @@ async def upload_cmd(_, message: Message):
else: else:
await message.edit(f"<b>API returned an error!\n" f"{response.text}\n Not allowed</b>", parse_mode=enums.ParseMode.HTML) await message.edit(f"<b>API returned an error!\n" f"{response.text}\n Not allowed</b>", parse_mode=enums.ParseMode.HTML)
print(response.text) print(response.text)
if os.path.exists(file_name):
os.remove(file_name) os.remove(file_name)

View File

@@ -14,7 +14,7 @@ from pyrogram import Client, filters, enums
from pyrogram.types import Message from pyrogram.types import Message
from utils.misc import modules_help, prefix from utils.misc import modules_help, prefix
from utils.scripts import edit_or_reply, format_exc, time_formatter, humanbytes, edit_or_send_as_file, get_text, progress from utils.scripts import edit_or_reply, format_exc, progress
from utils.config import vt_key as vak from utils.config import vt_key as vak
@@ -48,7 +48,8 @@ async def scan_my_file(client, message):
except Exception as e: except Exception as e:
return await ms_.edit(format_exc(e)) return await ms_.edit(format_exc(e))
await ms_.edit(f"<b><u>Scanned {message.reply_to_message.document.file_name}</b></u>. <b>You Can Visit :</b> <a href=\"https://www.virustotal.com/gui/file/{md5}\">Here</a> <b>In 5-10 Min To See File Report</b>") await ms_.edit(f"<b><u>Scanned {message.reply_to_message.document.file_name}</b></u>. <b>You Can Visit :</b> <a href=\"https://www.virustotal.com/gui/file/{md5}\">Here</a> <b>In 5-10 Min To See File Report</b>")
os.remove(downloaded_file_name) if os.path.exists(downloaded_file_name):
os.remove(downloaded_file_name)
@Client.on_message(filters.command("vtl", prefix) & filters.me) @Client.on_message(filters.command("vtl", prefix) & filters.me)
async def scan_my_large_file(client, message): async def scan_my_large_file(client, message):
@@ -119,7 +120,8 @@ async def scan_my_large_file(client, message):
except Exception as e: except Exception as e:
return await ms_.edit(format_exc(e)) return await ms_.edit(format_exc(e))
await ms_.edit(f"<b><u>Scanned {message.reply_to_message.document.file_name}</b></u>. <b>You Can Visit :</b> <a href=\"https://www.virustotal.com/gui/file/{md5}\">Here</a> <b>In 5-10 Min To See File Report</b>") await ms_.edit(f"<b><u>Scanned {message.reply_to_message.document.file_name}</b></u>. <b>You Can Visit :</b> <a href=\"https://www.virustotal.com/gui/file/{md5}\">Here</a> <b>In 5-10 Min To See File Report</b>")
os.remove(downloaded_file_name) if os.path.exists(downloaded_file_name):
os.remove(downloaded_file_name)
modules_help["virustotal"] = { modules_help["virustotal"] = {
"vt [reply to file]*": "Scan for viruses on Virus Total (for lower file size <32MB)", "vt [reply to file]*": "Scan for viruses on Virus Total (for lower file size <32MB)",