From 013c211f1460099b334919c348a1a418631235b2 Mon Sep 17 00:00:00 2001 From: levina <82658782+levina-lab@users.noreply.github.com> Date: Sat, 9 Oct 2021 22:38:28 +0700 Subject: [PATCH] some fixes --- bot/song.py | 110 ++++++++++++++++++++++++---------------------------- 1 file changed, 51 insertions(+), 59 deletions(-) diff --git a/bot/song.py b/bot/song.py index 1ce1237..519e312 100644 --- a/bot/song.py +++ b/bot/song.py @@ -1,31 +1,38 @@ -# Copyright (C) 2021 By VeezMusicProject - from __future__ import unicode_literals import asyncio import math import os import time -import wget from random import randint from urllib.parse import urlparse import aiofiles import aiohttp -import requests -import youtube_dl -from yt_dlp import YoutubeDL +import wget +import yt_dlp from pyrogram import Client, filters from pyrogram.errors import FloodWait, MessageNotModified from pyrogram.types import Message from youtube_search import YoutubeSearch +from yt_dlp import YoutubeDL -from config import Veez -from helpers.filters import command +from config import BOT_USERNAME as bn from helpers.decorators import humanbytes +from helpers.filters import command -@Client.on_message(command(["song", f"song@{Veez.BOT_USERNAME}"]) & ~filters.channel) +ydl_opts = { + 'format':'best', + 'keepvideo':True, + 'prefer_ffmpeg':False, + 'geo_bypass':True, + 'outtmpl':'%(title)s.%(ext)s', + 'quite':True +} + + +@Client.on_message(command(["song", f"song@{bn}"]) & ~filters.edited) def song(_, message): query = " ".join(message.command[1:]) m = message.reply("🔎 finding song...") @@ -46,11 +53,11 @@ def song(_, message): return m.edit("📥 downloading...") try: - with youtube_dl.YoutubeDL(ydl_ops) as ydl: + with yt_dlp.YoutubeDL(ydl_ops) as ydl: info_dict = ydl.extract_info(link, download=False) audio_file = ydl.prepare_filename(info_dict) ydl.process_info(info_dict) - rep = f"**🎧 By @{Veez.BOT_USERNAME}**" + rep = f"**🎧 Uploader @{bn}**" secmul, dur, dur_arr = 1, 0, duration.split(":") for i in range(len(dur_arr) - 1, -1, -1): dur += int(float(dur_arr[i])) * secmul @@ -65,7 +72,7 @@ def song(_, message): ) m.delete() except Exception as e: - m.edit("❌ error, wait for dev to fix") + m.edit("❌ error, wait for bot owner to fix") print(e) try: @@ -79,12 +86,12 @@ def get_text(message: Message) -> [None, str]: text_to_return = message.text if message.text is None: return None - if " " in text_to_return: - try: - return message.text.split(None, 1)[1] - except IndexError: - return None - else: + if " " not in text_to_return: + return None + + try: + return message.text.split(None, 1)[1] + except IndexError: return None @@ -100,10 +107,11 @@ async def progress(current, total, message, start, type_of_ps, file_name=None): time_to_completion = round((total - current) / speed) * 1000 estimated_total_time = elapsed_time + time_to_completion progress_str = "{0}{1} {2}%\n".format( - "".join(["🔴" for _ in range(math.floor(percentage / 10))]), - "".join(["🔘" for _ in range(10 - math.floor(percentage / 10))]), + "".join("🔴" for _ in range(math.floor(percentage / 10))), + "".join("🔘" for _ in range(10 - math.floor(percentage / 10))), round(percentage, 2), ) + tmp = progress_str + "{0} of {1}\nETA: {2}".format( humanbytes(current), humanbytes(total), time_formatter(estimated_total_time) ) @@ -126,15 +134,12 @@ async def progress(current, total, message, start, type_of_ps, file_name=None): def get_user(message: Message, text: str) -> [int, str, None]: - if text is None: - asplit = None - else: - asplit = text.split(" ", 1) + asplit = None if text is None else text.split(" ", 1) user_s = None reason_ = None if message.reply_to_message: user_s = message.reply_to_message.from_user.id - reason_ = text if text else None + reason_ = text or None elif asplit is None: return None, None elif len(asplit[0]) > 0: @@ -152,10 +157,7 @@ def get_readable_time(seconds: int) -> str: while count < 4: count += 1 - if count < 3: - remainder, result = divmod(seconds, 60) - else: - remainder, result = divmod(seconds, 24) + remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24) if seconds == 0 and remainder == 0: break time_list.append(int(result)) @@ -178,28 +180,15 @@ def time_formatter(milliseconds: int) -> str: hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) tmp = ( - ((str(days) + " day(s), ") if days else "") - + ((str(hours) + " hour(s), ") if hours else "") - + ((str(minutes) + " minute(s), ") if minutes else "") - + ((str(seconds) + " second(s), ") if seconds else "") - + ((str(milliseconds) + " millisecond(s), ") if milliseconds else "") + ((str(days) + " day(s), ") if days else "") + + ((str(hours) + " hour(s), ") if hours else "") + + ((str(minutes) + " minute(s), ") if minutes else "") + + ((str(seconds) + " second(s), ") if seconds else "") + + ((str(milliseconds) + " millisecond(s), ") if milliseconds else "") ) return tmp[:-2] -ydl_opts = { - "format": "bestaudio/best", - "writethumbnail": True, - "postprocessors": [ - { - "key": "FFmpegExtractAudio", - "preferredcodec": "mp3", - "preferredquality": "192", - } - ], -} - - def get_file_extension_from_url(url): url_path = urlparse(url).path basename = os.path.basename(url_path) @@ -225,15 +214,17 @@ def time_to_seconds(times): return sum(int(x) * 60 ** i for i, x in enumerate(reversed(stringt.split(":")))) -@Client.on_message(command(["vsong", f"vsong@{Veez.BOT_USERNAME}"]) & filters.group & ~filters.edited) +@Client.on_message( + command(["vsong", f"vsong@{bn}", "video", f"video@{bn}"]) & ~filters.edited +) async def vsong(client, message): ydl_opts = { - 'format':'best', - 'keepvideo':True, - 'prefer_ffmpeg':False, - 'geo_bypass':True, - 'outtmpl':'%(title)s.%(ext)s', - 'quite':True + "format": "best", + "keepvideo": True, + "prefer_ffmpeg": False, + "geo_bypass": True, + "outtmpl": "%(title)s.%(ext)s", + "quite": True, } query = " ".join(message.command[1:]) try: @@ -241,13 +232,13 @@ async def vsong(client, message): link = f"https://youtube.com{results[0]['url_suffix']}" title = results[0]["title"][:40] thumbnail = results[0]["thumbnails"][0] - thumb_name = f"thumb{title}.jpg" + thumb_name = f"{title}.jpg" thumb = requests.get(thumbnail, allow_redirects=True) open(thumb_name, "wb").write(thumb.content) - duration = results[0]["duration"] + results[0]["duration"] results[0]["url_suffix"] results[0]["views"] - rby = message.from_user.mention + message.from_user.mention except Exception as e: print(e) try: @@ -256,14 +247,15 @@ async def vsong(client, message): ytdl_data = ytdl.extract_info(link, download=True) file_name = ytdl.prepare_filename(ytdl_data) except Exception as e: - return await msg.edit(f"🚫 **error:** {str(e)}") + return await msg.edit(f"🚫 **error:** {e}") preview = wget.download(thumbnail) await msg.edit("📤 **uploading video...**") await message.reply_video( file_name, duration=int(ytdl_data["duration"]), thumb=preview, - caption=ytdl_data['title']) + caption=ytdl_data["title"], + ) try: os.remove(file_name) await msg.delete()