From 4092a975e747d8d5d6ead114c6673d59645b8df8 Mon Sep 17 00:00:00 2001 From: StarkGang Date: Sat, 5 Jun 2021 21:01:46 +0530 Subject: [PATCH 001/106] un --- any_dl.py | 255 +++++++++++++++++++++++++++++++++++++ cc_tools.py | 64 ++-------- collage.py | 9 +- fban.py | 41 ++++++ helper_files/dl_.py | 70 ++++++++++ helper_files/dl_helpers.py | 103 +++++++++++++++ req.txt | 4 + shazam.py | 87 +++++++++++++ 8 files changed, 573 insertions(+), 60 deletions(-) create mode 100644 any_dl.py create mode 100644 helper_files/dl_.py create mode 100644 helper_files/dl_helpers.py create mode 100644 shazam.py diff --git a/any_dl.py b/any_dl.py new file mode 100644 index 0000000..eb6894b --- /dev/null +++ b/any_dl.py @@ -0,0 +1,255 @@ +import time +import aiohttp +from main_startup.helper_func.basic_helpers import edit_or_reply, humanbytes, time_formatter +from .helper_files.dl_ import AnyDL +from fsplit.filesplit import Filesplit +import os +import re +import pathlib +import uuid +from pyrogram.errors import FloodWait, MessageNotModified +import math +from main_startup.config_var import Config +from main_startup.core.decorators import friday_on_cmd +from main_startup.core.startup_helpers import run_cmd +from main_startup.helper_func.basic_helpers import edit_or_reply, get_text, progress + +async def download_file(message, url, file_name): + c_ = time.time() + with open(file_name, mode='wb') as f: + async with aiohttp.ClientSession() as session: + async with session.get(url) as r: + total_length = r.headers.get('content-length') or r.headers.get("Content-Length") + dl = 0 + if total_length is None: + f.write(await r.read()) + else: + total_length = int(total_length) + async for chunk in r.content.iter_chunked(max(int(total_length/1000), 1024*1024)): + dl += len(chunk) + e_ = time.time() + diff = e_ - c_ + percentage = dl * 100 / total_length + speed = dl / diff + elapsed_time = round(diff) * 1000 + time_to_completion = round((total_length - dl) / speed) * 1000 + estimated_total_time = elapsed_time + time_to_completion + f.write(chunk) + progress_str = "{0}{1} {2}%\n".format( + "".join(["▰" for i in range(math.floor(percentage / 10))]), + "".join(["▱" for i in range(10 - math.floor(percentage / 10))]), + round(percentage, 2)) + r_ = f"Downloading This File \nFile : {file_name} \nFile Size : {humanbytes(total_length)} \nDownloaded : {humanbytes(dl)} \n{progress_str} \n\nSpeed : {humanbytes(round(speed))}/ps \nETA : {time_formatter(estimated_total_time)}" + try: + await message.edit(r_) + except MessageNotModified: + pass + return file_name + +image_ext = tuple([".jpg", ".png", ".jpeg"]) +vid_ext = tuple([".mp4", ".mkv"]) +sticker_ext = tuple([".wepb", ".tgs"]) +song_ext = tuple([".mp3", ".wav", ".m4a"]) + +async def upload_file(client, reply_message, message, file_path, caption): + rndm = uuid.uuid4().hex + siz_e = os.stat(file_path).st_size + if siz_e > 2040108421: + list_ = [] + await message.edit("`File Size More Than 2GB. Telegram Won't Allow This. Splitting Files.`") + fs = Filesplit() + if not os.path.exists(f"./splitted_{rndm}"): + os.makedirs(f"./splitted_{rndm}") + fs.split( + file=file_path, + split_size=2040108421, + output_dir=f"./splitted_{rndm}", + ) + file_list(f"./splitted_{rndm}", list_) + for oof in list_: + if oof == "fs_manifest.csv": + return + await send_file(client, reply_message, oof, caption, message) + return await message.delete() + else: + await send_file(client, reply_message, file_path, caption, message) + return await message.delete() + +async def send_file(client, r_msg, file, capt, e_msg): + c_time = time.time() + file_name = os.path.basename(file) + send_as_thumb = False + if os.path.exists("./main_startup/Cache/thumb.jpg"): + send_as_thumb = True + if file.endswith(image_ext): + await r_msg.reply_video( + file, + quote=True, + caption=capt, + progress=progress, + progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), + ) + elif file.endswith(vid_ext): + if send_as_thumb: + await r_msg.reply_video( + file, + quote=True, + thumb="./main_startup/Cache/thumb.jpg", + caption=capt, + progress=progress, + progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), + ) + else: + await r_msg.reply_video( + file, + quote=True, + caption=capt, + progress=progress, + progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), + ) + elif file.endswith(".gif"): + if send_as_thumb: + await r_msg.reply_animation( + file, + quote=True, + thumb="./main_startup/Cache/thumb.jpg", + caption=capt, + progress=progress, + progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), + ) + else: + await r_msg.reply_animation( + file, + quote=True, + caption=capt, + progress=progress, + progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), + ) + elif file.endswith(song_ext): + if send_as_thumb: + await r_msg.reply_audio( + file, + quote=True, + thumb="./main_startup/Cache/thumb.jpg", + caption=capt, + progress=progress, + progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), + ) + else: + await r_msg.reply_audio( + file, + quote=True, + caption=capt, + progress=progress, + progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), + ) + elif file.endswith(sticker_ext): + await r_msg.reply_sticker( + file, + quote=True, + progress=progress, + progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), + ) + else: + if send_as_thumb: + await r_msg.reply_document( + file, + quote=True, + thumb="./main_startup/Cache/thumb.jpg", + caption=capt, + progress=progress, + progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), + ) + else: + await r_msg.reply_document( + file, + quote=True, + caption=capt, + progress=progress, + progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), + ) + +def file_list(path, lisT): + pathlib.Path(path) + for filepath in pathlib.Path(path).glob("**/*"): + lisT.append(filepath.absolute()) + return lisT + +@friday_on_cmd( + ["udl"], + cmd_help={ + "help": "Download Files From Anonfiles, Mega, MediaFire. If Its Direct Link Make Sure To Give File Name", + "example": "{ch}udl (file url as input) if url in supported sites else {ch}udl (file url|file name)", + } +) +async def download_(client, message): + s = await edit_or_reply(message, "`Trying To Downloading..`") + dl_client = AnyDL() + url = get_text(message) + msg = message.reply_to_message or message + if "mediafire.com" in url: + try: + link = re.findall(r'\bhttps?://.*mediafire\.com\S+', url)[0] + except IndexError: + return await s.edit("`No Media File Url Links Found!`") + try: + file_url, file_name, file_size, file_upload_date, caption_, scan_result = await dl_client.media_fire_dl(url) + except BaseException as e: + return await s.edit(f"**Failed To GET Direct Link ::** `{e}`") + if file_url == None: + return await s.edit(f"**Failed To GET Direct Link**") + file = await download_file(s, file_url, file_name) + await s.delete() + caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size} \nFile Upload Date : {file_upload_date} \nFile Scan Result : {scan_result} \n{caption_}" + await upload_file(client, msg, s, file, caption) + return os.remove(file) + if "mega.nz" in url: + try: + link = re.findall(r'\bhttps?://.*mega\.nz\S+', url)[0] + except IndexError: + return await s.edit("`No Mega Url Links Found!`") + if "folder" in link: + return await s.edit("`What? Download A Folder? Are You Nutes?") + try: + file_url, file_name, file_size = await dl_client.mega_dl(link) + except BaseException as e: + return await s.edit(f"**Failed To GET Direct Link ::** `{e}`") + if file_url == None: + return await s.edit(f"**Failed To GET Direct Link**") + file = await download_file(s, file_url, file_name) + await s.delete() + caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size}" + await upload_file(client, msg, s, file, caption) + return os.remove(file) + if "anonfiles" in url: + try: + link = re.findall(r"\bhttps?://.*anonfiles\.com\S+", url)[0] + except IndexError: + return await s.edit("`No Anon Files Link Found.`") + try: + file_url, file_size, file_name = dl_client.anon_files_dl(link) + except BaseException as e: + return await s.edit(f"**Failed To GET Direct Link ::** `{e}`") + if file_url == None: + return await s.edit(f"**Failed To GET Direct Link**") + file = await download_file(s, file_url, file_name) + await s.delete() + caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size}" + await upload_file(client, msg, s, file, caption) + return os.remove(file) + else: + url_ = url.split('|') + if len(url_) != 2: + return await s.edit("`You Have To Give Me File Name & Url. Please Check Help Menu.`") + url = url_[0] + file_name = url_[1] + try: + file = await download_file(s, url_, file_name) + except BaseException as e: + return await s.edit(f"**Failed To Download ::** `{e}`") + file_size = humanbytes(os.stat(file).st_size) + caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size}" + await upload_file(client, msg, s, file, caption) + return os.remove(file) + + diff --git a/cc_tools.py b/cc_tools.py index 9e4bf13..a42d5be 100644 --- a/cc_tools.py +++ b/cc_tools.py @@ -65,7 +65,7 @@ async def namso_gen(bin, no_of_result=15): driver.find_element_by_xpath(button_xpath).click() await asyncio.sleep(2) s = driver.find_elements_by_xpath('//*[@id="result"]')[0].get_attribute("value") - driver.close() + driver.quit() return s @friday_on_cmd( @@ -89,7 +89,7 @@ async def ns_gen(client, message): bin = input s = await namso_gen(bin, no_of_results) if not s: - return msg.edit("`Invalid Bin Or Input Given More Than 25`") + return await msg.edit("`Invalid Bin Given Or Results Limit Reached.`") t = f""" **Bin :** `{bin}` @@ -101,9 +101,12 @@ async def ns_gen(client, message): **Powered By FridayUb** """ await msg.edit(t, parse_mode="md") - - - + +def stark_finder(to_find, from_find): + if re.search(r"( |^|[^\w])" + re.escape(to_find) + r"( |$|[^\w])", from_find, flags=re.IGNORECASE): + return True + return False + my_code = { 400: "『! Invalid Key !』", 200: "『 Valid Key 』", @@ -136,57 +139,6 @@ async def check_stripe_key(key_: str): else: return 200 -def stark_finder(to_find, from_find): - if re.search(r"( |^|[^\w])" + re.escape(to_find) + r"( |$|[^\w])", from_find, flags=re.IGNORECASE): - return True - return False - - -async def cc_(cc): - url = "https://starkapis.herokuapp.com/ccn/" - data_ = { - "cc": cc - } - async with aiohttp.ClientSession() as session: - async with session.get(url, json=data_) as resp: - response_ = await resp.json() - check_response = f"『 ✮ {response_['msg']} ✮ 』" - time_taken = response_['time_taken'] - cc = response_['cc'] - approved = response_['approved'] - mes = response_['exp_month'] - yes = response_['exp_year'] - cvc = response_['cvc'] - final_t = f""" -Result - -CC Number : {cc} -Approved : {approved} -CVC : {cvc} -Expiry Month : {mes} -Expiry Year : {yes} -Response : {check_response} -Time Taken: {time_taken} - -Checked Using FridayUB -""" - return final_t - -@friday_on_cmd( - ["ccn"], - cmd_help={ - "help": "Check CC - CCN Based.", - "example": "{ch}ccn 5224252466461650|11|2022|858", - }, -) -async def cc_check(client, message): - msg = await edit_or_reply(message, "`Please Wait`") - cc = get_text(message) - if not cc: - return await msg.edit("`Give Me A CC Check.`") - r = await cc_(cc) - await msg.edit(r) - @friday_on_cmd( ["sk"], cmd_help={ diff --git a/collage.py b/collage.py index d2cc34d..9e70cf5 100644 --- a/collage.py +++ b/collage.py @@ -100,9 +100,10 @@ async def wow_collage(client, message): limit = final_input[0] width = int(final_input[1]) stark_h = int(final_input[2]) - if not limit.isdigit(): - return await owo.edit("`Limit Should Be Digits.`") - limit_ = int(limit) + try: + limit_ = int(limit) + except ValueError: + return await owo.edit("`Limit Should Be In Digits.`") file_path = "./to_collage/" if os.path.exists(file_path): shutil.rmtree(file_path) @@ -112,7 +113,7 @@ async def wow_collage(client, message): try: await msg.download(file_path) except Exception as e: - logging.info(e) + logging.error(e) if img_ == 0: await owo.edit("`No Images Found.`") shutil.rmtree(file_path) diff --git a/fban.py b/fban.py index bd9cb95..b136537 100644 --- a/fban.py +++ b/fban.py @@ -123,6 +123,47 @@ async def fban_s(client, message): good_f_msg = f"**FBANNED** \n**Affected Feds :** `{len(fed_s) - failed_n}` \n**Failed :** `{failed_n}` \n**Total Fed :** `{len(fed_s)}`" await uj.edit(good_f_msg) +@friday_on_cmd( + ["unfban", "unfedban"], + is_official=False, + cmd_help={ + "help": "Un-Fban a user!", + "example": "{ch}unfban (enter username or id)", + }, +) +async def un_fban_s(client, message): + uj = await edit_or_reply(message, "`Fbanning!`") + failed_n = 0 + ur = get_text(message) + if not ur: + await uj.edit("`Who Should I Un-Fban? You?`") + return + if not Config.FBAN_GROUP: + await uj.edit("`Please Setup Fban Group!`") + return + fed_s = await get_all_feds() + if len(fed_s) == 0: + await uj.edit("`You Need Atleast One Fed In Db To Use This Plugin!`") + return + await uj.edit(f"`Un-Fbanning In {len(fed_s)} Feds!`") + try: + await client.send_message(Config.FBAN_GROUP, "/start") + except BaseException: + await uj.edit(f"`Unable To Send Message To Fban Group! \nTraceBack : {e}`") + return + for i in fed_s: + await asyncio.sleep(2) + try: + await client.send_message(Config.FBAN_GROUP, f"/joinfed {i['fed_s']}") + await client.send_message(Config.FBAN_GROUP, f"/unfban {ur}") + except FloodWait as e: + await asyncio.sleep(e.x) + except BaseException as eb: + logging.error(eb) + failed_n += 1 + good_f_msg = f"**UN-FBANNED** \n**Affected Feds :** `{len(fed_s) - failed_n}` \n**Failed :** `{failed_n}` \n**Total Fed :** `{len(fed_s)}`" + await uj.edit(good_f_msg) + async def fetch_all_fed(client, message): fed_list = [] diff --git a/helper_files/dl_.py b/helper_files/dl_.py new file mode 100644 index 0000000..d9c0e50 --- /dev/null +++ b/helper_files/dl_.py @@ -0,0 +1,70 @@ + + +import re +import aiohttp +from fake_useragent import UserAgent +from bs4 import BeautifulSoup +from lxml import etree +from xtraplugins.helper_files.dl_helpers import api_request, find_between, base64_url_decode, decrypt_attr, base64_to_a32, parse_url + +class AnyDL: + def __init__(self): + self.dl_path = "./main_startup/downloads" + + async def mega_dl(self, url): + path = parse_url(url).split('!') + if path == None: + return None, None, None + file_handle = path[0] + file_key = path[1] + file_key = base64_to_a32(file_key) + file_data = await api_request({ + 'a': 'g', + 'g': 1, + 'p': file_handle + }) + k = (file_key[0] ^ file_key[4], file_key[1] ^ file_key[5], + file_key[2] ^ file_key[6], file_key[3] ^ file_key[7]) + if 'g' not in file_data: + return None, None, None + file_url = file_data['g'] + file_size = file_data['s'] + attribs = base64_url_decode(file_data['at']) + attribs = decrypt_attr(attribs, k) + file_name = attribs['n'] + return file_url, file_name, file_size + + async def media_fire_dl(self, media_fire_url): + ua = UserAgent() + user_agent = ua.random + headers = {"User-Agent": user_agent} + async with aiohttp.ClientSession(headers=headers) as session: + async with session.get(media_fire_url) as resp: + if resp.status != 200: + return resp.status + b_ = BeautifulSoup(await resp.read(), 'html.parser') + dom = etree.HTML(str(b_)) + file_url = dom.xpath('//*[@id="downloadButton"]')[0].get("href") + file_name = dom.xpath('/html/body/div[1]/div[1]/div[2]/div/div[2]/div[1]/div[1]')[0].text + file_size = dom.xpath('/html/body/div[1]/div[1]/div[2]/div/div[2]/ul/li[1]/span')[0].text + file_uploaded_date = dom.xpath('/html/body/div[1]/div[1]/div[2]/div/div[2]/ul/li[2]/span')[0].text + caption_ = dom.xpath('/html/body/div[1]/div[1]/div[6]/div[1]/div[1]/div[3]/p')[0].text + scan_result = dom.xpath("/html/body/div[1]/div[1]/div[6]/div[1]/div[2]/div/div[2]/p/span")[0].text + return file_url, file_name, file_size, file_uploaded_date, caption_, scan_result + + async def anon_files_dl(self, anon_url): + ua = UserAgent() + user_agent = ua.random + headers = {"User-Agent": user_agent} + async with aiohttp.ClientSession(headers=headers) as session: + async with session.get(anon_url) as resp: + if resp.status != 200: + return resp.status + b_ = BeautifulSoup(await resp.read(), 'lxml') + file_url = b_.find("a", {"id": "download-url"}).get("href") + file_name = b_.find("h1", {"class": "text-center text-wordwrap"}).text + file_size = b_.find("a", {"id": "download-url"}).text + file_size = find_between(r"\(", r"\)", file_size) + return file_url, file_size, file_name + + \ No newline at end of file diff --git a/helper_files/dl_helpers.py b/helper_files/dl_helpers.py new file mode 100644 index 0000000..c20769c --- /dev/null +++ b/helper_files/dl_helpers.py @@ -0,0 +1,103 @@ +""" +Generates Direct Link From Mega Public Url +Kanged From mega.py +""" + +import json +import re +import json +import base64 +import struct +from Crypto.Cipher import AES +import aiohttp +import asyncio +import random +import codecs + +def aes_cbc_decrypt(data, key): + aes_cipher = AES.new(key, AES.MODE_CBC, codecs.latin_1_encode('\0' * 16)[0]) + return aes_cipher.decrypt(data) + +def decrypt_attr(attr, key): + attr = aes_cbc_decrypt(attr, a32_to_str(key)) + attr = codecs.latin_1_decode(attr)[0] + attr = attr.rstrip('\0') + return json.loads(attr[4:]) if attr[:6] == 'MEGA{"' else False + +def a32_to_str(a): + return struct.pack('>%dI' % len(a), *a) + +def str_to_a32(b): + if isinstance(b, str): + b = codecs.latin_1_encode(b)[0] + if len(b) % 4: + b += b'\0' * (4 - len(b) % 4) + return struct.unpack('>%dI' % (len(b) / 4), b) + +def base64_url_decode(data): + data += '=='[(2 - len(data) * 3) % 4:] + for search, replace in (('-', '+'), ('_', '/'), (',', '')): + data = data.replace(search, replace) + return base64.b64decode(data) + +def base64_to_a32(s): + return str_to_a32(base64_url_decode(s)) + +def parse_url(url): + if '/file/' in url: + url = url.replace(' ', '') + file_id = re.findall(r'\W\w\w\w\w\w\w\w\w\W', url)[0][1:-1] + id_index = re.search(file_id, url).end() + key = url[id_index + 1:] + return f'{file_id}!{key}' + elif '!' in url: + match = re.findall(r'/#!(.*)', url) + path = match[0] + return path + else: + return None + +async def download_file(url): + path = parse_url(url).split('!') + if path == None: + return None, None, None + file_handle = path[0] + file_key = path[1] + file_key = base64_to_a32(file_key) + file_data = await api_request({ + 'a': 'g', + 'g': 1, + 'p': file_handle + }) + k = (file_key[0] ^ file_key[4], file_key[1] ^ file_key[5], + file_key[2] ^ file_key[6], file_key[3] ^ file_key[7]) + if 'g' not in file_data: + return None, None, None + file_url = file_data['g'] + file_size = file_data['s'] + attribs = base64_url_decode(file_data['at']) + attribs = decrypt_attr(attribs, k) + file_name = attribs['n'] + return file_name,file_size, file_url + +async def api_request(data): + sequence_num = random.randint(0, 0xFFFFFFFF) + if not isinstance(data, list): + data = [data] + url = f'https://g.api.mega.co.nz/cs' + params = {'id': sequence_num} + async with aiohttp.ClientSession() as session: + response = await session.post(url, data=json.dumps(data), params=params) + json_resp = await response.json() + return json_resp[0] + +def find_between(self, start_string, end_string, to_find): + _to_ = f"{start_string}(.*?){end_string}" + result = re.search(_to_, to_find) + if not result: + return None + return result.group(1) + +loop = asyncio.get_event_loop() +file_url = loop.run_until_complete(download_file("https://mega.nz/#!8soDySiQ!Z6I57NiZ-K5CeE8E95ZKZyL1aSpdoo3eoDA_tE0Dlsc")) +print(file_url) diff --git a/req.txt b/req.txt index a7bbba1..d069f39 100644 --- a/req.txt +++ b/req.txt @@ -11,3 +11,7 @@ quotefancy feedparser asyncurban validators>=0.18.2 +shazamio +lxml +pycryptodome +fake_useragent \ No newline at end of file diff --git a/shazam.py b/shazam.py new file mode 100644 index 0000000..ecc9769 --- /dev/null +++ b/shazam.py @@ -0,0 +1,87 @@ +# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. +# +# This file is part of < https://github.com/DevsExpo/FridayUserBot > project, +# and is released under the "GNU v3.0 License Agreement". +# Please see < https://github.com/DevsExpo/blob/master/LICENSE > +# +# All rights reserved. + + +import os +import asyncio +from shazamio import Shazam +from main_startup.core.startup_helpers import run_cmd +import datetime +import requests +import time +from main_startup.core.decorators import friday_on_cmd +from main_startup.helper_func.basic_helpers import edit_or_reply, get_text, humanbytes + +async def shazam(file): + shazam = Shazam() + try: + r = await shazam.recognize_song(file) + except: + return None, None, None + if not r: + return None, None, None + track = r.get("track") + nt = track.get("images") + image = nt.get("coverarthq") + by = track.get("subtitle") + title = track.get("title") + return image, by, title + +async def convert_to_audio(vid_path): + stark_cmd = f"ffmpeg -i {vid_path} -map 0:a friday.mp3" + await runcmd(stark_cmd) + final_warner = "friday.mp3" + if not os.path.exists(final_warner): + return None + return final_warner + +@friday_on_cmd( + ["shazam"], + cmd_help={ + "help": "Recognize / Discover A Song", + "example": "{ch}shazam (reply to music file)", + }, +) +async def shazam_(client, message): + stime = time.time() + msg = await edit_or_reply(message, "`Shazaming This Song.") + if not message.reply_to_message: + return await msg.edit("`Reply To Song File`") + if not (message.reply_to_message.audio or message.reply_to_message.voice or message.reply_to_message.video): + return await msg.edit("`Reply To Audio File.`") + if message.reply_to_message.video: + video_file = await message.reply_to_message.download() + music_file = await convert_to_audio(video_file) + dur = message.reply_to_message.video.duration + if not music_file: + return await msg.edit("`Unable To Convert To Song File. Is This A Valid File?`") + elif (message.reply_to_message.voice or message.reply_to_message.audio): + dur = message.reply_to_message.voice.duration if message.reply_to_message.voice else message.reply_to_message.audio.duration + music_file = await message.reply_to_message.download() + size_ = humanbytes(os.stat(music_file).st_size) + dur = datetime.timedelta(seconds=dur) + thumb, by, title = await shazam(music_file) + if title == None: + return await msg.edit("`No Results Found.`") + etime = time.time() + t_k = round(etime - stime) + caption = f"""Shazamed Song + +Song Name : {title} +Singer : {by} +Duration : {dur} +Size : {size_} +Time Taken : {t_k} Seconds + +Shazamed By FridayUB + """ + if thumb: + await msg.delete() + await message.reply_to_message.reply_photo(thumb, caption=caption, quote=True) + else: + await msg.edit(caption) \ No newline at end of file From 1d0b49aa97c484375878553fab23d1be31022c65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 5 Jun 2021 21:42:56 +0530 Subject: [PATCH 002/106] Update req.txt --- req.txt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/req.txt b/req.txt index d069f39..d5eed1c 100644 --- a/req.txt +++ b/req.txt @@ -10,8 +10,7 @@ emoji-country-flag quotefancy feedparser asyncurban -validators>=0.18.2 +validators shazamio lxml pycryptodome -fake_useragent \ No newline at end of file From 5d6641f4c297ab7dd18e21c905d91f8b8d8737ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 5 Jun 2021 22:50:05 +0530 Subject: [PATCH 003/106] Update req.txt --- req.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/req.txt b/req.txt index d5eed1c..6ee5ef8 100644 --- a/req.txt +++ b/req.txt @@ -1,7 +1,9 @@ +lxml wikipedia pytgcalls mal-api git+https://github.com/chsaiujwal/maigret +git+https://github.com/starkgang/shazamio git+https://github.com/gleitz/howdoi speedtest-cli tswift @@ -11,6 +13,4 @@ quotefancy feedparser asyncurban validators -shazamio -lxml pycryptodome From 02fa8790d7633914d5abd503ef2733314bcfc400 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 6 Jun 2021 08:33:55 +0530 Subject: [PATCH 004/106] Update req.txt --- req.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/req.txt b/req.txt index 6ee5ef8..6815838 100644 --- a/req.txt +++ b/req.txt @@ -2,7 +2,7 @@ lxml wikipedia pytgcalls mal-api -git+https://github.com/chsaiujwal/maigret +git+https://github.com/StarkGang/maigret git+https://github.com/starkgang/shazamio git+https://github.com/gleitz/howdoi speedtest-cli From 1bdd3f329853e6d2b33beabd58d031e40aa47776 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 6 Jun 2021 08:38:42 +0530 Subject: [PATCH 005/106] Update dl_helpers.py --- helper_files/dl_helpers.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/helper_files/dl_helpers.py b/helper_files/dl_helpers.py index c20769c..632f642 100644 --- a/helper_files/dl_helpers.py +++ b/helper_files/dl_helpers.py @@ -97,7 +97,4 @@ def find_between(self, start_string, end_string, to_find): if not result: return None return result.group(1) - -loop = asyncio.get_event_loop() -file_url = loop.run_until_complete(download_file("https://mega.nz/#!8soDySiQ!Z6I57NiZ-K5CeE8E95ZKZyL1aSpdoo3eoDA_tE0Dlsc")) -print(file_url) + From 87aa6eb367a86d12ea12a624bc1f7c0891a5d713 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 6 Jun 2021 09:07:19 +0530 Subject: [PATCH 006/106] Fix --- any_dl.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/any_dl.py b/any_dl.py index eb6894b..cf9a311 100644 --- a/any_dl.py +++ b/any_dl.py @@ -70,10 +70,9 @@ async def upload_file(client, reply_message, message, file_path, caption): if oof == "fs_manifest.csv": return await send_file(client, reply_message, oof, caption, message) - return await message.delete() else: await send_file(client, reply_message, file_path, caption, message) - return await message.delete() + return await message.delete() async def send_file(client, r_msg, file, capt, e_msg): c_time = time.time() @@ -199,7 +198,6 @@ async def download_(client, message): if file_url == None: return await s.edit(f"**Failed To GET Direct Link**") file = await download_file(s, file_url, file_name) - await s.delete() caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size} \nFile Upload Date : {file_upload_date} \nFile Scan Result : {scan_result} \n{caption_}" await upload_file(client, msg, s, file, caption) return os.remove(file) @@ -217,7 +215,6 @@ async def download_(client, message): if file_url == None: return await s.edit(f"**Failed To GET Direct Link**") file = await download_file(s, file_url, file_name) - await s.delete() caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size}" await upload_file(client, msg, s, file, caption) return os.remove(file) @@ -233,7 +230,6 @@ async def download_(client, message): if file_url == None: return await s.edit(f"**Failed To GET Direct Link**") file = await download_file(s, file_url, file_name) - await s.delete() caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size}" await upload_file(client, msg, s, file, caption) return os.remove(file) From 5e3ea1c5b875c77a775ab0200ce1f30b8f8dd53d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 6 Jun 2021 09:12:59 +0530 Subject: [PATCH 007/106] Update any_dl.py --- any_dl.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/any_dl.py b/any_dl.py index cf9a311..70d2f19 100644 --- a/any_dl.py +++ b/any_dl.py @@ -25,7 +25,7 @@ async def download_file(message, url, file_name): f.write(await r.read()) else: total_length = int(total_length) - async for chunk in r.content.iter_chunked(max(int(total_length/1000), 1024*1024)): + async for chunk in r.content.iter_chunked(2341): dl += len(chunk) e_ = time.time() diff = e_ - c_ From cbab67eb42c329dd44e2cf477c5f81516862cfec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 6 Jun 2021 09:17:07 +0530 Subject: [PATCH 008/106] Update any_dl.py --- any_dl.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/any_dl.py b/any_dl.py index 70d2f19..0ac80d8 100644 --- a/any_dl.py +++ b/any_dl.py @@ -25,7 +25,7 @@ async def download_file(message, url, file_name): f.write(await r.read()) else: total_length = int(total_length) - async for chunk in r.content.iter_chunked(2341): + async for chunk in r.content.iter_chunked(max(int(total_length/1000), 1024*6)): dl += len(chunk) e_ = time.time() diff = e_ - c_ From d27fd971246b5e5df4fe3df6ba55b2c03f6c7f0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 6 Jun 2021 10:33:44 +0530 Subject: [PATCH 009/106] Update any_dl.py --- any_dl.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/any_dl.py b/any_dl.py index 0ac80d8..aa36289 100644 --- a/any_dl.py +++ b/any_dl.py @@ -25,7 +25,7 @@ async def download_file(message, url, file_name): f.write(await r.read()) else: total_length = int(total_length) - async for chunk in r.content.iter_chunked(max(int(total_length/1000), 1024*6)): + async for chunk in r.content.iter_chunked(max(int(total_length/500), (1024*1024)*2)): dl += len(chunk) e_ = time.time() diff = e_ - c_ @@ -247,5 +247,4 @@ async def download_(client, message): caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size}" await upload_file(client, msg, s, file, caption) return os.remove(file) - - + From ceed2094cd85ca145240434fcc2fa7f20c838e56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 6 Jun 2021 10:57:27 +0530 Subject: [PATCH 010/106] Update any_dl.py --- any_dl.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/any_dl.py b/any_dl.py index aa36289..8427d49 100644 --- a/any_dl.py +++ b/any_dl.py @@ -1,3 +1,11 @@ +# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. +# +# This file is part of < https://github.com/DevsExpo/FridayUserBot > project, +# and is released under the "GNU v3.0 License Agreement". +# Please see < https://github.com/DevsExpo/blob/master/LICENSE > +# +# All rights reserved. + import time import aiohttp from main_startup.helper_func.basic_helpers import edit_or_reply, humanbytes, time_formatter @@ -175,7 +183,7 @@ def file_list(path, lisT): return lisT @friday_on_cmd( - ["udl"], + ["udl", "any_dl"], cmd_help={ "help": "Download Files From Anonfiles, Mega, MediaFire. If Its Direct Link Make Sure To Give File Name", "example": "{ch}udl (file url as input) if url in supported sites else {ch}udl (file url|file name)", @@ -215,6 +223,7 @@ async def download_(client, message): if file_url == None: return await s.edit(f"**Failed To GET Direct Link**") file = await download_file(s, file_url, file_name) + file_size = humanbytes(file_size) caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size}" await upload_file(client, msg, s, file, caption) return os.remove(file) @@ -247,4 +256,4 @@ async def download_(client, message): caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size}" await upload_file(client, msg, s, file, caption) return os.remove(file) - + From ced8c31254450a3ad77781a378d924ba4aa94225 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 6 Jun 2021 10:58:48 +0530 Subject: [PATCH 011/106] Update any_dl.py --- any_dl.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/any_dl.py b/any_dl.py index 8427d49..a44ae28 100644 --- a/any_dl.py +++ b/any_dl.py @@ -233,7 +233,7 @@ async def download_(client, message): except IndexError: return await s.edit("`No Anon Files Link Found.`") try: - file_url, file_size, file_name = dl_client.anon_files_dl(link) + file_url, file_size, file_name = await dl_client.anon_files_dl(link) except BaseException as e: return await s.edit(f"**Failed To GET Direct Link ::** `{e}`") if file_url == None: From 341885ac3a06a5ad34252337aff959d41617afcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 6 Jun 2021 11:02:31 +0530 Subject: [PATCH 012/106] Update dl_helpers.py --- helper_files/dl_helpers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/helper_files/dl_helpers.py b/helper_files/dl_helpers.py index 632f642..2d90da9 100644 --- a/helper_files/dl_helpers.py +++ b/helper_files/dl_helpers.py @@ -91,7 +91,7 @@ async def api_request(data): json_resp = await response.json() return json_resp[0] -def find_between(self, start_string, end_string, to_find): +def find_between(start_string, end_string, to_find): _to_ = f"{start_string}(.*?){end_string}" result = re.search(_to_, to_find) if not result: From 795351a0902ac7b53dab5c73c5ff458b1d6b23c8 Mon Sep 17 00:00:00 2001 From: StarkGang Date: Tue, 8 Jun 2021 22:38:09 +0530 Subject: [PATCH 013/106] Fix --- carbon.py | 87 +++++++++++++++++++++++ collage.py | 13 ++-- helper_files/dl_.py | 8 ++- helper_files/dl_helpers.py | 2 +- music_player.py | 57 +++++++++++++++ rom_search.py | 139 +++++++++++++++++++++++++++++++++++++ 6 files changed, 298 insertions(+), 8 deletions(-) create mode 100644 carbon.py create mode 100644 rom_search.py diff --git a/carbon.py b/carbon.py new file mode 100644 index 0000000..8837ebd --- /dev/null +++ b/carbon.py @@ -0,0 +1,87 @@ +# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. +# +# This file is part of < https://github.com/DevsExpo/FridayUserBot > project, +# and is released under the "GNU v3.0 License Agreement". +# Please see < https://github.com/DevsExpo/blob/master/LICENSE > +# +# All rights reserved. + +from selenium.webdriver.support.ui import WebDriverWait +from selenium.webdriver.support import expected_conditions as EC +from selenium.webdriver.common.by import By +from selenium import webdriver +from selenium.webdriver.chrome.options import Options +import asyncio +import logging +from selenium.common.exceptions import NoSuchElementException +from main_startup import Config +import random +import os +from main_startup.core.decorators import friday_on_cmd +from main_startup.core.startup_helpers import run_cmd +from main_startup.helper_func.basic_helpers import edit_or_reply, get_text + + +GOOGLE_CHROME_BIN = Config.CHROME_BIN_PATH +CHROME_DRIVER = Config.CHROME_DRIVER_PATH + +async def make_carbon(code, driver, lang="auto"): + url = f'https://carbon.now.sh/?l={lang}&code={code}' + driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command') + params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': './'}} + command_result = driver.execute("send_command", params) + driver.get(url) + type_ = '//*[@id="__next"]/main/div[2]/div[2]/div[1]/div[1]/div/span[2]' + em = "export-menu" + png_xpath = '//*[@id="export-png"]' + four_x_path = '//*[@id="__next"]/main/div[2]/div[2]/div[1]/div[3]/div[4]/div[3]/div[2]/div[3]/div/button[3]' + color_used_xpath = '/html/body/div[1]/main/div[2]/div[2]/div[1]/div[1]/div/span[2]/input' + random_int = random.randint(1, 29) + value_ = "downshift-0-item-" + str(random_int) + wait = WebDriverWait(driver, 20) + wait.until(EC.visibility_of_element_located((By.XPATH, type_))).click() + wait.until(EC.visibility_of_element_located((By.ID, value_))).click() + wait.until(EC.visibility_of_element_located((By.ID, em))).click() + wait.until(EC.visibility_of_element_located((By.XPATH, four_x_path))).click() + wait.until(EC.visibility_of_element_located((By.XPATH, png_xpath))).click() + file_ = "./carbon.png" + while not os.path.exists(file_): + await asyncio.sleep(1) + color_used = wait.until(EC.visibility_of_element_located((By.XPATH, color_used_xpath))).get_attribute("value") + return file_, color_used + +@friday_on_cmd( + ["carbon", "karb"], + cmd_help={ + "help": "`Carbonize Codes In A Cool Way.`", + "example": "{ch}carbon (input or reply_message will be taken)", + }, +) +async def karb(client, message): + e_ = await edit_or_reply(message, "`Carbonzing Code...`") + code = get_text(message) + if not code: + if not message.reply_to_message: + return await message.edit("`Nothing To Carbonize..`") + if not message.reply_to_message.text: + return await message.edit("`Nothing To Carbonize...`") + code = code or message.reply_to_message.text + reply_ = message.reply_to_message or message + chrome_options = Options() + chrome_options.add_argument("--headless") + chrome_options.binary_location = GOOGLE_CHROME_BIN + chrome_options.add_argument("--window-size=1920x1080") + chrome_options.add_argument("--disable-dev-shm-usage") + chrome_options.add_argument("--no-sandbox") + chrome_options.add_argument("--disable-gpu") + prefs = {'download.default_directory' : './'} + chrome_options.add_experimental_option('prefs', prefs) + driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) + try: + carbon_file, value_ = await make_carbon(code, driver) + except BaseException as e: + await e_.edit(f"[Selenium] - [Chrome - Driver] - [Carbon] >> {e}") + return driver.quit() + driver.quit() + await reply_.send_photo(carbon_file, caption=f"Code Carbonized Using Friday \nStyle Used : {value_}") + await e_.delete() \ No newline at end of file diff --git a/collage.py b/collage.py index 9e70cf5..a9411e7 100644 --- a/collage.py +++ b/collage.py @@ -108,12 +108,13 @@ async def wow_collage(client, message): if os.path.exists(file_path): shutil.rmtree(file_path) os.mkdir(file_path) - async for msg in client.search_messages(chat, filter="photo", limit=limit_): - img_ += 1 - try: - await msg.download(file_path) - except Exception as e: - logging.error(e) + async for msg in client.iter_history(chat, limit=limit_): + if msg.photo: + img_ += 1 + try: + await msg.download(file_path) + except Exception as e: + logging.error(e) if img_ == 0: await owo.edit("`No Images Found.`") shutil.rmtree(file_path) diff --git a/helper_files/dl_.py b/helper_files/dl_.py index d9c0e50..3d4facf 100644 --- a/helper_files/dl_.py +++ b/helper_files/dl_.py @@ -1,4 +1,10 @@ - +# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. +# +# This file is part of < https://github.com/DevsExpo/FridayUserBot > project, +# and is released under the "GNU v3.0 License Agreement". +# Please see < https://github.com/DevsExpo/blob/master/LICENSE > +# +# All rights reserved. import re import aiohttp diff --git a/helper_files/dl_helpers.py b/helper_files/dl_helpers.py index 2d90da9..afe248d 100644 --- a/helper_files/dl_helpers.py +++ b/helper_files/dl_helpers.py @@ -1,6 +1,6 @@ """ Generates Direct Link From Mega Public Url -Kanged From mega.py +Copied From mega.py And Modified To Fit My Purpose. """ import json diff --git a/music_player.py b/music_player.py index 5cbd8c7..a76eb29 100644 --- a/music_player.py +++ b/music_player.py @@ -14,6 +14,7 @@ from main_startup.core.decorators import friday_on_cmd from main_startup.helper_func.basic_helpers import edit_or_reply, get_text from pytgcalls import GroupCall +import signal import asyncio import os import time @@ -205,6 +206,62 @@ async def convert_to_raw(audio_original, raw_file_name): return None return raw_file_name + +RD_ = {} +FFMPEG_PROCESSES = {} + + +@friday_on_cmd( + ["radio_vc"], + is_official=False, + cmd_help={"help": "Play Radio.", "example": "{ch}radio_vc (radio url)"}, +) +async def radio_s(client, message): + s = await edit_or_reply(message, "`Please Wait.`") + gmt = time.gmtime() + ts = calendar.timegm(gmt) + input_filename = f"{message.chat.id}_{ts}.raw" + radio_url = get_text(message) + if not radio_url: + return await s.edit("`Invalid Radio URL...`") + group_call = RD_.get((message.chat.id, client)) + if not group_call: + group_call = GroupCall(client, input_filename, path_to_log_file='') + RD_[(message.chat.id, client)] = group_call + process = FFMPEG_PROCESSES.get((message.chat.id, client)) + if process: + process.send_signal(signal.SIGTERM) + await group_call.start(message.chat.id) + process = ffmpeg.input(radio_url).output( + input_filename, + format='s16le', + acodec='pcm_s16le', + ac=2, + ar='48k' + ).overwrite_output().run_async() + FFMPEG_PROCESSES[(message.chat.id, client)] = process + await s.edit(f"**📻 Playing :** `{radio_url}`") + +@friday_on_cmd( + ["stop_radio"], + is_official=False, + cmd_help={"help": "Stop Radio.", "example": "{ch}stop_radio"}, +) +async def stop_radio(client, message: Message): + msg = await edit_or_reply(message, "`Please Wait.`") + group_call = GROUP_CALLS.get((message.chat.id, client)) + if group_call: + if group_call.is_connected: + await group_call.stop() + else: + return await msg.edit("`Is Vc is Connected?`") + else: + return await msg.edit("`Is Vc is Connected?`") + process = FFMPEG_PROCESSES.get((message.chat.id, client)) + if process: + process.send_signal(signal.SIGTERM) + await msg.edit("`Radio Stopped : 📻`") + @friday_on_cmd( ["pause"], diff --git a/rom_search.py b/rom_search.py new file mode 100644 index 0000000..1ffb8a4 --- /dev/null +++ b/rom_search.py @@ -0,0 +1,139 @@ +# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. +# +# This file is part of < https://github.com/DevsExpo/FridayUserBot > project, +# and is released under the "GNU v3.0 License Agreement". +# Please see < https://github.com/DevsExpo/blob/master/LICENSE > +# +# All rights reserved. + +from selenium.webdriver.support.ui import WebDriverWait +from selenium.webdriver.support import expected_conditions as EC +from selenium.common.exceptions import TimeoutException +from selenium.webdriver.common.by import By +from selenium import webdriver +from selenium.webdriver.common.keys import Keys +from selenium.webdriver.support.ui import Select +from selenium.webdriver.chrome.options import Options +from selenium.common.exceptions import NoSuchElementException +import asyncio +from main_startup import Config +import aiohttp +from bs4 import BeautifulSoup +from lxml import etree +from main_startup.core.decorators import friday_on_cmd +from main_startup.core.startup_helpers import run_cmd +from main_startup.helper_func.basic_helpers import edit_or_reply, get_text + +GOOGLE_CHROME_BIN = Config.CHROME_BIN_PATH +CHROME_DRIVER = Config.CHROME_DRIVER_PATH +ch_ = Config.COMMAND_HANDLER + +async def get_url(query: str): + url = "https://xiaomifirmwareupdater.com/miui/" + chrome_options = Options() + chrome_options.add_argument("--headless") + chrome_options.binary_location = GOOGLE_CHROME_BIN + chrome_options.add_argument("--disable-dev-shm-usage") + chrome_options.add_argument("--no-sandbox") + chrome_options.add_argument("--disable-gpu") + driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) + driver.get(url) + wait = WebDriverWait(driver, 20) + wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#miui_filter > label > input"))).send_keys(query) + await asyncio.sleep(5) + try: + bruh = driver.find_element_by_css_selector("#miui > tbody > tr:nth-child(1) > td:nth-child(8) > a") + except NoSuchElementException: + driver.quit() + return None, None, None, None, None, None, None + if not bruh: + driver.quit() + return None, None, None, None, None, None, None + href = bruh.get_attribute('href') + driver.quit() + return await fetch_data(href) + +async def fetch_data(url: str): + async with aiohttp.ClientSession() as session: + resp = await session.get(url) + b_ = BeautifulSoup(await resp.read(), 'lxml') + device_name = b_.select("#downloads > div > ul > li:nth-child(1) > h5")[0].text.split("Device: ")[1] + version = b_.select("#downloads > div > ul > li:nth-child(3) > h5")[0].text.split("Version: ")[1] + size = b_.select("#downloads > div > ul > li:nth-child(6) > h5")[0].text.split("Size: ")[1] + rs_date = b_.select("#downloads > div > ul > li:nth-child(7) > h5")[0].text.split("Release Date: ")[1] + type_ = b_.select("#downloads > div > ul > li:nth-child(5) > h5")[0].text.split("Type: ")[1] + package_name = b_.find("span", {"id": "filename"}).text + url = f"https://bigota.d.miui.com/{version}/{package_name}" + return url, device_name, version, size, rs_date, type_, package_name + +async def realme_rom_search(query: str): + url = "https://realmeupdater.com/" + chrome_options = Options() + chrome_options.add_argument("--headless") + chrome_options.binary_location = GOOGLE_CHROME_BIN + chrome_options.add_argument("--disable-dev-shm-usage") + chrome_options.add_argument("--no-sandbox") + chrome_options.add_argument("--disable-gpu") + driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) + driver.get(url) + await asyncio.sleep(5) + driver.maximize_window() + wait = WebDriverWait(driver, 30) + driver.get("https://realmeupdater.com/") + driver.execute_script("var scrollingElement = (document.scrollingElement || document.body);scrollingElement.scrollTop = scrollingElement.scrollHeight;") + wait.until(EC.visibility_of_element_located((By.ID, "select2-device-container"))).click() + wait.until(EC.visibility_of_element_located((By.XPATH, "/html/body/span/span/span[1]/input"))).send_keys(query) + try: + all_options = driver.find_elements(By.CSS_SELECTOR, "#select2-device-results li") + except NoSuchElementException: + driver.quit() + return None, None, None, None, None + if not all_options: + driver.quit() + return None, None, None, None, None + all_options[0].click() + wait.until(EC.visibility_of_element_located((By.XPATH, "/html/body/div[5]/div[1]/div[2]/div/div/div[2]/div/div[1]/form/div/div[3]/button"))).click() + device = wait.until(EC.visibility_of_element_located((By.XPATH, "//h5[./b[text()='Device: ']]"))).text.split(maxsplit=1)[1] + system = wait.until(EC.visibility_of_element_located((By.XPATH, "//h5[./b[text()='System: ']]"))).text.split(maxsplit=1)[1] + size = wait.until(EC.visibility_of_element_located((By.XPATH, "//h5[./b[text()='Size: ']]"))).text.split(maxsplit=1)[1] + rdate = wait.until(EC.visibility_of_element_located((By.XPATH, "//h5[./b[text()='Release Date: ']]"))).text.split(": ", maxsplit=1)[1] + file_name = wait.until(EC.visibility_of_element_located((By.ID, "filename"))).text + file_url = f"https://download.c.realme.com/osupdate/{file_name}" + driver.quit() + return file_url, rdate, size, system, device + +@friday_on_cmd( + ["mrs"], + cmd_help={ + "help": "`Search MiUi Roms :)`", + "example": "{ch}mrs mi 10 pro", + }, +) +async def m_(client, message): + e_ = await edit_or_reply(message, "`Please Wait..`") + query = get_text(message) + if not query: + return await e_.edit("`Please Give Me An Query.`") + url, device_name, version, size, rs_date, type_, package_name = await get_url(query) + if url == None: + return await e_.edit("`No Results Matching You Query.`") + final_ = f"MIUI Search \nModel : {device_name} \nVersion : {version} \nSize : {size} \nRelease Date : {rs_date} \nType : {type_} \nPackage Name : {package_name} \nDownload : {ch_}udl {url}" + await message.edit(final_) + +@friday_on_cmd( + ["rms"], + cmd_help={ + "help": "`Search Realme Roms :)`", + "example": "{ch}rms pro", + }, +) +async def rm_s(client, message): + e_ = await edit_or_reply(message, "`Please Wait..`") + query = get_text(message) + if not query: + return await e_.edit("`Please Give Me An Query.`") + file_url, r_date, size, system, device = await realme_rom_search(query) + if file_url == None: + return await e_.edit("`No Results Matching You Query.`") + final_ = f"RealMeRom Search \nDevice : {device} \nSystem : {system} \nSize : {size} \nRelease Date : {r_date} \nDownload : {ch_}udl {file_url}" + await message.edit(final_) \ No newline at end of file From 5ce8bce518167308f8cfa7028879e437b16feb36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Tue, 8 Jun 2021 22:46:57 +0530 Subject: [PATCH 014/106] Update music_player.py --- music_player.py | 1 + 1 file changed, 1 insertion(+) diff --git a/music_player.py b/music_player.py index a76eb29..1ae27cc 100644 --- a/music_player.py +++ b/music_player.py @@ -11,6 +11,7 @@ import ffmpeg from main_startup import Friday import time +import calender from main_startup.core.decorators import friday_on_cmd from main_startup.helper_func.basic_helpers import edit_or_reply, get_text from pytgcalls import GroupCall From ef212d858db2750480a4189c2e0b0a3d3c49fb93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Tue, 8 Jun 2021 22:55:44 +0530 Subject: [PATCH 015/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index 1ae27cc..834ea53 100644 --- a/music_player.py +++ b/music_player.py @@ -11,7 +11,7 @@ import ffmpeg from main_startup import Friday import time -import calender +import calendar from main_startup.core.decorators import friday_on_cmd from main_startup.helper_func.basic_helpers import edit_or_reply, get_text from pytgcalls import GroupCall From d551af3aba93afe5db4b598ea185d685d06b25c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 06:31:38 +0530 Subject: [PATCH 016/106] Update music_player.py --- music_player.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/music_player.py b/music_player.py index 834ea53..0af973a 100644 --- a/music_player.py +++ b/music_player.py @@ -213,15 +213,13 @@ async def convert_to_raw(audio_original, raw_file_name): @friday_on_cmd( - ["radio_vc"], + ["pradio"], is_official=False, - cmd_help={"help": "Play Radio.", "example": "{ch}radio_vc (radio url)"}, + cmd_help={"help": "Play Radio.", "example": "{ch}pradio (radio url)"}, ) async def radio_s(client, message): s = await edit_or_reply(message, "`Please Wait.`") - gmt = time.gmtime() - ts = calendar.timegm(gmt) - input_filename = f"{message.chat.id}_{ts}.raw" + input_filename = f"radio-{message.chat.id}.raw" radio_url = get_text(message) if not radio_url: return await s.edit("`Invalid Radio URL...`") @@ -244,7 +242,7 @@ async def radio_s(client, message): await s.edit(f"**📻 Playing :** `{radio_url}`") @friday_on_cmd( - ["stop_radio"], + ["sradio"], is_official=False, cmd_help={"help": "Stop Radio.", "example": "{ch}stop_radio"}, ) From 4b065c76dbc8aaba83e2146ac2f0abd9077693b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 06:59:38 +0530 Subject: [PATCH 017/106] Create music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index 0af973a..67aeb73 100644 --- a/music_player.py +++ b/music_player.py @@ -248,7 +248,7 @@ async def radio_s(client, message): ) async def stop_radio(client, message: Message): msg = await edit_or_reply(message, "`Please Wait.`") - group_call = GROUP_CALLS.get((message.chat.id, client)) + group_call = RD_.get((message.chat.id, client)) if group_call: if group_call.is_connected: await group_call.stop() From 90f008908e9ca69b1bda044dba96a55c070d939a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 11:16:19 +0530 Subject: [PATCH 018/106] Update music_player.py --- music_player.py | 56 +++++++++++++++++++++++++++++++++++-------------- 1 file changed, 40 insertions(+), 16 deletions(-) diff --git a/music_player.py b/music_player.py index 67aeb73..dff8056 100644 --- a/music_player.py +++ b/music_player.py @@ -27,7 +27,7 @@ s = [] s_dict = {} group_call = GroupCall(None, play_on_repeat=False) - +GPC = {} @friday_on_cmd( ["playlist"], @@ -35,16 +35,17 @@ cmd_help={"help": "Get Current Chat Playlist!", "example": "{ch}playlist"}, ) async def pl(client, message): - group_call.client = client + group_call = GPC.get((message.chat.id, client.me.id)) play = await edit_or_reply(message, "`Please Wait!`") song = f"**PlayList in {message.chat.title}** \n" sno = 0 + if not group_call: + return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") if not s: if group_call.is_connected: - await play.edit(f"**Currently Playing :** `{str(group_call.input_filename).replace('.raw', '')}`") + return await play.edit(f"**Currently Playing :** `{str(group_call.input_filename).replace('.raw', '')}`") else: - await play.edit("`Playlist is Empty Sar And Nothing is Playing Also :(!`") - return + return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") if group_call.is_connected: song += f"**Currently Playing :** `{str(group_call.input_filename).replace('.raw', '')}` \n\n" for i in s: @@ -55,7 +56,6 @@ async def pl(client, message): @group_call.on_playout_ended async def playout_ended_handler(group_call, filename): global s - client_ = group_call.client if os.path.exists(group_call.input_filename): os.remove(group_call.input_filename) if not s: @@ -79,12 +79,15 @@ async def playout_ended_handler(group_call, filename): cmd_help={"help": "Skip Song in Playlist.", "example": "{ch}skip_vc (key_len)"} ) async def ski_p(client, message): - group_call.client = client + m_ = await edit_or_reply(message, "`Please Wait!`") + no_t_s = get_text(message) + group_call = GPC.get((message.chat.id, client.me.id)) + if not group_call: + await m_.edit("`Is Group Call Even Connected?`") + return if not group_call.is_connected: await m_.edit("`Is Group Call Even Connected?`") return - m_ = await edit_or_reply(message, "`Please Wait!`") - no_t_s = get_text(message) if not no_t_s: return await m_.edit("`Give Me Valid List Key Len.`") if no_t_s == "current": @@ -268,7 +271,10 @@ async def stop_radio(client, message: Message): cmd_help={"help": "Pause Currently Playing Song.", "example": "{ch}pause"}, ) async def no_song_play(client, message): - group_call.client = client + group_call = GPC.get((message.chat.id, client.me.id)) + if not group_call: + await edit_or_reply(message, "`Is Group Call Even Connected?`") + return if not group_call.is_connected: await edit_or_reply(message, "`Is Group Call Even Connected?`") return @@ -282,7 +288,10 @@ async def no_song_play(client, message): cmd_help={"help": "Resume Paused Song.", "example": "{ch}resume"}, ) async def wow_dont_stop_songs(client, message): - group_call.client = client + group_call = GPC.get((message.chat.id, client.me.id)) + if not group_call: + await edit_or_reply(message, "`Is Group Call Even Connected?`") + return if not group_call.is_connected: await edit_or_reply(message, "`Is Group Call Even Connected?`") return @@ -296,7 +305,10 @@ async def wow_dont_stop_songs(client, message): cmd_help={"help": "Stop VoiceChat!", "example": "{ch}stopvc"}, ) async def kill_vc_(client, message): - group_call.client = client + group_call = GPC.get((message.chat.id, client.me.id)) + if not group_call: + await edit_or_reply(message, "`Is Group Call Even Connected?`") + return if not group_call.is_connected: await edit_or_reply(message, "`Is Group Call Even Connected?`") return @@ -312,7 +324,10 @@ async def kill_vc_(client, message): cmd_help={"help": "Replay Song In VC!", "example": "{ch}rvc"}, ) async def replay(client, message): - group_call.client = client + group_call = GPC.get((message.chat.id, client.me.id)) + if not group_call: + await edit_or_reply(message, "`Is Group Call Even Connected?`") + return if not group_call.is_connected: await edit_or_reply(message, "`Is Group Call Even Connected?`") return @@ -326,7 +341,10 @@ async def replay(client, message): cmd_help={"help": "Rejoin Voice Chat!", "example": "{ch}rjvc"}, ) async def rejoinvcpls(client, message): - group_call.client = client + group_call = GPC.get((message.chat.id, client.me.id)) + if not group_call: + await edit_or_reply(message, "`Is Group Call Even Connected?`") + return if not group_call.is_connected: await edit_or_reply(message, "`Is Group Call Even Connected?`") return @@ -340,7 +358,10 @@ async def rejoinvcpls(client, message): cmd_help={"help": "Leave Voice Call!", "example": "{ch}leavevc"}, ) async def leave_vc_test(client, message): - group_call.client = client + group_call = GPC.get((message.chat.id, client.me.id)) + if not group_call: + await edit_or_reply(message, "`Is Group Call Even Connected?`") + return if not group_call.is_connected: await edit_or_reply(message, "`Is Group Call Even Connected?`") return @@ -359,7 +380,10 @@ async def leave_vc_test(client, message): }, ) async def set_vol(client, message): - group_call.client = client + group_call = GPC.get((message.chat.id, client.me.id)) + if not group_call: + await edit_or_reply(message, "`Is Group Call Even Connected?`") + return if not group_call.is_connected: await edit_or_reply(message, "`Is Group Call Even Connected?`") return From f80e7ff66c6b4c4a6696acbf4277ad57e4f473f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 11:24:24 +0530 Subject: [PATCH 019/106] Update rom_search.py --- rom_search.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rom_search.py b/rom_search.py index 1ffb8a4..956006c 100644 --- a/rom_search.py +++ b/rom_search.py @@ -117,7 +117,7 @@ async def m_(client, message): url, device_name, version, size, rs_date, type_, package_name = await get_url(query) if url == None: return await e_.edit("`No Results Matching You Query.`") - final_ = f"MIUI Search \nModel : {device_name} \nVersion : {version} \nSize : {size} \nRelease Date : {rs_date} \nType : {type_} \nPackage Name : {package_name} \nDownload : {ch_}udl {url}" + final_ = f"MIUI Search \nModel : {device_name} \nVersion : {version} \nSize : {size} \nRelease Date : {rs_date} \nType : {type_} \nPackage Name : {package_name} \nDownload : {ch_}udl {url}" await message.edit(final_) @friday_on_cmd( @@ -136,4 +136,4 @@ async def rm_s(client, message): if file_url == None: return await e_.edit("`No Results Matching You Query.`") final_ = f"RealMeRom Search \nDevice : {device} \nSystem : {system} \nSize : {size} \nRelease Date : {r_date} \nDownload : {ch_}udl {file_url}" - await message.edit(final_) \ No newline at end of file + await message.edit(final_) From a1f4740a0dc65f80127cf87cdc95e52bdc690ff8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 11:34:17 +0530 Subject: [PATCH 020/106] Update music_player.py --- music_player.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/music_player.py b/music_player.py index dff8056..2e762a9 100644 --- a/music_player.py +++ b/music_player.py @@ -26,7 +26,6 @@ s = [] s_dict = {} -group_call = GroupCall(None, play_on_repeat=False) GPC = {} @friday_on_cmd( @@ -124,7 +123,7 @@ async def ski_p(client, message): async def play_m(client, message): global s global s_dict - group_call.client = client + group_call = GPC.get((message.chat.id, client.me.id)) u_s = await edit_or_reply(message, "`Processing..`") if message.reply_to_message: if message.reply_to_message.audio: @@ -184,7 +183,16 @@ async def play_m(client, message): if not raw_file_name: return await u_s.edit("`FFmpeg Failed To Convert Song To raw Format. Please Give Valid File.`") os.remove(audio_original) - if not group_call.is_connected: + if not group_call: + group_call = GroupCall(client, play_on_repeat=False) + GPC[(message.chat.id, client.me.id)] = group_call + try: + await group_call.start(message.chat.id) + except BaseException as e: + return await u_s.edit(f"**Error While Joining VC:** `{e}`") + group_call.input_filename = raw_file_name + return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") + elif not group_call.is_connected: try: await group_call.start(message.chat.id) except BaseException as e: @@ -205,7 +213,7 @@ async def play_m(client, message): async def convert_to_raw(audio_original, raw_file_name): try: ffmpeg.input(audio_original).output( - raw_file_name, format="s16le", acodec="pcm_s16le", ac=2, ar="48k").overwrite_output().run() + raw_file_name, format="s16le", acodec="pcm_s16le", ac=2, ar="48k", loglevel="error").overwrite_output().run() except: return None return raw_file_name @@ -240,6 +248,7 @@ async def radio_s(client, message): acodec='pcm_s16le', ac=2, ar='48k' + loglevel='error' ).overwrite_output().run_async() FFMPEG_PROCESSES[(message.chat.id, client)] = process await s.edit(f"**📻 Playing :** `{radio_url}`") From 73a43c3a224a0d073535d46dee8bd2c50b00394f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 11:35:52 +0530 Subject: [PATCH 021/106] Update music_player.py --- music_player.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/music_player.py b/music_player.py index 2e762a9..d99aa92 100644 --- a/music_player.py +++ b/music_player.py @@ -247,7 +247,7 @@ async def radio_s(client, message): format='s16le', acodec='pcm_s16le', ac=2, - ar='48k' + ar='48k', loglevel='error' ).overwrite_output().run_async() FFMPEG_PROCESSES[(message.chat.id, client)] = process @@ -269,9 +269,9 @@ async def stop_radio(client, message: Message): else: return await msg.edit("`Is Vc is Connected?`") process = FFMPEG_PROCESSES.get((message.chat.id, client)) + await msg.edit("`Radio Stopped : 📻`") if process: process.send_signal(signal.SIGTERM) - await msg.edit("`Radio Stopped : 📻`") @friday_on_cmd( From 70067d2b9ae51a26bb9dd0ecfebb64039be6a1f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 12:04:33 +0530 Subject: [PATCH 022/106] Update music_player.py --- music_player.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/music_player.py b/music_player.py index d99aa92..f2c1e91 100644 --- a/music_player.py +++ b/music_player.py @@ -51,8 +51,7 @@ async def pl(client, message): sno += 1 song += f"**{sno} ▶** `{i.replace('.raw', '')} | {s_dict[i]['singer']} | {s_dict[i]['dur']}` \n\n" await play.edit(song) - -@group_call.on_playout_ended + async def playout_ended_handler(group_call, filename): global s if os.path.exists(group_call.input_filename): @@ -186,6 +185,7 @@ async def play_m(client, message): if not group_call: group_call = GroupCall(client, play_on_repeat=False) GPC[(message.chat.id, client.me.id)] = group_call + group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) try: await group_call.start(message.chat.id) except BaseException as e: @@ -197,6 +197,7 @@ async def play_m(client, message): await group_call.start(message.chat.id) except BaseException as e: return await u_s.edit(f"**Error While Joining VC:** `{e}`") + group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) group_call.input_filename = raw_file_name return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") else: From 65d8e09ddc55ff1398340cc76987dbcab64d2ad1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 12:07:01 +0530 Subject: [PATCH 023/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index f2c1e91..79df435 100644 --- a/music_player.py +++ b/music_player.py @@ -14,7 +14,7 @@ import calendar from main_startup.core.decorators import friday_on_cmd from main_startup.helper_func.basic_helpers import edit_or_reply, get_text -from pytgcalls import GroupCall +from pytgcalls import GroupCall, GroupCallAction import signal import asyncio import os From ddf7518e1b244549dd15baf47ae1a346469a797f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 12:18:26 +0530 Subject: [PATCH 024/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index 79df435..b87eb65 100644 --- a/music_player.py +++ b/music_player.py @@ -259,7 +259,7 @@ async def radio_s(client, message): is_official=False, cmd_help={"help": "Stop Radio.", "example": "{ch}stop_radio"}, ) -async def stop_radio(client, message: Message): +async def stop_radio(client, message): msg = await edit_or_reply(message, "`Please Wait.`") group_call = RD_.get((message.chat.id, client)) if group_call: From 26677d30937c40c6f6fffc8409e282bfff62bb57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 16:36:35 +0530 Subject: [PATCH 025/106] Update music_player.py --- music_player.py | 49 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/music_player.py b/music_player.py index b87eb65..d729944 100644 --- a/music_player.py +++ b/music_player.py @@ -24,7 +24,6 @@ from youtube_dl import YoutubeDL from youtubesearchpython import SearchVideos -s = [] s_dict = {} GPC = {} @@ -52,23 +51,34 @@ async def pl(client, message): song += f"**{sno} ▶** `{i.replace('.raw', '')} | {s_dict[i]['singer']} | {s_dict[i]['dur']}` \n\n" await play.edit(song) +async def get_chat_(client, chat_): + chat_ = str(chat_) + if chat_.startswith("-100"): + try: + return (await client.get_chat(int(chat_))).id + except ValueError: + return int(chat_.split("-100")[1]) + async def playout_ended_handler(group_call, filename): - global s + chat_ = await get_chat_(client, f"-100{group_call.full_chat.id}") + client_ = group_call.client + s = s_dict.get((chat_, client_)) if os.path.exists(group_call.input_filename): os.remove(group_call.input_filename) if not s: - await client_.send_message( - int(f"-100{group_call.full_chat.id}"), - f"`Finished Playing. Nothing Left Play! Left VC.`", - ) await group_call.stop() return + name = s[0]['raw'].split(".raw")[0] + singer_ = s[0]['singer'] + dur_ = s[0]['dur'] + song_info = f"🎵🎸 Now Playing \nSong : {name_} \nSinger : {singer_} \nDuration : {dur_}" await client_.send_message( - int(f"-100{group_call.full_chat.id}"), f"**Now Playing :** `{str(s[0]).replace('.raw', '')} | {s_dict[s[0]]['singer']} | {s_dict[s[0]]['dur']}` \n\n" + chat_, + song_info ) - holi = s[0] + holi = s[0]['raw'] s.pop(0) - logging.info("Now Playing " + str(holi).replace(".raw", "")) + logging.debug(song_info) group_call.input_filename = holi @friday_on_cmd( @@ -80,6 +90,7 @@ async def ski_p(client, message): m_ = await edit_or_reply(message, "`Please Wait!`") no_t_s = get_text(message) group_call = GPC.get((message.chat.id, client.me.id)) + s = s_dict.get((chat_, client_)) if not group_call: await m_.edit("`Is Group Call Even Connected?`") return @@ -91,15 +102,15 @@ async def ski_p(client, message): if no_t_s == "current": if not s: return await m_.edit("`No Song in List. So Stopping Song is A Smarter Way.`") - next_s = s[0] + next_s = s[0]['raw'] s.pop(0) - name = str(next_s).replace(".raw", "") + name = str(next_s['raw']).split(".raw")[0] prev = group_call.input_filename group_call.input_filename = next_s return await m_.edit(f"`Skipped {prev}. Now Playing {name}!`") else: if not s: - return await m_.edit("`There is No Playlist.`") + return await m_.edit("`There is No Playlist!`") if not no_t_s.isdigit(): return await m_.edit("`Input Should Be In Digits.`") no_t_s = int(no_t_s) @@ -107,7 +118,7 @@ async def ski_p(client, message): return await m_.edit("`0? What?`") no_t_s = int(no_t_s - 1) try: - s_ = s[no_t_s] + s_ = s[no_t_s]['raw'] s.pop(no_t_s) except: return await m_.edit("`Invalid Key.`") @@ -201,13 +212,17 @@ async def play_m(client, message): group_call.input_filename = raw_file_name return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") else: - s.append(raw_file_name) + s_d = s_dict.get((message.chat.id, client)) f_info = {"song name": vid_title, + "raw": raw_file_name, "singer": uploade_r, "dur": dur } - s_dict[raw_file_name] = f_info - return await u_s.edit(f"Added `{vid_title}` To Position `#{len(s)+1}`!") + if s_d: + s_d.append(f_info) + else: + s_dict[(message.chat.id, client)] = [f_info] + return await u_s.edit(f"Added `{vid_title}` To Position `#{len(s_d)+1}`!") @@ -326,6 +341,7 @@ async def kill_vc_(client, message): os.remove(group_call.input_filename) group_call.stop_playout() await edit_or_reply(message, "`Stopped Playing Songs!`") + del GPC[(message.chat.id, client.me.id)] @friday_on_cmd( @@ -379,6 +395,7 @@ async def leave_vc_test(client, message): os.remove(group_call.input_filename) await group_call.stop() await edit_or_reply(message, f"`Left : {message.chat.title} - Vc`") + del GPC[(message.chat.id, client.me.id)] @friday_on_cmd( From d679beff0d2553043978f4461934a0e90c92bd83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 16:40:36 +0530 Subject: [PATCH 026/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index d729944..d8002ec 100644 --- a/music_player.py +++ b/music_player.py @@ -37,6 +37,7 @@ async def pl(client, message): play = await edit_or_reply(message, "`Please Wait!`") song = f"**PlayList in {message.chat.title}** \n" sno = 0 + s = s_dict.get((chat_, client_)) if not group_call: return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") if not s: @@ -131,7 +132,6 @@ async def ski_p(client, message): cmd_help={"help": "Play The Song In VC Directly From Youtube Or Telegram!", "example": "{ch}play_vc (song query)"}, ) async def play_m(client, message): - global s global s_dict group_call = GPC.get((message.chat.id, client.me.id)) u_s = await edit_or_reply(message, "`Processing..`") From e2bc2e21a8ceac5189a09ce2bda169289ec478cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 16:44:04 +0530 Subject: [PATCH 027/106] Update music_player.py --- music_player.py | 1 + 1 file changed, 1 insertion(+) diff --git a/music_player.py b/music_player.py index d8002ec..9eec078 100644 --- a/music_player.py +++ b/music_player.py @@ -222,6 +222,7 @@ async def play_m(client, message): s_d.append(f_info) else: s_dict[(message.chat.id, client)] = [f_info] + s_d = s_dict.get((message.chat.id, client)) return await u_s.edit(f"Added `{vid_title}` To Position `#{len(s_d)+1}`!") From cd83a7372c4d88bdd46caeebc53f504d86b48089 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 17:19:42 +0530 Subject: [PATCH 028/106] Update music_player.py --- music_player.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/music_player.py b/music_player.py index 9eec078..51bb9fc 100644 --- a/music_player.py +++ b/music_player.py @@ -49,7 +49,7 @@ async def pl(client, message): song += f"**Currently Playing :** `{str(group_call.input_filename).replace('.raw', '')}` \n\n" for i in s: sno += 1 - song += f"**{sno} ▶** `{i.replace('.raw', '')} | {s_dict[i]['singer']} | {s_dict[i]['dur']}` \n\n" + song += f"**{sno} ▶** `{i.replace('.raw', '')} | {[i]['singer']} | {[i]['dur']}` \n\n" await play.edit(song) async def get_chat_(client, chat_): @@ -61,8 +61,8 @@ async def get_chat_(client, chat_): return int(chat_.split("-100")[1]) async def playout_ended_handler(group_call, filename): - chat_ = await get_chat_(client, f"-100{group_call.full_chat.id}") client_ = group_call.client + chat_ = await get_chat_(client_, f"-100{group_call.full_chat.id}") s = s_dict.get((chat_, client_)) if os.path.exists(group_call.input_filename): os.remove(group_call.input_filename) @@ -72,7 +72,7 @@ async def playout_ended_handler(group_call, filename): name = s[0]['raw'].split(".raw")[0] singer_ = s[0]['singer'] dur_ = s[0]['dur'] - song_info = f"🎵🎸 Now Playing \nSong : {name_} \nSinger : {singer_} \nDuration : {dur_}" + song_info = f"🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_}" await client_.send_message( chat_, song_info From 1b8ec4766b47e51b2038569f51103eed2290570c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 17:21:58 +0530 Subject: [PATCH 029/106] Update music_player.py --- music_player.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/music_player.py b/music_player.py index 51bb9fc..11a5c4f 100644 --- a/music_player.py +++ b/music_player.py @@ -13,7 +13,7 @@ import time import calendar from main_startup.core.decorators import friday_on_cmd -from main_startup.helper_func.basic_helpers import edit_or_reply, get_text +from main_startup.helper_func.basic_helpers import edit_or_reply, get_text, humanbytes from pytgcalls import GroupCall, GroupCallAction import signal import asyncio @@ -72,12 +72,13 @@ async def playout_ended_handler(group_call, filename): name = s[0]['raw'].split(".raw")[0] singer_ = s[0]['singer'] dur_ = s[0]['dur'] - song_info = f"🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_}" + holi = s[0]['raw'] + file_size = humanbytes(os.stat(holi).st_size) + song_info = f"🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_} \n📂 Size : {file_size}" await client_.send_message( chat_, song_info ) - holi = s[0]['raw'] s.pop(0) logging.debug(song_info) group_call.input_filename = holi From f5a07d7b53cde05c28231da838f1f797be4d0f43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 17:25:30 +0530 Subject: [PATCH 030/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index 11a5c4f..4663385 100644 --- a/music_player.py +++ b/music_player.py @@ -49,7 +49,7 @@ async def pl(client, message): song += f"**Currently Playing :** `{str(group_call.input_filename).replace('.raw', '')}` \n\n" for i in s: sno += 1 - song += f"**{sno} ▶** `{i.replace('.raw', '')} | {[i]['singer']} | {[i]['dur']}` \n\n" + song += f"**{sno} ▶** `{i.replace('.raw', '')} | {i['singer']} | {i['dur']}` \n\n" await play.edit(song) async def get_chat_(client, chat_): From f6e75ebfaeebc39b87d3b2f672a4d7d8d65334c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 17:33:51 +0530 Subject: [PATCH 031/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index 4663385..cd6441f 100644 --- a/music_player.py +++ b/music_player.py @@ -37,7 +37,7 @@ async def pl(client, message): play = await edit_or_reply(message, "`Please Wait!`") song = f"**PlayList in {message.chat.title}** \n" sno = 0 - s = s_dict.get((chat_, client_)) + s = s_dict.get((message.chat.id, client)) if not group_call: return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") if not s: From af12769ece911df1c73ce21a7af9d8e92d78454b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 17:42:46 +0530 Subject: [PATCH 032/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index cd6441f..e2ef18e 100644 --- a/music_player.py +++ b/music_player.py @@ -49,7 +49,7 @@ async def pl(client, message): song += f"**Currently Playing :** `{str(group_call.input_filename).replace('.raw', '')}` \n\n" for i in s: sno += 1 - song += f"**{sno} ▶** `{i.replace('.raw', '')} | {i['singer']} | {i['dur']}` \n\n" + song += f"**{sno} ▶** `{str(i).replace('.raw', '')} | {i['singer']} | {i['dur']}` \n\n" await play.edit(song) async def get_chat_(client, chat_): From b78f0ffc669f3c56557c8fd4b35938280273de6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 19:28:48 +0530 Subject: [PATCH 033/106] Update music_player.py --- music_player.py | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/music_player.py b/music_player.py index e2ef18e..4d333b1 100644 --- a/music_player.py +++ b/music_player.py @@ -37,7 +37,7 @@ async def pl(client, message): play = await edit_or_reply(message, "`Please Wait!`") song = f"**PlayList in {message.chat.title}** \n" sno = 0 - s = s_dict.get((message.chat.id, client)) + s = s_dict.get((message.chat.id, client.me.id)) if not group_call: return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") if not s: @@ -63,13 +63,13 @@ async def get_chat_(client, chat_): async def playout_ended_handler(group_call, filename): client_ = group_call.client chat_ = await get_chat_(client_, f"-100{group_call.full_chat.id}") - s = s_dict.get((chat_, client_)) + s = s_dict.get((chat_, client_.me.id)) if os.path.exists(group_call.input_filename): os.remove(group_call.input_filename) if not s: await group_call.stop() return - name = s[0]['raw'].split(".raw")[0] + name_ = s[0]['song_name'] singer_ = s[0]['singer'] dur_ = s[0]['dur'] holi = s[0]['raw'] @@ -92,7 +92,7 @@ async def ski_p(client, message): m_ = await edit_or_reply(message, "`Please Wait!`") no_t_s = get_text(message) group_call = GPC.get((message.chat.id, client.me.id)) - s = s_dict.get((chat_, client_)) + s = s_dict.get((message.chat.id, client.me.id)) if not group_call: await m_.edit("`Is Group Call Even Connected?`") return @@ -106,7 +106,7 @@ async def ski_p(client, message): return await m_.edit("`No Song in List. So Stopping Song is A Smarter Way.`") next_s = s[0]['raw'] s.pop(0) - name = str(next_s['raw']).split(".raw")[0] + name = str(next_s['song_name']) prev = group_call.input_filename group_call.input_filename = next_s return await m_.edit(f"`Skipped {prev}. Now Playing {name}!`") @@ -120,7 +120,7 @@ async def ski_p(client, message): return await m_.edit("`0? What?`") no_t_s = int(no_t_s - 1) try: - s_ = s[no_t_s]['raw'] + s_ = s[no_t_s]['song_name'] s.pop(no_t_s) except: return await m_.edit("`Invalid Key.`") @@ -133,10 +133,12 @@ async def ski_p(client, message): cmd_help={"help": "Play The Song In VC Directly From Youtube Or Telegram!", "example": "{ch}play_vc (song query)"}, ) async def play_m(client, message): - global s_dict group_call = GPC.get((message.chat.id, client.me.id)) u_s = await edit_or_reply(message, "`Processing..`") - if message.reply_to_message: + input_str = get_text(message) + if not input_str: + if not message.reply_to_message: + return await u_s.edit_text("`Reply To A File To PLay It.`") if message.reply_to_message.audio: await u_s.edit_text("`Please Wait, Let Me Download This File!`") audio = message.reply_to_message.audio @@ -149,7 +151,6 @@ async def play_m(client, message): else: return await u_s.edit("`Reply To A File To PLay It.`") else: - input_str = get_text(message) if not input_str: return await u_s.edit("`Give Me A Song Name. Like Why we lose or Alone.`") search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1) @@ -186,14 +187,14 @@ async def play_m(client, message): with YoutubeDL(opts) as ytdl: ytdl_data = ytdl.extract_info(url, download=True) except Exception as e: - await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") - return + return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") audio_original = f"{ytdl_data['id']}.mp3" raw_file_name = f"{vid_title}.raw" raw_file_name = await convert_to_raw(audio_original, raw_file_name) - if not raw_file_name: - return await u_s.edit("`FFmpeg Failed To Convert Song To raw Format. Please Give Valid File.`") - os.remove(audio_original) + if not os.path.exists(raw_file_name): + return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{raw_file_name}`") + if os.path.exists(audio_original): + os.remove(audio_original) if not group_call: group_call = GroupCall(client, play_on_repeat=False) GPC[(message.chat.id, client.me.id)] = group_call @@ -213,8 +214,8 @@ async def play_m(client, message): group_call.input_filename = raw_file_name return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") else: - s_d = s_dict.get((message.chat.id, client)) - f_info = {"song name": vid_title, + s_d = s_dict.get((message.chat.id, client.me.id)) + f_info = {"song_name": vid_title, "raw": raw_file_name, "singer": uploade_r, "dur": dur @@ -222,8 +223,8 @@ async def play_m(client, message): if s_d: s_d.append(f_info) else: - s_dict[(message.chat.id, client)] = [f_info] - s_d = s_dict.get((message.chat.id, client)) + s_dict[(message.chat.id, client.me.id)] = [f_info] + s_d = s_dict.get((message.chat.id, client.me.id)) return await u_s.edit(f"Added `{vid_title}` To Position `#{len(s_d)+1}`!") @@ -232,8 +233,8 @@ async def convert_to_raw(audio_original, raw_file_name): try: ffmpeg.input(audio_original).output( raw_file_name, format="s16le", acodec="pcm_s16le", ac=2, ar="48k", loglevel="error").overwrite_output().run() - except: - return None + except BaseException as e: + return str(e) return raw_file_name From bdd17e9ccae3f2eacd9f365c866303faca64a0fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 20:13:31 +0530 Subject: [PATCH 034/106] Update music_player.py --- music_player.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/music_player.py b/music_player.py index 4d333b1..b8b01c2 100644 --- a/music_player.py +++ b/music_player.py @@ -49,7 +49,7 @@ async def pl(client, message): song += f"**Currently Playing :** `{str(group_call.input_filename).replace('.raw', '')}` \n\n" for i in s: sno += 1 - song += f"**{sno} ▶** `{str(i).replace('.raw', '')} | {i['singer']} | {i['dur']}` \n\n" + song += f"**{sno} ▶** `{i['song_name']} | {i['singer']} | {i['dur']}` \n\n" await play.edit(song) async def get_chat_(client, chat_): @@ -151,14 +151,11 @@ async def play_m(client, message): else: return await u_s.edit("`Reply To A File To PLay It.`") else: - if not input_str: - return await u_s.edit("`Give Me A Song Name. Like Why we lose or Alone.`") search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1) rt = search.result() - try: - result_s = rt["search_result"] - except: - return await u_s.edit(f"`Song Not Found With Name {input_str}, Please Try Giving Some Other Name.`") + result_s = rt.get("search_result") + if not result_s: + return await u_s.edit(f"`No Song Found Matching With Query - {input_str}, Please Try Giving Some Other Name.`") url = result_s[0]["link"] dur = result_s[0]["duration"] vid_title = result_s[0]["title"] @@ -175,8 +172,7 @@ async def play_m(client, message): "postprocessors": [ { "key": "FFmpegExtractAudio", - "preferredcodec": "mp3", - "preferredquality": "720", + "preferredcodec": "mp3" } ], "outtmpl": "%(id)s.mp3", @@ -186,7 +182,7 @@ async def play_m(client, message): try: with YoutubeDL(opts) as ytdl: ytdl_data = ytdl.extract_info(url, download=True) - except Exception as e: + except BaseException as e: return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") audio_original = f"{ytdl_data['id']}.mp3" raw_file_name = f"{vid_title}.raw" @@ -198,11 +194,11 @@ async def play_m(client, message): if not group_call: group_call = GroupCall(client, play_on_repeat=False) GPC[(message.chat.id, client.me.id)] = group_call - group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) try: await group_call.start(message.chat.id) except BaseException as e: return await u_s.edit(f"**Error While Joining VC:** `{e}`") + group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) group_call.input_filename = raw_file_name return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") elif not group_call.is_connected: @@ -227,7 +223,6 @@ async def play_m(client, message): s_d = s_dict.get((message.chat.id, client.me.id)) return await u_s.edit(f"Added `{vid_title}` To Position `#{len(s_d)+1}`!") - async def convert_to_raw(audio_original, raw_file_name): try: @@ -248,6 +243,11 @@ async def convert_to_raw(audio_original, raw_file_name): cmd_help={"help": "Play Radio.", "example": "{ch}pradio (radio url)"}, ) async def radio_s(client, message): + g_s_ = GPC.get((message.chat.id, client.me.id)) + if g_s_: + if g_s_.is_connected: + await group_call.stop() + return del GPC[(message.chat.id, client.me.id)] s = await edit_or_reply(message, "`Please Wait.`") input_filename = f"radio-{message.chat.id}.raw" radio_url = get_text(message) From 494733558a08e9ec840bdbff7c6c0a43525ef4ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 20:16:06 +0530 Subject: [PATCH 035/106] Fix radio --- music_player.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/music_player.py b/music_player.py index b8b01c2..0ada5b8 100644 --- a/music_player.py +++ b/music_player.py @@ -246,18 +246,18 @@ async def radio_s(client, message): g_s_ = GPC.get((message.chat.id, client.me.id)) if g_s_: if g_s_.is_connected: - await group_call.stop() + await g_s_.stop() return del GPC[(message.chat.id, client.me.id)] s = await edit_or_reply(message, "`Please Wait.`") - input_filename = f"radio-{message.chat.id}.raw" + input_filename = f"radio_{message.chat.id}.raw" radio_url = get_text(message) if not radio_url: return await s.edit("`Invalid Radio URL...`") - group_call = RD_.get((message.chat.id, client)) + group_call = RD_.get((message.chat.id, client.me.id)) if not group_call: group_call = GroupCall(client, input_filename, path_to_log_file='') - RD_[(message.chat.id, client)] = group_call - process = FFMPEG_PROCESSES.get((message.chat.id, client)) + RD_[(message.chat.id, client.me.id)] = group_call + process = FFMPEG_PROCESSES.get((message.chat.id, client.me.id)) if process: process.send_signal(signal.SIGTERM) await group_call.start(message.chat.id) @@ -269,7 +269,7 @@ async def radio_s(client, message): ar='48k', loglevel='error' ).overwrite_output().run_async() - FFMPEG_PROCESSES[(message.chat.id, client)] = process + FFMPEG_PROCESSES[(message.chat.id, client.me.id)] = process await s.edit(f"**📻 Playing :** `{radio_url}`") @friday_on_cmd( @@ -279,7 +279,7 @@ async def radio_s(client, message): ) async def stop_radio(client, message): msg = await edit_or_reply(message, "`Please Wait.`") - group_call = RD_.get((message.chat.id, client)) + group_call = RD_.get((message.chat.id, client.me.id)) if group_call: if group_call.is_connected: await group_call.stop() @@ -287,7 +287,7 @@ async def stop_radio(client, message): return await msg.edit("`Is Vc is Connected?`") else: return await msg.edit("`Is Vc is Connected?`") - process = FFMPEG_PROCESSES.get((message.chat.id, client)) + process = FFMPEG_PROCESSES.get((message.chat.id, client.me.id)) await msg.edit("`Radio Stopped : 📻`") if process: process.send_signal(signal.SIGTERM) From f67e39762370f857e03d545ae6312b3e4142d21b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 21:02:26 +0530 Subject: [PATCH 036/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index 0ada5b8..32569ff 100644 --- a/music_player.py +++ b/music_player.py @@ -247,7 +247,7 @@ async def radio_s(client, message): if g_s_: if g_s_.is_connected: await g_s_.stop() - return del GPC[(message.chat.id, client.me.id)] + del GPC[(message.chat.id, client.me.id)] s = await edit_or_reply(message, "`Please Wait.`") input_filename = f"radio_{message.chat.id}.raw" radio_url = get_text(message) From f1a226ae1689eb47a2d0e4c7d599f12ab1432400 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 21:47:20 +0530 Subject: [PATCH 037/106] Update music_player.py --- music_player.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/music_player.py b/music_player.py index 32569ff..804a46b 100644 --- a/music_player.py +++ b/music_player.py @@ -63,10 +63,13 @@ async def get_chat_(client, chat_): async def playout_ended_handler(group_call, filename): client_ = group_call.client chat_ = await get_chat_(client_, f"-100{group_call.full_chat.id}") + print(s_dict) s = s_dict.get((chat_, client_.me.id)) + print(chat) if os.path.exists(group_call.input_filename): os.remove(group_call.input_filename) if not s: + print('no') await group_call.stop() return name_ = s[0]['song_name'] From 8704735e0105643a0226e04b1580d52655b5fcb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 21:55:09 +0530 Subject: [PATCH 038/106] Update music_player.py --- music_player.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/music_player.py b/music_player.py index 804a46b..f690d08 100644 --- a/music_player.py +++ b/music_player.py @@ -1,4 +1,4 @@ -# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. +Of# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. # # This file is part of < https://github.com/DevsExpo/FridayUserBot > project, # and is released under the "GNU v3.0 License Agreement". @@ -65,7 +65,7 @@ async def playout_ended_handler(group_call, filename): chat_ = await get_chat_(client_, f"-100{group_call.full_chat.id}") print(s_dict) s = s_dict.get((chat_, client_.me.id)) - print(chat) + print(chat_) if os.path.exists(group_call.input_filename): os.remove(group_call.input_filename) if not s: From 06d8032cc99f9cdf23c81f66a7ba8653aa6e19a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 21:56:57 +0530 Subject: [PATCH 039/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index f690d08..442138a 100644 --- a/music_player.py +++ b/music_player.py @@ -1,4 +1,4 @@ -Of# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. +# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. # # This file is part of < https://github.com/DevsExpo/FridayUserBot > project, # and is released under the "GNU v3.0 License Agreement". From b8193e1bbb01699ec59f254690f6adedce24b78e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 9 Jun 2021 22:17:56 +0530 Subject: [PATCH 040/106] Update music_player.py --- music_player.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/music_player.py b/music_player.py index 442138a..34fcd34 100644 --- a/music_player.py +++ b/music_player.py @@ -62,14 +62,13 @@ async def get_chat_(client, chat_): async def playout_ended_handler(group_call, filename): client_ = group_call.client - chat_ = await get_chat_(client_, f"-100{group_call.full_chat.id}") - print(s_dict) + chat_ = ('-' + str(await get_chat_(client_, f"-100{group_call.full_chat.id}"))) + chat_ = int(chat_) s = s_dict.get((chat_, client_.me.id)) print(chat_) if os.path.exists(group_call.input_filename): os.remove(group_call.input_filename) if not s: - print('no') await group_call.stop() return name_ = s[0]['song_name'] From 3dbed2261b58392044c6ba3290e25315ea468371 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Thu, 10 Jun 2021 09:35:37 +0530 Subject: [PATCH 041/106] Update music_player.py --- music_player.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/music_player.py b/music_player.py index 34fcd34..d45fa7f 100644 --- a/music_player.py +++ b/music_player.py @@ -58,7 +58,9 @@ async def get_chat_(client, chat_): try: return (await client.get_chat(int(chat_))).id except ValueError: - return int(chat_.split("-100")[1]) + _i = "-" + str(chat_.split("-100")[1]) + _i = (await client.get_chat(int(_i))).id + return int(_i) async def playout_ended_handler(group_call, filename): client_ = group_call.client @@ -76,7 +78,7 @@ async def playout_ended_handler(group_call, filename): dur_ = s[0]['dur'] holi = s[0]['raw'] file_size = humanbytes(os.stat(holi).st_size) - song_info = f"🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_} \n📂 Size : {file_size}" + song_info = f"🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_} \n📂 Size : {file_size}" await client_.send_message( chat_, song_info @@ -149,7 +151,7 @@ async def play_m(client, message): uploade_r = message.reply_to_message.audio.performer or "Unknown Artist." dura_ = message.reply_to_message.audio.duration dur = datetime.timedelta(seconds=dura_) - raw_file_name = f"{audio.file_name}.raw" if audio.file_name else f"{audio.title}.raw" + #raw_file_name = f"{audio.file_name}.raw" if audio.file_name else f"{audio.title}.raw" else: return await u_s.edit("`Reply To A File To PLay It.`") else: @@ -187,7 +189,10 @@ async def play_m(client, message): except BaseException as e: return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") audio_original = f"{ytdl_data['id']}.mp3" - raw_file_name = f"{vid_title}.raw" + #raw_file_name = f"{vid_title}.raw" + import uuid + id = uuid.uuid1() + raw_file_name = f"{id.node}.raw" raw_file_name = await convert_to_raw(audio_original, raw_file_name) if not os.path.exists(raw_file_name): return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{raw_file_name}`") From da9ba2fb862b998d1f5b2ec59e43b93136f0660e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 06:38:40 +0530 Subject: [PATCH 042/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index d45fa7f..6d57f58 100644 --- a/music_player.py +++ b/music_player.py @@ -64,7 +64,7 @@ async def get_chat_(client, chat_): async def playout_ended_handler(group_call, filename): client_ = group_call.client - chat_ = ('-' + str(await get_chat_(client_, f"-100{group_call.full_chat.id}"))) + chat_ = await get_chat_(client_, f"-100{group_call.full_chat.id}") chat_ = int(chat_) s = s_dict.get((chat_, client_.me.id)) print(chat_) From 6581c977ca30de5b279f9eca2dd0ba2e6e1746b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 06:48:56 +0530 Subject: [PATCH 043/106] Update music_player.py --- music_player.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/music_player.py b/music_player.py index 6d57f58..8420987 100644 --- a/music_player.py +++ b/music_player.py @@ -42,7 +42,7 @@ async def pl(client, message): return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") if not s: if group_call.is_connected: - return await play.edit(f"**Currently Playing :** `{str(group_call.input_filename).replace('.raw', '')}`") + return await play.edit(f"**Currently Playing :** `{group_call.song_name}`") else: return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") if group_call.is_connected: @@ -110,8 +110,9 @@ async def ski_p(client, message): return await m_.edit("`No Song in List. So Stopping Song is A Smarter Way.`") next_s = s[0]['raw'] s.pop(0) - name = str(next_s['song_name']) + name = str(s[0]['song_name']) prev = group_call.input_filename + group_call.song_name = name group_call.input_filename = next_s return await m_.edit(f"`Skipped {prev}. Now Playing {name}!`") else: @@ -207,6 +208,7 @@ async def play_m(client, message): return await u_s.edit(f"**Error While Joining VC:** `{e}`") group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) group_call.input_filename = raw_file_name + group_call.song_name = vid_title return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") elif not group_call.is_connected: try: @@ -215,6 +217,7 @@ async def play_m(client, message): return await u_s.edit(f"**Error While Joining VC:** `{e}`") group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) group_call.input_filename = raw_file_name + group_call.song_name = vid_title return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") else: s_d = s_dict.get((message.chat.id, client.me.id)) From 0970f01d8f94bbc66bfd8577b3109541a04ea63e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 08:16:31 +0530 Subject: [PATCH 044/106] Update music_player.py --- music_player.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/music_player.py b/music_player.py index 8420987..6a030d0 100644 --- a/music_player.py +++ b/music_player.py @@ -46,7 +46,7 @@ async def pl(client, message): else: return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") if group_call.is_connected: - song += f"**Currently Playing :** `{str(group_call.input_filename).replace('.raw', '')}` \n\n" + song += f"**Currently Playing :** `{group_call.song_name}` \n\n" for i in s: sno += 1 song += f"**{sno} ▶** `{i['song_name']} | {i['singer']} | {i['dur']}` \n\n" @@ -190,7 +190,6 @@ async def play_m(client, message): except BaseException as e: return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") audio_original = f"{ytdl_data['id']}.mp3" - #raw_file_name = f"{vid_title}.raw" import uuid id = uuid.uuid1() raw_file_name = f"{id.node}.raw" @@ -202,20 +201,20 @@ async def play_m(client, message): if not group_call: group_call = GroupCall(client, play_on_repeat=False) GPC[(message.chat.id, client.me.id)] = group_call + group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) try: await group_call.start(message.chat.id) except BaseException as e: return await u_s.edit(f"**Error While Joining VC:** `{e}`") - group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) group_call.input_filename = raw_file_name group_call.song_name = vid_title return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") elif not group_call.is_connected: + group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) try: await group_call.start(message.chat.id) except BaseException as e: return await u_s.edit(f"**Error While Joining VC:** `{e}`") - group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) group_call.input_filename = raw_file_name group_call.song_name = vid_title return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") From e1b639dff4fd90f4babf3cee2ac3c6753614c78b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 08:57:33 +0530 Subject: [PATCH 045/106] Update music_player.py --- music_player.py | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/music_player.py b/music_player.py index 6a030d0..a030b53 100644 --- a/music_player.py +++ b/music_player.py @@ -17,6 +17,7 @@ from pytgcalls import GroupCall, GroupCallAction import signal import asyncio +import uuid import os import time import requests @@ -83,9 +84,9 @@ async def playout_ended_handler(group_call, filename): chat_, song_info ) - s.pop(0) logging.debug(song_info) group_call.input_filename = holi + s.pop(0) @friday_on_cmd( ["skip_vc"], @@ -138,6 +139,8 @@ async def ski_p(client, message): cmd_help={"help": "Play The Song In VC Directly From Youtube Or Telegram!", "example": "{ch}play_vc (song query)"}, ) async def play_m(client, message): + r_id = uuid.uuid1() + raw_file_name = f"{r_id.node}.raw" group_call = GPC.get((message.chat.id, client.me.id)) u_s = await edit_or_reply(message, "`Processing..`") input_str = get_text(message) @@ -152,7 +155,6 @@ async def play_m(client, message): uploade_r = message.reply_to_message.audio.performer or "Unknown Artist." dura_ = message.reply_to_message.audio.duration dur = datetime.timedelta(seconds=dura_) - #raw_file_name = f"{audio.file_name}.raw" if audio.file_name else f"{audio.title}.raw" else: return await u_s.edit("`Reply To A File To PLay It.`") else: @@ -190,12 +192,10 @@ async def play_m(client, message): except BaseException as e: return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") audio_original = f"{ytdl_data['id']}.mp3" - import uuid - id = uuid.uuid1() - raw_file_name = f"{id.node}.raw" - raw_file_name = await convert_to_raw(audio_original, raw_file_name) - if not os.path.exists(raw_file_name): - return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{raw_file_name}`") + try: + raw_file_name = await convert_to_raw(audio_original, raw_file_name) + except BaseException as e: + return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{e}`") if os.path.exists(audio_original): os.remove(audio_original) if not group_call: @@ -234,11 +234,8 @@ async def play_m(client, message): async def convert_to_raw(audio_original, raw_file_name): - try: - ffmpeg.input(audio_original).output( - raw_file_name, format="s16le", acodec="pcm_s16le", ac=2, ar="48k", loglevel="error").overwrite_output().run() - except BaseException as e: - return str(e) + ffmpeg.input(audio_original).output( + raw_file_name, format="s16le", acodec="pcm_s16le", ac=2, ar="48k", loglevel="error").overwrite_output().run_async() return raw_file_name From 10ed7d1ec939919a8a55d8406e05b0267edc1a93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 09:03:29 +0530 Subject: [PATCH 046/106] Update music_player.py --- music_player.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/music_player.py b/music_player.py index a030b53..2f6460e 100644 --- a/music_player.py +++ b/music_player.py @@ -193,11 +193,9 @@ async def play_m(client, message): return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") audio_original = f"{ytdl_data['id']}.mp3" try: - raw_file_name = await convert_to_raw(audio_original, raw_file_name) + raw_file = await convert_to_raw(audio_original, raw_file_name) except BaseException as e: return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{e}`") - if os.path.exists(audio_original): - os.remove(audio_original) if not group_call: group_call = GroupCall(client, play_on_repeat=False) GPC[(message.chat.id, client.me.id)] = group_call @@ -206,8 +204,9 @@ async def play_m(client, message): await group_call.start(message.chat.id) except BaseException as e: return await u_s.edit(f"**Error While Joining VC:** `{e}`") - group_call.input_filename = raw_file_name + group_call.input_filename = raw_file group_call.song_name = vid_title + os.remove(audio_original) return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") elif not group_call.is_connected: group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) @@ -215,13 +214,16 @@ async def play_m(client, message): await group_call.start(message.chat.id) except BaseException as e: return await u_s.edit(f"**Error While Joining VC:** `{e}`") - group_call.input_filename = raw_file_name + group_call.input_filename = raw_file group_call.song_name = vid_title + os.remove(audio_original) return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") else: + group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) s_d = s_dict.get((message.chat.id, client.me.id)) + os.remove(audio_original) f_info = {"song_name": vid_title, - "raw": raw_file_name, + "raw": raw_file, "singer": uploade_r, "dur": dur } From 7325e0e26b93e8130e524aa871fd70bbece81201 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 09:08:10 +0530 Subject: [PATCH 047/106] Update music_player.py --- music_player.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/music_player.py b/music_player.py index 2f6460e..b1acd31 100644 --- a/music_player.py +++ b/music_player.py @@ -209,7 +209,6 @@ async def play_m(client, message): os.remove(audio_original) return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") elif not group_call.is_connected: - group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) try: await group_call.start(message.chat.id) except BaseException as e: @@ -218,8 +217,7 @@ async def play_m(client, message): group_call.song_name = vid_title os.remove(audio_original) return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") - else: - group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) + elif group_call.is_connected: s_d = s_dict.get((message.chat.id, client.me.id)) os.remove(audio_original) f_info = {"song_name": vid_title, From 4e908360715739c990d29c42df84f45dce07352a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 09:21:18 +0530 Subject: [PATCH 048/106] Update music_player.py --- music_player.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/music_player.py b/music_player.py index b1acd31..75850fc 100644 --- a/music_player.py +++ b/music_player.py @@ -206,7 +206,6 @@ async def play_m(client, message): return await u_s.edit(f"**Error While Joining VC:** `{e}`") group_call.input_filename = raw_file group_call.song_name = vid_title - os.remove(audio_original) return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") elif not group_call.is_connected: try: @@ -215,11 +214,9 @@ async def play_m(client, message): return await u_s.edit(f"**Error While Joining VC:** `{e}`") group_call.input_filename = raw_file group_call.song_name = vid_title - os.remove(audio_original) return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") elif group_call.is_connected: s_d = s_dict.get((message.chat.id, client.me.id)) - os.remove(audio_original) f_info = {"song_name": vid_title, "raw": raw_file, "singer": uploade_r, @@ -238,7 +235,6 @@ async def convert_to_raw(audio_original, raw_file_name): raw_file_name, format="s16le", acodec="pcm_s16le", ac=2, ar="48k", loglevel="error").overwrite_output().run_async() return raw_file_name - RD_ = {} FFMPEG_PROCESSES = {} @@ -249,11 +245,6 @@ async def convert_to_raw(audio_original, raw_file_name): cmd_help={"help": "Play Radio.", "example": "{ch}pradio (radio url)"}, ) async def radio_s(client, message): - g_s_ = GPC.get((message.chat.id, client.me.id)) - if g_s_: - if g_s_.is_connected: - await g_s_.stop() - del GPC[(message.chat.id, client.me.id)] s = await edit_or_reply(message, "`Please Wait.`") input_filename = f"radio_{message.chat.id}.raw" radio_url = get_text(message) From de27c904331a9be3197fcfe8a39d5ba139d160f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 09:28:10 +0530 Subject: [PATCH 049/106] Fix --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index 75850fc..5e60224 100644 --- a/music_player.py +++ b/music_player.py @@ -198,8 +198,8 @@ async def play_m(client, message): return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{e}`") if not group_call: group_call = GroupCall(client, play_on_repeat=False) - GPC[(message.chat.id, client.me.id)] = group_call group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) + GPC[(message.chat.id, client.me.id)] = group_call try: await group_call.start(message.chat.id) except BaseException as e: From 2b3da0413c236f3cc03dbe21f2891bb9d8c769da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 09:51:28 +0530 Subject: [PATCH 050/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index 5e60224..6cac25d 100644 --- a/music_player.py +++ b/music_player.py @@ -199,13 +199,13 @@ async def play_m(client, message): if not group_call: group_call = GroupCall(client, play_on_repeat=False) group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) - GPC[(message.chat.id, client.me.id)] = group_call try: await group_call.start(message.chat.id) except BaseException as e: return await u_s.edit(f"**Error While Joining VC:** `{e}`") group_call.input_filename = raw_file group_call.song_name = vid_title + GPC[(message.chat.id, client.me.id)] = group_call return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") elif not group_call.is_connected: try: From abcaf1082555050faddaaebf784ef607f158b9b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 10:01:24 +0530 Subject: [PATCH 051/106] Update music_player.py --- music_player.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/music_player.py b/music_player.py index 6cac25d..d5cd025 100644 --- a/music_player.py +++ b/music_player.py @@ -207,14 +207,6 @@ async def play_m(client, message): group_call.song_name = vid_title GPC[(message.chat.id, client.me.id)] = group_call return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") - elif not group_call.is_connected: - try: - await group_call.start(message.chat.id) - except BaseException as e: - return await u_s.edit(f"**Error While Joining VC:** `{e}`") - group_call.input_filename = raw_file - group_call.song_name = vid_title - return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") elif group_call.is_connected: s_d = s_dict.get((message.chat.id, client.me.id)) f_info = {"song_name": vid_title, From 49044585b8000001422328b32a821623d1754cbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 10:04:42 +0530 Subject: [PATCH 052/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index d5cd025..6ddd73e 100644 --- a/music_player.py +++ b/music_player.py @@ -198,13 +198,13 @@ async def play_m(client, message): return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{e}`") if not group_call: group_call = GroupCall(client, play_on_repeat=False) - group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) try: await group_call.start(message.chat.id) except BaseException as e: return await u_s.edit(f"**Error While Joining VC:** `{e}`") group_call.input_filename = raw_file group_call.song_name = vid_title + group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) GPC[(message.chat.id, client.me.id)] = group_call return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") elif group_call.is_connected: From 5d2ffaa140ef439b5f9e7483d3abe817e0a0638d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 11:36:27 +0530 Subject: [PATCH 053/106] Update music_player.py --- music_player.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/music_player.py b/music_player.py index 6ddd73e..3d704cc 100644 --- a/music_player.py +++ b/music_player.py @@ -68,7 +68,6 @@ async def playout_ended_handler(group_call, filename): chat_ = await get_chat_(client_, f"-100{group_call.full_chat.id}") chat_ = int(chat_) s = s_dict.get((chat_, client_.me.id)) - print(chat_) if os.path.exists(group_call.input_filename): os.remove(group_call.input_filename) if not s: @@ -78,6 +77,7 @@ async def playout_ended_handler(group_call, filename): singer_ = s[0]['singer'] dur_ = s[0]['dur'] holi = s[0]['raw'] + s.pop(0) file_size = humanbytes(os.stat(holi).st_size) song_info = f"🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_} \n📂 Size : {file_size}" await client_.send_message( @@ -86,7 +86,6 @@ async def playout_ended_handler(group_call, filename): ) logging.debug(song_info) group_call.input_filename = holi - s.pop(0) @friday_on_cmd( ["skip_vc"], @@ -207,7 +206,7 @@ async def play_m(client, message): group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) GPC[(message.chat.id, client.me.id)] = group_call return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") - elif group_call.is_connected: + else: s_d = s_dict.get((message.chat.id, client.me.id)) f_info = {"song_name": vid_title, "raw": raw_file, From 92e6a9e0b21d455376586dafa8a54e8a75921fc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 12:10:37 +0530 Subject: [PATCH 054/106] Create music_player.py --- music_player.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/music_player.py b/music_player.py index 3d704cc..c80096f 100644 --- a/music_player.py +++ b/music_player.py @@ -192,24 +192,31 @@ async def play_m(client, message): return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") audio_original = f"{ytdl_data['id']}.mp3" try: - raw_file = await convert_to_raw(audio_original, raw_file_name) + raw_file_name = await convert_to_raw(audio_original, raw_file_name) except BaseException as e: return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{e}`") if not group_call: group_call = GroupCall(client, play_on_repeat=False) + GPC[(message.chat.id, client.me.id)] = group_call try: await group_call.start(message.chat.id) except BaseException as e: return await u_s.edit(f"**Error While Joining VC:** `{e}`") - group_call.input_filename = raw_file - group_call.song_name = vid_title group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) - GPC[(message.chat.id, client.me.id)] = group_call + group_call.input_filename = raw_file_name + return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") + elif not group_call.is_connected: + try: + await group_call.start(message.chat.id) + except BaseException as e: + return await u_s.edit(f"**Error While Joining VC:** `{e}`") + group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) + group_call.input_filename = raw_file_name return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") else: s_d = s_dict.get((message.chat.id, client.me.id)) f_info = {"song_name": vid_title, - "raw": raw_file, + "raw": raw_file_name, "singer": uploade_r, "dur": dur } From 49b2da505f88a90c22704862e14b9308f5c453d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 12:18:07 +0530 Subject: [PATCH 055/106] Update music_player.py --- music_player.py | 45 +++++++++++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/music_player.py b/music_player.py index c80096f..808a4b3 100644 --- a/music_player.py +++ b/music_player.py @@ -17,7 +17,6 @@ from pytgcalls import GroupCall, GroupCallAction import signal import asyncio -import uuid import os import time import requests @@ -43,11 +42,11 @@ async def pl(client, message): return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") if not s: if group_call.is_connected: - return await play.edit(f"**Currently Playing :** `{group_call.song_name}`") + return await play.edit(f"**Currently Playing :** `{str(group_call.input_filename).replace('.raw', '')}`") else: return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") if group_call.is_connected: - song += f"**Currently Playing :** `{group_call.song_name}` \n\n" + song += f"**Currently Playing :** `{str(group_call.input_filename).replace('.raw', '')}` \n\n" for i in s: sno += 1 song += f"**{sno} ▶** `{i['song_name']} | {i['singer']} | {i['dur']}` \n\n" @@ -59,15 +58,16 @@ async def get_chat_(client, chat_): try: return (await client.get_chat(int(chat_))).id except ValueError: - _i = "-" + str(chat_.split("-100")[1]) - _i = (await client.get_chat(int(_i))).id - return int(_i) + chat_ = chat_.split("-100")[1] + chat_ = '-' + str(chat_) + return int(chat_) async def playout_ended_handler(group_call, filename): client_ = group_call.client chat_ = await get_chat_(client_, f"-100{group_call.full_chat.id}") chat_ = int(chat_) s = s_dict.get((chat_, client_.me.id)) + print(chat_) if os.path.exists(group_call.input_filename): os.remove(group_call.input_filename) if not s: @@ -77,13 +77,13 @@ async def playout_ended_handler(group_call, filename): singer_ = s[0]['singer'] dur_ = s[0]['dur'] holi = s[0]['raw'] - s.pop(0) file_size = humanbytes(os.stat(holi).st_size) - song_info = f"🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_} \n📂 Size : {file_size}" + song_info = f"🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_} \n📂 Size : {file_size}" await client_.send_message( chat_, song_info ) + s.pop(0) logging.debug(song_info) group_call.input_filename = holi @@ -110,9 +110,8 @@ async def ski_p(client, message): return await m_.edit("`No Song in List. So Stopping Song is A Smarter Way.`") next_s = s[0]['raw'] s.pop(0) - name = str(s[0]['song_name']) + name = str(next_s['song_name']) prev = group_call.input_filename - group_call.song_name = name group_call.input_filename = next_s return await m_.edit(f"`Skipped {prev}. Now Playing {name}!`") else: @@ -138,8 +137,6 @@ async def ski_p(client, message): cmd_help={"help": "Play The Song In VC Directly From Youtube Or Telegram!", "example": "{ch}play_vc (song query)"}, ) async def play_m(client, message): - r_id = uuid.uuid1() - raw_file_name = f"{r_id.node}.raw" group_call = GPC.get((message.chat.id, client.me.id)) u_s = await edit_or_reply(message, "`Processing..`") input_str = get_text(message) @@ -154,6 +151,7 @@ async def play_m(client, message): uploade_r = message.reply_to_message.audio.performer or "Unknown Artist." dura_ = message.reply_to_message.audio.duration dur = datetime.timedelta(seconds=dura_) + raw_file_name = f"{audio.file_name}.raw" if audio.file_name else f"{audio.title}.raw" else: return await u_s.edit("`Reply To A File To PLay It.`") else: @@ -191,10 +189,12 @@ async def play_m(client, message): except BaseException as e: return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") audio_original = f"{ytdl_data['id']}.mp3" - try: - raw_file_name = await convert_to_raw(audio_original, raw_file_name) - except BaseException as e: - return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{e}`") + raw_file_name = f"{vid_title}.raw" + raw_file_name = await convert_to_raw(audio_original, raw_file_name) + if not os.path.exists(raw_file_name): + return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{raw_file_name}`") + if os.path.exists(audio_original): + os.remove(audio_original) if not group_call: group_call = GroupCall(client, play_on_repeat=False) GPC[(message.chat.id, client.me.id)] = group_call @@ -229,10 +229,14 @@ async def play_m(client, message): async def convert_to_raw(audio_original, raw_file_name): - ffmpeg.input(audio_original).output( - raw_file_name, format="s16le", acodec="pcm_s16le", ac=2, ar="48k", loglevel="error").overwrite_output().run_async() + try: + ffmpeg.input(audio_original).output( + raw_file_name, format="s16le", acodec="pcm_s16le", ac=2, ar="48k", loglevel="error").overwrite_output().run() + except BaseException as e: + return str(e) return raw_file_name + RD_ = {} FFMPEG_PROCESSES = {} @@ -243,6 +247,11 @@ async def convert_to_raw(audio_original, raw_file_name): cmd_help={"help": "Play Radio.", "example": "{ch}pradio (radio url)"}, ) async def radio_s(client, message): + g_s_ = GPC.get((message.chat.id, client.me.id)) + if g_s_: + if g_s_.is_connected: + await g_s_.stop() + del GPC[(message.chat.id, client.me.id)] s = await edit_or_reply(message, "`Please Wait.`") input_filename = f"radio_{message.chat.id}.raw" radio_url = get_text(message) From 69f5446e8a4e47d6eb5b714f375143fff3f074cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 12:37:06 +0530 Subject: [PATCH 056/106] Update music_player.py --- music_player.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/music_player.py b/music_player.py index 808a4b3..0eaff89 100644 --- a/music_player.py +++ b/music_player.py @@ -16,6 +16,8 @@ from main_startup.helper_func.basic_helpers import edit_or_reply, get_text, humanbytes from pytgcalls import GroupCall, GroupCallAction import signal +import random +import string import asyncio import os import time @@ -67,7 +69,6 @@ async def playout_ended_handler(group_call, filename): chat_ = await get_chat_(client_, f"-100{group_call.full_chat.id}") chat_ = int(chat_) s = s_dict.get((chat_, client_.me.id)) - print(chat_) if os.path.exists(group_call.input_filename): os.remove(group_call.input_filename) if not s: @@ -77,8 +78,9 @@ async def playout_ended_handler(group_call, filename): singer_ = s[0]['singer'] dur_ = s[0]['dur'] holi = s[0]['raw'] + link = s[0]['url'] file_size = humanbytes(os.stat(holi).st_size) - song_info = f"🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_} \n📂 Size : {file_size}" + song_info = f"🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_} \n📂 Size : {file_size}" await client_.send_message( chat_, song_info @@ -110,7 +112,7 @@ async def ski_p(client, message): return await m_.edit("`No Song in List. So Stopping Song is A Smarter Way.`") next_s = s[0]['raw'] s.pop(0) - name = str(next_s['song_name']) + name = str(s[0]['song_name']) prev = group_call.input_filename group_call.input_filename = next_s return await m_.edit(f"`Skipped {prev}. Now Playing {name}!`") @@ -151,7 +153,9 @@ async def play_m(client, message): uploade_r = message.reply_to_message.audio.performer or "Unknown Artist." dura_ = message.reply_to_message.audio.duration dur = datetime.timedelta(seconds=dura_) - raw_file_name = f"{audio.file_name}.raw" if audio.file_name else f"{audio.title}.raw" + raw_file_name = ''.join([random.choice(string.ascii_lowercase) for i in range(5)]) + ".raw" + #raw_file_name = f"{audio.file_name}.raw" if audio.file_name else f"{audio.title}.raw" + url = message.reply_to_message.link else: return await u_s.edit("`Reply To A File To PLay It.`") else: @@ -189,7 +193,8 @@ async def play_m(client, message): except BaseException as e: return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") audio_original = f"{ytdl_data['id']}.mp3" - raw_file_name = f"{vid_title}.raw" + raw_file_name = ''.join([random.choice(string.ascii_lowercase) for i in range(5)]) + ".raw" + #raw_file_name = f"{vid_title}.raw" raw_file_name = await convert_to_raw(audio_original, raw_file_name) if not os.path.exists(raw_file_name): return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{raw_file_name}`") @@ -218,7 +223,8 @@ async def play_m(client, message): f_info = {"song_name": vid_title, "raw": raw_file_name, "singer": uploade_r, - "dur": dur + "dur": dur, + "url": url } if s_d: s_d.append(f_info) From c1d43e6b2a99cfb70482f71858b2391d6380a458 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Fri, 11 Jun 2021 12:41:33 +0530 Subject: [PATCH 057/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index 0eaff89..aee2bca 100644 --- a/music_player.py +++ b/music_player.py @@ -80,7 +80,7 @@ async def playout_ended_handler(group_call, filename): holi = s[0]['raw'] link = s[0]['url'] file_size = humanbytes(os.stat(holi).st_size) - song_info = f"🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_} \n📂 Size : {file_size}" + song_info = f'🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_} \n📂 Size : {file_size}' await client_.send_message( chat_, song_info From 6ff4bf21d5888ac388f3675daeb20c1c64eb5241 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 10:22:45 +0530 Subject: [PATCH 058/106] Update music_player.py --- music_player.py | 107 ++++++++++++++++++++++++++++++++---------------- 1 file changed, 71 insertions(+), 36 deletions(-) diff --git a/music_player.py b/music_player.py index aee2bca..3df3438 100644 --- a/music_player.py +++ b/music_player.py @@ -10,6 +10,10 @@ import logging import ffmpeg from main_startup import Friday +import functools +import threading +from concurrent.futures import ThreadPoolExecutor +import multiprocessing import time import calendar from main_startup.core.decorators import friday_on_cmd @@ -44,14 +48,14 @@ async def pl(client, message): return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") if not s: if group_call.is_connected: - return await play.edit(f"**Currently Playing :** `{str(group_call.input_filename).replace('.raw', '')}`") + return await play.edit(f"**Currently Playing :** `{group_call.song_name}`") else: return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") if group_call.is_connected: - song += f"**Currently Playing :** `{str(group_call.input_filename).replace('.raw', '')}` \n\n" + song += f"**Currently Playing :** `{group_call.song_name}` \n\n" for i in s: sno += 1 - song += f"**{sno} ▶** `{i['song_name']} | {i['singer']} | {i['dur']}` \n\n" + song += f"**{sno} ▶** [{i['song_name']}]({i['url']}) `| {i['singer']} | {i['dur']}` \n\n" await play.edit(song) async def get_chat_(client, chat_): @@ -73,21 +77,23 @@ async def playout_ended_handler(group_call, filename): os.remove(group_call.input_filename) if not s: await group_call.stop() + del GPC[(message.chat.id, client.me.id)] return name_ = s[0]['song_name'] singer_ = s[0]['singer'] dur_ = s[0]['dur'] - holi = s[0]['raw'] + raw_file = s[0]['raw'] link = s[0]['url'] file_size = humanbytes(os.stat(holi).st_size) song_info = f'🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_} \n📂 Size : {file_size}' await client_.send_message( chat_, + disable_web_page_preview=True, song_info ) s.pop(0) logging.debug(song_info) - group_call.input_filename = holi + group_call.input_filename = raw_file @friday_on_cmd( ["skip_vc"], @@ -113,7 +119,7 @@ async def ski_p(client, message): next_s = s[0]['raw'] s.pop(0) name = str(s[0]['song_name']) - prev = group_call.input_filename + prev = group_call.song_name group_call.input_filename = next_s return await m_.edit(f"`Skipped {prev}. Now Playing {name}!`") else: @@ -131,7 +137,17 @@ async def ski_p(client, message): except: return await m_.edit("`Invalid Key.`") return await m_.edit(f"`Skipped : {s_} At Position #{no_t_s}`") - + +max_workers = multiprocessing.cpu_count() * 5 +exc_ = ThreadPoolExecutor(max_workers=max_workers) + +def run_in_exc(f): + @functools.wraps(f) + async def wrapper(*args, **kwargs): + loop = asyncio.get_running_loop() + return await loop.run_in_executor(exc_, lambda: f(*args, **kwargs)) + return wrapper + @friday_on_cmd( ["play_vc"], @@ -154,11 +170,10 @@ async def play_m(client, message): dura_ = message.reply_to_message.audio.duration dur = datetime.timedelta(seconds=dura_) raw_file_name = ''.join([random.choice(string.ascii_lowercase) for i in range(5)]) + ".raw" - #raw_file_name = f"{audio.file_name}.raw" if audio.file_name else f"{audio.title}.raw" url = message.reply_to_message.link else: return await u_s.edit("`Reply To A File To PLay It.`") - else: + elif "you" : search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1) rt = search.result() result_s = rt.get("search_result") @@ -169,32 +184,11 @@ async def play_m(client, message): vid_title = result_s[0]["title"] yt_id = result_s[0]["id"] uploade_r = result_s[0]["channel"] - opts = { - "format": "bestaudio", - "addmetadata": True, - "key": "FFmpegMetadata", - "writethumbnail": True, - "prefer_ffmpeg": True, - "geo_bypass": True, - "nocheckcertificate": True, - "postprocessors": [ - { - "key": "FFmpegExtractAudio", - "preferredcodec": "mp3" - } - ], - "outtmpl": "%(id)s.mp3", - "quiet": True, - "logtostderr": False, - } try: - with YoutubeDL(opts) as ytdl: - ytdl_data = ytdl.extract_info(url, download=True) + audio_original = await yt_dl(url, client, message) except BaseException as e: - return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") - audio_original = f"{ytdl_data['id']}.mp3" + return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") raw_file_name = ''.join([random.choice(string.ascii_lowercase) for i in range(5)]) + ".raw" - #raw_file_name = f"{vid_title}.raw" raw_file_name = await convert_to_raw(audio_original, raw_file_name) if not os.path.exists(raw_file_name): return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{raw_file_name}`") @@ -233,15 +227,56 @@ async def play_m(client, message): s_d = s_dict.get((message.chat.id, client.me.id)) return await u_s.edit(f"Added `{vid_title}` To Position `#{len(s_d)+1}`!") - -async def convert_to_raw(audio_original, raw_file_name): +@run_in_exc +def convert_to_raw(audio_original, raw_file_name): try: - ffmpeg.input(audio_original).output( - raw_file_name, format="s16le", acodec="pcm_s16le", ac=2, ar="48k", loglevel="error").overwrite_output().run() + ffmpeg.input(audio_original).output(raw_file_name, format="s16le", acodec="pcm_s16le", ac=2, ar="48k", loglevel="error").overwrite_output().run() except BaseException as e: return str(e) return raw_file_name +def edit_msg(client, message, to_edit): + try: + client.loop.create_task(message.edit(to_edit)) + except MessageNotModified: + pass + +def download_progress_hook(d, message, client): + if d['status'] == 'downloading': + done = humanbytes(d.get("downloaded_bytes")) + total = d.get("total_bytes") or d.get("total_bytes_estimate") + total = humanbytes(total) + filesize = humanbytes(total) + eta = d.get("eta") + speed = d.get("_speed_str") + to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {filesize} \nSpeed : {speed} \nETA : {eta} \nDownloaded {done} Out Of {total}" + threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() + +@run_in_exc +def yt_dl(url, client, message): + opts = { + "format": "bestaudio", + "addmetadata": True, + "key": "FFmpegMetadata", + "writethumbnail": True, + "prefer_ffmpeg": True, + "geo_bypass": True, + "progress_hooks": [lambda d: progress_hook(message, client)], + "nocheckcertificate": True, + "postprocessors": [ + { + "key": "FFmpegExtractAudio", + "preferredcodec": "mp3" + } + ], + "outtmpl": "%(id)s.mp3", + "quiet": True, + "logtostderr": False, + } + with YoutubeDL(opts) as ytdl: + ytdl_data = ytdl.extract_info(url, download=True) + file_name = ytdl_data['id'] + ".mp3" + return file_name RD_ = {} FFMPEG_PROCESSES = {} From 11bce790d24ac65f05d0e22e7b7c237de276bc80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 10:25:54 +0530 Subject: [PATCH 059/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index 3df3438..8da62f4 100644 --- a/music_player.py +++ b/music_player.py @@ -173,7 +173,7 @@ async def play_m(client, message): url = message.reply_to_message.link else: return await u_s.edit("`Reply To A File To PLay It.`") - elif "you" : + else: search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1) rt = search.result() result_s = rt.get("search_result") From b86a10df2cccbe06ea7e6f7e6c2dc646f626f3e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 10:30:29 +0530 Subject: [PATCH 060/106] Update music_player.py --- music_player.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/music_player.py b/music_player.py index 8da62f4..b908641 100644 --- a/music_player.py +++ b/music_player.py @@ -88,8 +88,8 @@ async def playout_ended_handler(group_call, filename): song_info = f'🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_} \n📂 Size : {file_size}' await client_.send_message( chat_, + song_info, disable_web_page_preview=True, - song_info ) s.pop(0) logging.debug(song_info) @@ -261,7 +261,7 @@ def yt_dl(url, client, message): "writethumbnail": True, "prefer_ffmpeg": True, "geo_bypass": True, - "progress_hooks": [lambda d: progress_hook(message, client)], + "progress_hooks": [lambda d: download_progress_hook(d, message, client)], "nocheckcertificate": True, "postprocessors": [ { From d48e6f928f826fa2ec2cde925f408c683993d584 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 10:36:42 +0530 Subject: [PATCH 061/106] Update music_player.py --- music_player.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/music_player.py b/music_player.py index b908641..b1c377b 100644 --- a/music_player.py +++ b/music_player.py @@ -17,7 +17,7 @@ import time import calendar from main_startup.core.decorators import friday_on_cmd -from main_startup.helper_func.basic_helpers import edit_or_reply, get_text, humanbytes +from main_startup.helper_func.basic_helpers import edit_or_reply, get_text, humanbytes, time_formatter from pytgcalls import GroupCall, GroupCallAction import signal import random @@ -243,13 +243,12 @@ def edit_msg(client, message, to_edit): def download_progress_hook(d, message, client): if d['status'] == 'downloading': - done = humanbytes(d.get("downloaded_bytes")) + done = humanbytes(int(d.get("downloaded_bytes"))) total = d.get("total_bytes") or d.get("total_bytes_estimate") - total = humanbytes(total) - filesize = humanbytes(total) - eta = d.get("eta") + filesize = humanbytes(int(total)) + eta = time_formatter(int(d.get("eta"))) speed = d.get("_speed_str") - to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {filesize} \nSpeed : {speed} \nETA : {eta} \nDownloaded {done} Out Of {total}" + to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {filesize} \nSpeed : {speed} \nETA : {eta} \nDownloaded {done} Out Of {filesize}" threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() @run_in_exc @@ -275,7 +274,7 @@ def yt_dl(url, client, message): } with YoutubeDL(opts) as ytdl: ytdl_data = ytdl.extract_info(url, download=True) - file_name = ytdl_data['id'] + ".mp3" + file_name = str(ytdl_data['id']) + ".mp3" return file_name RD_ = {} From 9b6caa411bbaeb661cadae5b540e1ee31022f6b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 10:45:53 +0530 Subject: [PATCH 062/106] Update music_player.py --- music_player.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/music_player.py b/music_player.py index b1c377b..667a85a 100644 --- a/music_player.py +++ b/music_player.py @@ -243,11 +243,11 @@ def edit_msg(client, message, to_edit): def download_progress_hook(d, message, client): if d['status'] == 'downloading': - done = humanbytes(int(d.get("downloaded_bytes"))) - total = d.get("total_bytes") or d.get("total_bytes_estimate") + done = humanbytes(int(d.get("downloaded_bytes", 1))) + total = d.get("total_bytes") or d.get("total_bytes_estimate", 1) filesize = humanbytes(int(total)) - eta = time_formatter(int(d.get("eta"))) - speed = d.get("_speed_str") + eta = time_formatter(int(d.get("eta", 1))) + speed = d.get("_speed_str", "N/A") to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {filesize} \nSpeed : {speed} \nETA : {eta} \nDownloaded {done} Out Of {filesize}" threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() From 6d41f94969ccc30b1d5cfec6ead70d05853a08bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 10:54:17 +0530 Subject: [PATCH 063/106] Update music_player.py --- music_player.py | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/music_player.py b/music_player.py index 667a85a..95d17db 100644 --- a/music_player.py +++ b/music_player.py @@ -184,8 +184,9 @@ async def play_m(client, message): vid_title = result_s[0]["title"] yt_id = result_s[0]["id"] uploade_r = result_s[0]["channel"] + start = time.time() try: - audio_original = await yt_dl(url, client, message) + audio_original = await yt_dl(url, client, message, start) except BaseException as e: return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") raw_file_name = ''.join([random.choice(string.ascii_lowercase) for i in range(5)]) + ".raw" @@ -241,18 +242,23 @@ def edit_msg(client, message, to_edit): except MessageNotModified: pass -def download_progress_hook(d, message, client): +def download_progress_hook(d, message, client, start): + diff = now - start + now = time.time() if d['status'] == 'downloading': - done = humanbytes(int(d.get("downloaded_bytes", 1))) - total = d.get("total_bytes") or d.get("total_bytes_estimate", 1) - filesize = humanbytes(int(total)) - eta = time_formatter(int(d.get("eta", 1))) - speed = d.get("_speed_str", "N/A") - to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {filesize} \nSpeed : {speed} \nETA : {eta} \nDownloaded {done} Out Of {filesize}" - threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() + done = d.get("downloaded_bytes") + total = d.get("total_bytes") or d.get("total_bytes_estimate") + if round(diff % 10.00) == 0 or done == total:: + done = humanbytes(int(d.get("downloaded_bytes", 1))) + total = d.get("total_bytes") or d.get("total_bytes_estimate") or 1 + filesize = humanbytes(int(total)) + eta = time_formatter(int(d.get("eta", 1))) + speed = d.get("_speed_str", "N/A") + to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {filesize} \nSpeed : {speed} \nETA : {eta} \nDownloaded {done} Out Of {filesize}" + threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() @run_in_exc -def yt_dl(url, client, message): +def yt_dl(url, client, message, start): opts = { "format": "bestaudio", "addmetadata": True, @@ -260,7 +266,7 @@ def yt_dl(url, client, message): "writethumbnail": True, "prefer_ffmpeg": True, "geo_bypass": True, - "progress_hooks": [lambda d: download_progress_hook(d, message, client)], + "progress_hooks": [lambda d: download_progress_hook(d, message, client, start)], "nocheckcertificate": True, "postprocessors": [ { From 556df5bb54293d5ec3fca445d58d3cc83ef329b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 10:57:24 +0530 Subject: [PATCH 064/106] Update music_player.py --- music_player.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/music_player.py b/music_player.py index 95d17db..c415498 100644 --- a/music_player.py +++ b/music_player.py @@ -248,11 +248,12 @@ def download_progress_hook(d, message, client, start): if d['status'] == 'downloading': done = d.get("downloaded_bytes") total = d.get("total_bytes") or d.get("total_bytes_estimate") - if round(diff % 10.00) == 0 or done == total:: + if round(diff % 10.00) == 0 or done == total: + file_name = d.get("filename") done = humanbytes(int(d.get("downloaded_bytes", 1))) total = d.get("total_bytes") or d.get("total_bytes_estimate") or 1 filesize = humanbytes(int(total)) - eta = time_formatter(int(d.get("eta", 1))) + eta = time_formatter(int(d.get("eta", 12))) speed = d.get("_speed_str", "N/A") to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {filesize} \nSpeed : {speed} \nETA : {eta} \nDownloaded {done} Out Of {filesize}" threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() From 2351f80b53e6243c9592aa2aabb7f313b5fc6ea8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 10:59:36 +0530 Subject: [PATCH 065/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index c415498..cb237e4 100644 --- a/music_player.py +++ b/music_player.py @@ -243,8 +243,8 @@ def edit_msg(client, message, to_edit): pass def download_progress_hook(d, message, client, start): - diff = now - start now = time.time() + diff = now - start if d['status'] == 'downloading': done = d.get("downloaded_bytes") total = d.get("total_bytes") or d.get("total_bytes_estimate") From 9dde54ad8a0a687bd857ad6399d021a745a0f233 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 11:14:47 +0530 Subject: [PATCH 066/106] Update music_player.py --- music_player.py | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/music_player.py b/music_player.py index cb237e4..66a978b 100644 --- a/music_player.py +++ b/music_player.py @@ -246,16 +246,23 @@ def download_progress_hook(d, message, client, start): now = time.time() diff = now - start if d['status'] == 'downloading': - done = d.get("downloaded_bytes") + current = d.get("downloaded_bytes") total = d.get("total_bytes") or d.get("total_bytes_estimate") - if round(diff % 10.00) == 0 or done == total: + if round(diff % 10.00) == 0 or current == total: file_name = d.get("filename") - done = humanbytes(int(d.get("downloaded_bytes", 1))) - total = d.get("total_bytes") or d.get("total_bytes_estimate") or 1 - filesize = humanbytes(int(total)) - eta = time_formatter(int(d.get("eta", 12))) - speed = d.get("_speed_str", "N/A") - to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {filesize} \nSpeed : {speed} \nETA : {eta} \nDownloaded {done} Out Of {filesize}" + percentage = current * 100 / total + speed = current / diff + elapsed_time = round(diff) * 1000 + if elapsed_time == 0: + return + time_to_completion = round((total - current) / speed) * 1000 + eta = elapsed_time + time_to_completion + progress_str = "{0}{1} {2}%\n".format( + "".join(["▰" for i in range(math.floor(percentage / 10))]), + "".join(["▱" for i in range(10 - math.floor(percentage / 10))]), + round(percentage, 2), + ) + to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {humanbytes(total)} \nSpeed : {time_formatter(speed)} \nETA : {time_formatter(eta)} \n`{progress_str}`" threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() @run_in_exc From a1b924f3fecf771aefd82a3a4b5789ee486d604a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 11:16:14 +0530 Subject: [PATCH 067/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index 66a978b..2e7c065 100644 --- a/music_player.py +++ b/music_player.py @@ -84,7 +84,7 @@ async def playout_ended_handler(group_call, filename): dur_ = s[0]['dur'] raw_file = s[0]['raw'] link = s[0]['url'] - file_size = humanbytes(os.stat(holi).st_size) + file_size = humanbytes(os.stat(raw_file).st_size) song_info = f'🎼 Now Playing 🎼 \n🎵 Song : {name_} \n🎸 Singer : {singer_} \n⏲️ Duration : {dur_} \n📂 Size : {file_size}' await client_.send_message( chat_, From efc4f08b57c6cff80fdd5453753580e8328cb3a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 11:19:22 +0530 Subject: [PATCH 068/106] Update music_player.py --- music_player.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/music_player.py b/music_player.py index 2e7c065..8b7e22b 100644 --- a/music_player.py +++ b/music_player.py @@ -7,12 +7,18 @@ # All rights reserved. import os +import math +import os +import shlex +import time +from math import ceil import logging import ffmpeg from main_startup import Friday import functools import threading from concurrent.futures import ThreadPoolExecutor +from pyrogram.errors import FloodWait, MessageNotModified import multiprocessing import time import calendar @@ -241,6 +247,8 @@ def edit_msg(client, message, to_edit): client.loop.create_task(message.edit(to_edit)) except MessageNotModified: pass + except FloodWait as e: + await asyncio.sleep(e.x) def download_progress_hook(d, message, client, start): now = time.time() From 3cdccb168e9d45465a9e0e2280d6799b65bed5e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 11:22:58 +0530 Subject: [PATCH 069/106] Update music_player.py --- music_player.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/music_player.py b/music_player.py index 8b7e22b..dc23dc4 100644 --- a/music_player.py +++ b/music_player.py @@ -248,7 +248,7 @@ def edit_msg(client, message, to_edit): except MessageNotModified: pass except FloodWait as e: - await asyncio.sleep(e.x) + client.loop.create_task(asyncio.sleep(e.x)) def download_progress_hook(d, message, client, start): now = time.time() From d2ae31befb35e3191d968074012424b03dc84c75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 11:41:55 +0530 Subject: [PATCH 070/106] Update music_player.py --- music_player.py | 34 ++++++++++++++-------------------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/music_player.py b/music_player.py index dc23dc4..33ec28a 100644 --- a/music_player.py +++ b/music_player.py @@ -249,29 +249,23 @@ def edit_msg(client, message, to_edit): pass except FloodWait as e: client.loop.create_task(asyncio.sleep(e.x)) + except TypeError: + pass def download_progress_hook(d, message, client, start): - now = time.time() - diff = now - start + elapsed = d.get("elapsed") if d['status'] == 'downloading': - current = d.get("downloaded_bytes") - total = d.get("total_bytes") or d.get("total_bytes_estimate") - if round(diff % 10.00) == 0 or current == total: - file_name = d.get("filename") - percentage = current * 100 / total - speed = current / diff - elapsed_time = round(diff) * 1000 - if elapsed_time == 0: - return - time_to_completion = round((total - current) / speed) * 1000 - eta = elapsed_time + time_to_completion - progress_str = "{0}{1} {2}%\n".format( - "".join(["▰" for i in range(math.floor(percentage / 10))]), - "".join(["▱" for i in range(10 - math.floor(percentage / 10))]), - round(percentage, 2), - ) - to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {humanbytes(total)} \nSpeed : {time_formatter(speed)} \nETA : {time_formatter(eta)} \n`{progress_str}`" - threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() + current = d.get("_downloaded_bytes_str", "Unknown") + total = d.get("_total_bytes_str", "Unknown") + file_name = d.get("filename") + eta = d.get('_eta_str', "N/A") + percent = d.get("_percent_str", "N/A") + speed = d.get("_speed_str", "N/A") + to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {total} \nSpeed : {speed} \nETA : {eta} \nDownload {current} out of {total} (`{percent}`)" + threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() + elif d['status'] == 'finished': + to_edit = f"[Download Complete]" + threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() @run_in_exc def yt_dl(url, client, message, start): From a885d558c162623b2858b610026028b2603f4d2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sat, 12 Jun 2021 11:56:29 +0530 Subject: [PATCH 071/106] Update music_player.py --- music_player.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/music_player.py b/music_player.py index 33ec28a..f1ebe86 100644 --- a/music_player.py +++ b/music_player.py @@ -255,16 +255,16 @@ def edit_msg(client, message, to_edit): def download_progress_hook(d, message, client, start): elapsed = d.get("elapsed") if d['status'] == 'downloading': - current = d.get("_downloaded_bytes_str", "Unknown") - total = d.get("_total_bytes_str", "Unknown") + current = d.get("_downloaded_bytes_str") or humanbytes(d.get("downloaded_bytes", 1)) + total = d.get("_total_bytes_str") or d.get("_total_bytes_estimate_str") file_name = d.get("filename") eta = d.get('_eta_str', "N/A") percent = d.get("_percent_str", "N/A") speed = d.get("_speed_str", "N/A") - to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {total} \nSpeed : {speed} \nETA : {eta} \nDownload {current} out of {total} (`{percent}`)" + to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {total} \nSpeed : {speed} \nETA : {eta} \nDownload {current} out of {total} (__{percent}__)" threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() elif d['status'] == 'finished': - to_edit = f"[Download Complete]" + to_edit = f"`[Download Completed]` in (__{elapsed}__)." threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() @run_in_exc From 15540e5bbb50b5c013047b9287306f1ec4ede85d Mon Sep 17 00:00:00 2001 From: StarkGang Date: Mon, 14 Jun 2021 13:47:17 +0530 Subject: [PATCH 072/106] Nice --- harem.py | 20 ++++---- rom_search.py | 15 +++--- unzip.py | 87 ++++++++++++++++++++++++++++++++++ webtools.py | 129 ++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 237 insertions(+), 14 deletions(-) create mode 100644 unzip.py create mode 100644 webtools.py diff --git a/harem.py b/harem.py index 5ae8683..27eda17 100644 --- a/harem.py +++ b/harem.py @@ -17,6 +17,7 @@ get_text, get_user, iter_chats, + run_in_exc ) from main_startup.helper_func.logger_s import LogIt from plugins import devs_id @@ -102,13 +103,8 @@ async def harem_event(f, client, message): return bool(True) return bool(False) - -harem_event = filters.create(func=harem_event, name="harem_event") -is_harem_enabled = filters.create(func=is_harem_enabled, name="is_harem_enabled") - -@listen(filters.user([int(792028928)]) & ~filters.edited & is_harem_enabled & harem_event & filters.group) -async def harem_catcher(client, message): - img = await message.download() +@run_in_exc +def get_data(img): searchUrl = "https://www.google.com/searchbyimage/upload" file_img = {"encoded_image": (img, open(img, "rb")), "image_content": ""} response = requests.post(searchUrl, files=file_img, allow_redirects=False) @@ -116,7 +112,15 @@ async def harem_catcher(client, message): os.remove(img) if response.status_code == 400: return logging.info("(Waifu Catch Failed) - [Invalid Response]") - fetchUrl = response.headers["Location"] + return response.headers["Location"] + +harem_event = filters.create(func=harem_event, name="harem_event") +is_harem_enabled = filters.create(func=is_harem_enabled, name="is_harem_enabled") + +@listen(filters.user([int(792028928)]) & ~filters.edited & is_harem_enabled & harem_event & filters.group) +async def harem_catcher(client, message): + img = await message.download() + fetchUrl = await get_data(img) match = await ParseSauce(fetchUrl + "&preferences?hl=en&fg=1#languages") guessp = match["best_guess"] if not guessp: diff --git a/rom_search.py b/rom_search.py index 956006c..8bb05ab 100644 --- a/rom_search.py +++ b/rom_search.py @@ -22,13 +22,14 @@ from lxml import etree from main_startup.core.decorators import friday_on_cmd from main_startup.core.startup_helpers import run_cmd -from main_startup.helper_func.basic_helpers import edit_or_reply, get_text +from main_startup.helper_func.basic_helpers import edit_or_reply, get_text, run_in_exc GOOGLE_CHROME_BIN = Config.CHROME_BIN_PATH CHROME_DRIVER = Config.CHROME_DRIVER_PATH ch_ = Config.COMMAND_HANDLER -async def get_url(query: str): +@run_in_exc +def get_url(query: str): url = "https://xiaomifirmwareupdater.com/miui/" chrome_options = Options() chrome_options.add_argument("--headless") @@ -51,7 +52,7 @@ async def get_url(query: str): return None, None, None, None, None, None, None href = bruh.get_attribute('href') driver.quit() - return await fetch_data(href) + return href async def fetch_data(url: str): async with aiohttp.ClientSession() as session: @@ -66,7 +67,8 @@ async def fetch_data(url: str): url = f"https://bigota.d.miui.com/{version}/{package_name}" return url, device_name, version, size, rs_date, type_, package_name -async def realme_rom_search(query: str): +@run_in_exc +def realme_rom_search(query: str): url = "https://realmeupdater.com/" chrome_options = Options() chrome_options.add_argument("--headless") @@ -114,9 +116,10 @@ async def m_(client, message): query = get_text(message) if not query: return await e_.edit("`Please Give Me An Query.`") - url, device_name, version, size, rs_date, type_, package_name = await get_url(query) - if url == None: + href = await get_url(query) + if href == None: return await e_.edit("`No Results Matching You Query.`") + url, device_name, version, size, rs_date, type_, package_name = await fetch_data(href) final_ = f"MIUI Search \nModel : {device_name} \nVersion : {version} \nSize : {size} \nRelease Date : {rs_date} \nType : {type_} \nPackage Name : {package_name} \nDownload : {ch_}udl {url}" await message.edit(final_) diff --git a/unzip.py b/unzip.py new file mode 100644 index 0000000..16799f7 --- /dev/null +++ b/unzip.py @@ -0,0 +1,87 @@ +# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. +# +# This file is part of < https://github.com/DevsExpo/FridayUserBot > project, +# and is released under the "GNU v3.0 License Agreement". +# Please see < https://github.com/DevsExpo/blob/master/LICENSE > +# +# All rights reserved. + +import logging +import os +import pathlib +import time +import time as t +import zipfile +from datetime import datetime + +from main_startup.core.decorators import friday_on_cmd +from main_startup.helper_func.basic_helpers import edit_or_reply, humanbytes + +extracted = "./downloads/extracted/" + + +@friday_on_cmd( + ["unzip"], + cmd_help={ + "help": "Unzip the Zip File!", + "example": "{ch}unzip (reply to zip file)", + }, +) +async def test(client, message): + Pablo = await edit_or_reply(message, "`Processing...`") + if not message.reply_to_message: + await Pablo.edit("`Reply To Zip File To Unzip!`") + return + if not message.reply_to_message.document: + await Pablo.edit("`Reply To Zip File To Unzip!`") + return + if message.reply_to_message.document.mime_type != "application/zip": + await Pablo.edit("`Is That Even A Zip?`") + return + if not os.path.isdir(extracted): + os.makedirs(extracted) + start = datetime.now() + downloaded_file_name = await message.reply_to_message.download() + end = datetime.now() + ms = (end - start).seconds + await Pablo.edit( + "Stored the zip to `{}` in {} seconds.".format(downloaded_file_name, ms) + ) + try: + with zipfile.ZipFile(downloaded_file_name, "r") as zip_ref: + zip_ref.extractall(extracted) + except Exception as e: + await Pablo.edit(f"`Error! Zip Couldn't Extarct Zip. \nTraceBack : {e}`") + return + filename = [] + list(file_list(extracted, filename)) + total_files = len(filename) + failed_s = 0 + await Pablo.edit("`Unzipping, Please Wait!`") + for single_file in filename: + if os.path.exists(single_file): + caption_rts = os.path.basename(single_file) + size = os.stat(single_file).st_size + capt = f"<< **{caption_rts}** [`{humanbytes(size)}`] >>" + try: + await client.send_document( + message.chat.id, single_file, caption=capt, force_document=False + ) + except Exception as e: + logging.info(e) + failed_s += 1 + os.remove(single_file) + await Pablo.edit( + f"`Unzipped And Uploaded {total_files-failed_s} File Out Of {total_files}!`" + ) + os.remove(downloaded_file_name) + + +def file_list(path, lisT): + pathlib.Path(path) + for filepath in pathlib.Path(path).glob("**/*"): + if os.path.isdir(filepath): + file_list(filepath, lisT) + else: + lisT.append(filepath.absolute()) + return lisT \ No newline at end of file diff --git a/webtools.py b/webtools.py new file mode 100644 index 0000000..51ede0f --- /dev/null +++ b/webtools.py @@ -0,0 +1,129 @@ +import os +import time + +import pyshorteners +import requests +from bs4 import BeautifulSoup +from faker import Faker +from faker.providers import internet + +from main_startup.core.decorators import friday_on_cmd +from main_startup.helper_func.basic_helpers import ( + delete_or_pass, + edit_or_reply, + get_text, + progress, +) + + +@friday_on_cmd( + ["fakegen", "fakedata"], + cmd_help={"help": "Generate Random Fake Details", "example": "{ch}fakegen"}, +) +async def gen_fake_details(client, message): + lel = await edit_or_reply(message, "`Processing...`") + fake = Faker() + name = str(fake.name()) + fake.add_provider(internet) + address = str(fake.address()) + ip = fake.ipv4_private() + cc = fake.credit_card_full() + email = fake.ascii_free_email() + job = fake.job() + android = fake.android_platform_token() + pc = fake.chrome() + await lel.edit( + f" Fake Information Generated\nName :-{name}\n\nAddress:-{address}\n\nIP ADDRESS:-{ip}\n\ncredit card:-{cc}\n\nEmail Id:-{email}\n\nJob:-{job}\n\nandroid user agent:-{android}\n\nPc user agent:-{pc}", + parse_mode="HTML", + ) + + +@friday_on_cmd( + ["short"], + cmd_help={"help": "Shorten URL link!", "example": "{ch}short link"}, +) +async def vom(client, message): + event = await edit_or_reply(message, "`Shortening the link.....`") + link = get_text(message) + if not link: + await event.edit( + "``Please Give Me A Valid Input. You Can Check Help Menu To Know More!``" + ) + return + sed = pyshorteners.Shortener() + kek = sed.dagd.short(link) + bestisbest = ( + f"Url Shortened \nGiven Link ➠ {link}\n" + f"Shortened Link ➠ {kek}" + ) + await event.edit(bestisbest) + + +@friday_on_cmd( + ["rmeme", "randomeme"], + cmd_help={"help": "Generate Random Memes!", "example": "{ch}rmeme"}, +) +async def givemememe(client, message): + hmm_s = "https://some-random-api.ml/meme" + r = requests.get(url=hmm_s).json() + image_s = r["image"] + await message.reply_photo(image_s) + await delete_or_pass(message) + + +@friday_on_cmd( + ["binlookup", "bin"], + cmd_help={"help": "Get Details About Bin!", "example": "{ch}bin (bin number)"}, +) +async def nobin(client, message): + stark_m = await edit_or_reply(message, "`Please Wait!`") + bin = get_text(message) + if not bin: + await stark_m.edit( + "`Please Give Me A Valid Input. You Can Check Help Menu To Know More!`" + ) + return + url = f"https://lookup.binlist.net/{bin}" + r = requests.get(url=url) + if r.status_code != 200: + await stark_m.edit("Invalid Bin, Please Give Me A Valid Bin To Check.") + return + jr = r.json() + data_is = ( + f"Bin{bin} \n" + f"Type{jr.get('type', '?')} \n" + f"Scheme{jr.get('scheme', '?')} \n" + f"Brand{jr.get('brand', '?')} \n" + f"Country{jr['country']['name']} {jr['country']['emoji']} \n" + ) + await stark_m.edit(data_is, parse_mode="html") + + +@friday_on_cmd( + ["iban", "ibaninfo"], + cmd_help={"help": "Get Details About IBAN", "example": "{ch}iban (iban here)"}, +) +async def ibanbanem(client, message): + stark_m = await edit_or_reply(message, "`Please Wait!`") + iban = get_text(message) + if not iban: + await stark_m.edit( + "`Please Give Me A Valid Input. You Can Check Help Menu To Know More!`" + ) + return + api = f"https://openiban.com/validate/{iban}?getBIC=true&validateBankCode=true" + r = requests.get(url=api).json() + if r["valid"] is False: + await stark_m.edit("Invalid IBAN, Try Again With A Valid IBAN!") + return + banks = r["bankData"] + kek = ( + f"VALID{r['valid']} \n" + f"IBAN{r['iban']} \n" + f"BANK-CODE{banks['bankCode']} \n" + f"BANK-NAME{banks['name']} \n" + f"ZIP{banks['zip']} \n" + f"CITY{banks['city']} \n" + f"BIC{banks['bic']} \n" + ) + await stark_m.edit(kek, parse_mode="html") \ No newline at end of file From e63aa0abb6bac20de333950dd3f96e8ffbd54d24 Mon Sep 17 00:00:00 2001 From: StarkGang Date: Mon, 14 Jun 2021 21:47:36 +0530 Subject: [PATCH 073/106] N --- Cricket_info.py | 8 ++-- amazon_watch.py | 104 ------------------------------------------------ amazonsearch.py | 11 ++++- carbon.py | 9 +++-- cc_tools.py | 24 +++++------ 5 files changed, 28 insertions(+), 128 deletions(-) delete mode 100644 amazon_watch.py diff --git a/Cricket_info.py b/Cricket_info.py index 29f2649..660cbbe 100644 --- a/Cricket_info.py +++ b/Cricket_info.py @@ -7,7 +7,7 @@ # All rights reserved. -import urllib.request +import aiohttp from main_startup.helper_func.basic_helpers import edit_or_reply, get_text from bs4 import BeautifulSoup from pyrogram import filters @@ -23,7 +23,9 @@ ) async def _(client, message): score_page = "http://static.cricinfo.com/rss/livescores.xml" - page = urllib.request.urlopen(score_page) + async with aiohttp.ClientSession() as session: + async with session.get(score_page) as resp: + page = await resp.text() soup = BeautifulSoup(page, "html.parser") result = soup.find_all("description") Sed = "" @@ -31,7 +33,7 @@ async def _(client, message): Sed += match.get_text() + "\n\n" await edit_or_reply( message, - f"Match information gathered successful\n\n\n{Sed}", + f"Match information Gathered Successfully\n\n\n{Sed}", parse_mode="html", ) diff --git a/amazon_watch.py b/amazon_watch.py deleted file mode 100644 index 869396a..0000000 --- a/amazon_watch.py +++ /dev/null @@ -1,104 +0,0 @@ -# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. -# -# This file is part of < https://github.com/DevsExpo/FridayUserBot > project, -# and is released under the "GNU v3.0 License Agreement". -# Please see < https://github.com/DevsExpo/blob/master/LICENSE > -# -# All rights reserved. - -import requests -from apscheduler.schedulers.asyncio import AsyncIOScheduler -from bs4 import BeautifulSoup -from main_startup import Friday -from main_startup.config_var import Config -from main_startup.core.decorators import friday_on_cmd -from main_startup.helper_func.basic_helpers import edit_or_reply, get_text -from xtraplugins.dB.amazon_price_tracker_db import ( - add_amazon_tracker, - get_all_amazon_trackers, - is_amazon_tracker_in_db, - rmamazon_tracker, -) - - -@friday_on_cmd( - ["atl", "amazontrack"], - is_official=False, - cmd_help={ - "help": "Add Amazon Product To Tracking List!", - "example": "{ch}atl (amazon-url)", - }, -) -async def add_to_db(client, message): - aurl = await edit_or_reply(message, "`Processing..`") - headers = { - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" - } - url = get_text(message) - page = requests.get(url, headers=headers) - soup = BeautifulSoup(page.content, "html.parser") - try: - title = soup.find(id="productTitle").get_text() - price = soup.find(id="priceblock_ourprice").get_text() - title = title.strip() - price = price[2:].split(",") - except BaseException: - await aurl.edit("`Url is Invalid!`") - return - price = round(float("".join(price))) - if await is_amazon_tracker_in_db(str(url)): - await aurl.edit("`Tracker Already Found In DB. Whats Point in Adding Again?`") - return - await add_amazon_tracker(url, price) - await aurl.edit( - f"**Added To TrackList** \n**Title :** `{title}` \n**Price :** `{price}`" - ) - - -@friday_on_cmd( - ["rmlt", "rmamazontrack"], - is_official=False, - cmd_help={ - "help": "Remove Amazon Product From Tracking List!", - "example": "{ch}rmlt (amazon-url)", - }, -) -async def rm_from_db(client, message): - rmurl = await edit_or_reply(message, "`Processing..`") - url = get_text(message) - if not await is_amazon_tracker_in_db(str(url)): - await rmurl.edit("`This Url Was Not Found In My DB!`") - return - await rmamazon_tracker(str(url)) - await rmurl.edit("`Removed This Product From DB!`") - return - - -async def track_amazon(): - headers = { - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" - } - kk = await get_all_amazon_trackers() - if len(kk) == 0: - return - for ujwal in kk: - page = requests.get(ujwal["amazon_link"], headers=headers) - soup = BeautifulSoup(page.content, "html.parser") - title = soup.find(id="productTitle").get_text() - price = soup.find(id="priceblock_ourprice").get_text() - title = title.strip() - price = price[2:].split(",") - price = round(float("".join(price))) - if int(price) > int(ujwal["price"]): - await Friday.send_message( - Config.LOG_GRP, - f"#Tracker - Price Reduced \nProduct Name : {title} \nCurrent price : {price}", - ) - await rmamazon_tracker(str(ujwal["amazon_link"])) - else: - pass - - -scheduler = AsyncIOScheduler(timezone="Asia/Kolkata") -scheduler.add_job(track_amazon, trigger="cron", hour=13, minute=35) -scheduler.start() \ No newline at end of file diff --git a/amazonsearch.py b/amazonsearch.py index d5a0cf6..0d85743 100644 --- a/amazonsearch.py +++ b/amazonsearch.py @@ -6,11 +6,13 @@ # # All rights reserved. -import requests +import aiohttp from main_startup.core.decorators import friday_on_cmd from main_startup.helper_func.basic_helpers import edit_or_reply, get_text + + @friday_on_cmd( ["amsearch"], cmd_help={ @@ -26,7 +28,12 @@ async def _am_search_by_lackhac(client,message): await msg_.edit("`Please, Give Input!`") return product = "" - r = requests.get(f"https://amznsearch.vercel.app/api/?query={query}").json() + url = f"https://amznsearch.vercel.app/api/?query={query}" + async with aiohttp.ClientSession() as session: + resp = await session.get(url) + r = await resp.json() + if not r: + return await msg_.edit("`No Results Found!`") for products in r: link = products['productLink'] name = products['productName'] diff --git a/carbon.py b/carbon.py index 8837ebd..35eb37d 100644 --- a/carbon.py +++ b/carbon.py @@ -19,13 +19,14 @@ import os from main_startup.core.decorators import friday_on_cmd from main_startup.core.startup_helpers import run_cmd -from main_startup.helper_func.basic_helpers import edit_or_reply, get_text +from main_startup.helper_func.basic_helpers import edit_or_reply, get_text, run_in_exc GOOGLE_CHROME_BIN = Config.CHROME_BIN_PATH CHROME_DRIVER = Config.CHROME_DRIVER_PATH -async def make_carbon(code, driver, lang="auto"): +@run_in_exc +def make_carbon(code, driver, lang="auto"): url = f'https://carbon.now.sh/?l={lang}&code={code}' driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command') params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': './'}} @@ -45,11 +46,10 @@ async def make_carbon(code, driver, lang="auto"): wait.until(EC.visibility_of_element_located((By.XPATH, four_x_path))).click() wait.until(EC.visibility_of_element_located((By.XPATH, png_xpath))).click() file_ = "./carbon.png" - while not os.path.exists(file_): - await asyncio.sleep(1) color_used = wait.until(EC.visibility_of_element_located((By.XPATH, color_used_xpath))).get_attribute("value") return file_, color_used + @friday_on_cmd( ["carbon", "karb"], cmd_help={ @@ -83,5 +83,6 @@ async def karb(client, message): await e_.edit(f"[Selenium] - [Chrome - Driver] - [Carbon] >> {e}") return driver.quit() driver.quit() + await asyncio.sleep(5) await reply_.send_photo(carbon_file, caption=f"Code Carbonized Using Friday \nStyle Used : {value_}") await e_.delete() \ No newline at end of file diff --git a/cc_tools.py b/cc_tools.py index a42d5be..b8ecc1e 100644 --- a/cc_tools.py +++ b/cc_tools.py @@ -23,18 +23,20 @@ get_text, get_user, iter_chats, + run_in_exc ) from main_startup.helper_func.logger_s import LogIt from plugins import devs_id from selenium.webdriver.support.ui import WebDriverWait -from selenium.webdriver.support import expected_conditions +from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By GOOGLE_CHROME_BIN = Config.CHROME_BIN_PATH CHROME_DRIVER = Config.CHROME_DRIVER_PATH -async def namso_gen(bin, no_of_result=15): +@run_in_exc +def namso_gen(bin, no_of_result=15): url = "https://namso-gen.com/" chrome_options = Options() chrome_options.add_argument("--headless") @@ -45,26 +47,18 @@ async def namso_gen(bin, no_of_result=15): chrome_options.add_argument("--disable-gpu") driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) driver.get(url) - # Sleep Until Page is Fully Loaded - await asyncio.sleep(5) w = WebDriverWait(driver, 20) bin_xpath = '//*[@id="main"]/div/div/div[3]/div[1]/form/div[1]/label/input' no_of_r_xpath = '//*[@id="main"]/div/div/div[3]/div[1]/form/div[3]/div[3]/label/input' button_xpath = '/html/body/div/div/div/main/div/div/div[3]/div[1]/form/div[5]/button' - w.until(expected_conditions.presence_of_element_located((By.XPATH, bin_xpath))) - elem = driver.find_element_by_xpath(bin_xpath) - elem.send_keys(bin) - await asyncio.sleep(2) - elem3 = driver.find_element_by_xpath(no_of_r_xpath) + w.until(EC.visibility_of_element_located((By.XPATH, bin_xpath))).send_keys(bin) + elem3 = w.until(EC.visibility_of_element_located((By.XPATH, no_of_r_xpath))) for i in range(2): elem3.send_keys(Keys.BACKSPACE) - await asyncio.sleep(1) - elem3 = driver.find_element_by_xpath(no_of_r_xpath) + elem3 = w.until(EC.visibility_of_element_located((By.XPATH, no_of_r_xpath))) elem3.send_keys(no_of_result) - await asyncio.sleep(2) - driver.find_element_by_xpath(button_xpath).click() - await asyncio.sleep(2) - s = driver.find_elements_by_xpath('//*[@id="result"]')[0].get_attribute("value") + w.until(EC.visibility_of_element_located((By.XPATH, button_xpath))).click() + s = w.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="result"]')))[0].get_attribute("value") driver.quit() return s From 9c6afdcba7d42491aedd5e1d6b4699cd0462626e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Tue, 15 Jun 2021 08:37:09 +0530 Subject: [PATCH 074/106] Update music_player.py --- music_player.py | 33 ++++++++------------------------- 1 file changed, 8 insertions(+), 25 deletions(-) diff --git a/music_player.py b/music_player.py index f1ebe86..b3e49e6 100644 --- a/music_player.py +++ b/music_player.py @@ -23,7 +23,7 @@ import time import calendar from main_startup.core.decorators import friday_on_cmd -from main_startup.helper_func.basic_helpers import edit_or_reply, get_text, humanbytes, time_formatter +from main_startup.helper_func.basic_helpers import edit_or_reply, get_text, humanbytes, time_formatter, run_in_exc from pytgcalls import GroupCall, GroupCallAction import signal import random @@ -143,18 +143,8 @@ async def ski_p(client, message): except: return await m_.edit("`Invalid Key.`") return await m_.edit(f"`Skipped : {s_} At Position #{no_t_s}`") - -max_workers = multiprocessing.cpu_count() * 5 -exc_ = ThreadPoolExecutor(max_workers=max_workers) - -def run_in_exc(f): - @functools.wraps(f) - async def wrapper(*args, **kwargs): - loop = asyncio.get_running_loop() - return await loop.run_in_executor(exc_, lambda: f(*args, **kwargs)) - return wrapper - - + + @friday_on_cmd( ["play_vc"], is_official=False, @@ -196,9 +186,10 @@ async def play_m(client, message): except BaseException as e: return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") raw_file_name = ''.join([random.choice(string.ascii_lowercase) for i in range(5)]) + ".raw" - raw_file_name = await convert_to_raw(audio_original, raw_file_name) - if not os.path.exists(raw_file_name): - return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{raw_file_name}`") + try: + raw_file_name = await convert_to_raw(audio_original, raw_file_name) + except BaseException as e: + return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{e}`") if os.path.exists(audio_original): os.remove(audio_original) if not group_call: @@ -236,10 +227,7 @@ async def play_m(client, message): @run_in_exc def convert_to_raw(audio_original, raw_file_name): - try: - ffmpeg.input(audio_original).output(raw_file_name, format="s16le", acodec="pcm_s16le", ac=2, ar="48k", loglevel="error").overwrite_output().run() - except BaseException as e: - return str(e) + ffmpeg.input(audio_original).output(raw_file_name, format="s16le", acodec="pcm_s16le", ac=2, ar="48k", loglevel="error").overwrite_output().run() return raw_file_name def edit_msg(client, message, to_edit): @@ -253,7 +241,6 @@ def edit_msg(client, message, to_edit): pass def download_progress_hook(d, message, client, start): - elapsed = d.get("elapsed") if d['status'] == 'downloading': current = d.get("_downloaded_bytes_str") or humanbytes(d.get("downloaded_bytes", 1)) total = d.get("_total_bytes_str") or d.get("_total_bytes_estimate_str") @@ -263,9 +250,6 @@ def download_progress_hook(d, message, client, start): speed = d.get("_speed_str", "N/A") to_edit = f"Downloading File \nFile Name : {file_name} \nFile Size : {total} \nSpeed : {speed} \nETA : {eta} \nDownload {current} out of {total} (__{percent}__)" threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() - elif d['status'] == 'finished': - to_edit = f"`[Download Completed]` in (__{elapsed}__)." - threading.Thread(target=edit_msg, args=(client, message, to_edit)).start() @run_in_exc def yt_dl(url, client, message, start): @@ -273,7 +257,6 @@ def yt_dl(url, client, message, start): "format": "bestaudio", "addmetadata": True, "key": "FFmpegMetadata", - "writethumbnail": True, "prefer_ffmpeg": True, "geo_bypass": True, "progress_hooks": [lambda d: download_progress_hook(d, message, client, start)], From 210cb85478f36e1fa5370bf370d6d33db359e124 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Tue, 15 Jun 2021 08:54:12 +0530 Subject: [PATCH 075/106] Update rom_search.py --- rom_search.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/rom_search.py b/rom_search.py index 8bb05ab..dd6e1e7 100644 --- a/rom_search.py +++ b/rom_search.py @@ -41,7 +41,6 @@ def get_url(query: str): driver.get(url) wait = WebDriverWait(driver, 20) wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#miui_filter > label > input"))).send_keys(query) - await asyncio.sleep(5) try: bruh = driver.find_element_by_css_selector("#miui > tbody > tr:nth-child(1) > td:nth-child(8) > a") except NoSuchElementException: @@ -78,7 +77,6 @@ def realme_rom_search(query: str): chrome_options.add_argument("--disable-gpu") driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) driver.get(url) - await asyncio.sleep(5) driver.maximize_window() wait = WebDriverWait(driver, 30) driver.get("https://realmeupdater.com/") From 0e83b80e5168bb6e42af5dc205a92baa0e585b1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Tue, 15 Jun 2021 08:55:19 +0530 Subject: [PATCH 076/106] Update cc_tools.py --- cc_tools.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cc_tools.py b/cc_tools.py index b8ecc1e..b6b7774 100644 --- a/cc_tools.py +++ b/cc_tools.py @@ -58,7 +58,7 @@ def namso_gen(bin, no_of_result=15): elem3 = w.until(EC.visibility_of_element_located((By.XPATH, no_of_r_xpath))) elem3.send_keys(no_of_result) w.until(EC.visibility_of_element_located((By.XPATH, button_xpath))).click() - s = w.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="result"]')))[0].get_attribute("value") + s = w.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="result"]'))).get_attribute("value") driver.quit() return s From 60d3ea05355c8f475e26ec3d27ad5d47317c55a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Tue, 15 Jun 2021 08:56:28 +0530 Subject: [PATCH 077/106] Update carbon.py --- carbon.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/carbon.py b/carbon.py index 35eb37d..583924f 100644 --- a/carbon.py +++ b/carbon.py @@ -84,5 +84,5 @@ async def karb(client, message): return driver.quit() driver.quit() await asyncio.sleep(5) - await reply_.send_photo(carbon_file, caption=f"Code Carbonized Using Friday \nStyle Used : {value_}") - await e_.delete() \ No newline at end of file + await reply_.reply_photo(carbon_file, caption=f"Code Carbonized Using Friday \nStyle Used : {value_}") + await e_.delete() From 5d89e54d5663dc2798ecdac1cf93effbde358890 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Tue, 15 Jun 2021 09:28:39 +0530 Subject: [PATCH 078/106] Update carbon.py --- carbon.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/carbon.py b/carbon.py index 583924f..728e40a 100644 --- a/carbon.py +++ b/carbon.py @@ -79,10 +79,10 @@ async def karb(client, message): driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) try: carbon_file, value_ = await make_carbon(code, driver) + await asyncio.sleep(5) except BaseException as e: await e_.edit(f"[Selenium] - [Chrome - Driver] - [Carbon] >> {e}") return driver.quit() driver.quit() - await asyncio.sleep(5) await reply_.reply_photo(carbon_file, caption=f"Code Carbonized Using Friday \nStyle Used : {value_}") await e_.delete() From 0e25580b5446c246bd6c78b3c872560c5222b767 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Tue, 15 Jun 2021 10:23:23 +0530 Subject: [PATCH 079/106] Update req.txt --- req.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/req.txt b/req.txt index 6815838..7dd98d1 100644 --- a/req.txt +++ b/req.txt @@ -1,6 +1,7 @@ lxml wikipedia pytgcalls +six==1.16.0 mal-api git+https://github.com/StarkGang/maigret git+https://github.com/starkgang/shazamio From 58af4943c3e4ebdb46d5176ceb125bf9592afe77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Tue, 15 Jun 2021 21:50:53 +0530 Subject: [PATCH 080/106] Update req.txt --- req.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/req.txt b/req.txt index 7dd98d1..6815838 100644 --- a/req.txt +++ b/req.txt @@ -1,7 +1,6 @@ lxml wikipedia pytgcalls -six==1.16.0 mal-api git+https://github.com/StarkGang/maigret git+https://github.com/starkgang/shazamio From c122af0b10b51523ad95b2e3355eebaf26c71c2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 16 Jun 2021 11:08:42 +0530 Subject: [PATCH 081/106] Update imdb.py --- imdb.py | 166 +++++++++++++++++++++++--------------------------------- 1 file changed, 67 insertions(+), 99 deletions(-) diff --git a/imdb.py b/imdb.py index 425e3c4..2ff441b 100644 --- a/imdb.py +++ b/imdb.py @@ -8,10 +8,16 @@ from main_startup.core.decorators import friday_on_cmd from main_startup.helper_func.basic_helpers import edit_or_reply, get_text -import requests -import bs4 +import aiohttp +from bs4 import BeautifulSoup +import json import re +async def get_content(url): + async with aiohttp.ClientSession() as session: + r = await session.get(url) + return await r.read() + @friday_on_cmd( ["imdb"], cmd_help={ @@ -21,101 +27,63 @@ ) async def _(client,message): - msgg = get_text(message) - sedlife = await edit_or_reply(message, "```Searching For Movie..```") - if not msgg: - await sedlife.edit("`Dumb Give Me Inpit`") + query = get_text(message) + msg = await edit_or_reply(message, "`Searching For Movie..`") + reply = message.reply_to_message or message + if not query: + await msg.edit("`Please Give Me An Input.`") return - try: - movie_name = msgg - final_name = "+".join(movie_name) - page = requests.get( - "https://www.imdb.com/find?ref_=nv_sr_fn&q=" + final_name + "&s=all" - ) - str(page.status_code) - soup = bs4.BeautifulSoup(page.content, "lxml") - odds = soup.findAll("tr", "odd") - mov_title = odds[0].findNext("td").findNext("td").text - mov_link = ( - "http://www.imdb.com/" + odds[0].findNext("td").findNext("td").a["href"] - ) - page1 = requests.get(mov_link) - soup = bs4.BeautifulSoup(page1.content, "lxml") - if soup.find("div", "poster"): - poster = soup.find("div", "poster").img["src"] - else: - poster = "" - if soup.find("div", "title_wrapper"): - pg = soup.find("div", "title_wrapper").findNext("div").text - mov_details = re.sub(r"\s+", " ", pg) - else: - mov_details = "" - credits = soup.findAll("div", "credit_summary_item") - if len(credits) == 1: - director = credits[0].a.text - writer = "Not available" - stars = "Not available" - elif len(credits) > 2: - director = credits[0].a.text - writer = credits[1].a.text - actors = [] - for x in credits[2].findAll("a"): - actors.append(x.text) - actors.pop() - stars = actors[0] + "," + actors[1] + "," + actors[2] - else: - director = credits[0].a.text - writer = "Not available" - actors = [] - for x in credits[1].findAll("a"): - actors.append(x.text) - actors.pop() - stars = actors[0] + "," + actors[1] + "," + actors[2] - if soup.find("div", "inline canwrap"): - story_line = soup.find("div", "inline canwrap").findAll("p")[0].text - else: - story_line = "Not available" - info = soup.findAll("div", "txt-block") - if info: - mov_country = [] - mov_language = [] - for node in info: - a = node.findAll("a") - for i in a: - if "country_of_origin" in i["href"]: - mov_country.append(i.text) - elif "primary_language" in i["href"]: - mov_language.append(i.text) - if soup.findAll("div", "ratingValue"): - for r in soup.findAll("div", "ratingValue"): - mov_rating = r.strong["title"] - else: - mov_rating = "Not available" - await sedlife.edit( - "" - "Title : " - + mov_title - + "\n" - + mov_details - + "\nRating : " - + mov_rating - + "\nCountry : " - + mov_country[0] - + "\nLanguage : " - + mov_language[0] - + "\nDirector : " - + director - + "\nWriter : " - + writer - + "\nStars : " - + stars - + "\nIMDB Url : " - + mov_link - + "\nStory Line : " - + story_line, - parse_mode="HTML" - ) - except IndexError: - await sedlife.edit("Ploxxx enter **Valid movie name** kthx") - - + url = "https://www.imdb.com/find?q=" + query + "&s=tt&exact=true&ref_=fn_al_tt_ex" + r = await get_content(url) + soup = BeautifulSoup(r, "lxml") + o_ = soup.find("td", {"class": "result_text"}) + if not o_: + return await msg.edit("`No Results Found, Matching Your Query.`") + url = "https://www.imdb.com" + o_.find('a').get('href') + resp = await get_content(url) + b = BeautifulSoup(resp, "lxml") + r_json = json.loads(b.find("script", attrs={"type": "application/ld+json"}).contents[0]) + res_str = "IMDB SEARCH RESULT" + if r_json.get("@type"): + res_str += f"\nType : {r_json['@type']} \n" + if r_json.get("name"): + res_str += f"Name : {r_json['name']} \n" + if r_json.get("contentRating"): + res_str += f"Content Rating : {r_json['contentRating']} \n" + if r_json.get("genre"): + all_genre = r_json['genre'] + genre = "" + for i in all_genre: + genre += f"{i}, " + genre = genre[:-2] + res_str += f"Genre : {genre} \n" + if r_json.get("actor"): + all_actors = r_json['actor'] + actors = "" + for i in all_actors: + actors += f"{i['name']}, " + actors = actors[:-2] + res_str += f"Actors : {actors} \n" + if r_json.get("trailer"): + trailer_url = "https://imdb.com" + r_json['trailer']['embedUrl'] + res_str += f"Trailer : {trailer_url} \n" + if r_json.get("description"): + res_str += f"Description : {r_json['description']} \n" + if r_json.get("keywords"): + keywords = r_json['keywords'].split(",") + key_ = "" + for i in keywords: + i = i.replace(" ", "_") + key_ += f"#{i}, " + key_ = key_[:-2] + res_str += f"Keywords / Tags : {key_} \n" + if r_json.get("datePublished"): + res_str += f"Date Published : {r_json['datePublished']} \n" + if r_json.get("aggregateRating"): + res_str += f"Rating Count : {r_json['aggregateRating']['ratingCount']} \nRating Value : {r_json['aggregateRating']['ratingValue']} \n" + res_str += f"URL : {url}" + thumb = r_json.get('image') + if thumb: + await msg.delete() + return await reply.reply_photo(thumb, caption=res_str) + await msg.edit(res_str) From f4021f3a76f1932bf5eb36f3c27fae5be06e2232 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Wed, 16 Jun 2021 11:23:46 +0530 Subject: [PATCH 082/106] Update imdb.py --- imdb.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imdb.py b/imdb.py index 2ff441b..a651a02 100644 --- a/imdb.py +++ b/imdb.py @@ -33,7 +33,7 @@ async def _(client,message): if not query: await msg.edit("`Please Give Me An Input.`") return - url = "https://www.imdb.com/find?q=" + query + "&s=tt&exact=true&ref_=fn_al_tt_ex" + url = "https://www.imdb.com/find?ref_=nv_sr_fn&q=" + query + "&s=all" r = await get_content(url) soup = BeautifulSoup(r, "lxml") o_ = soup.find("td", {"class": "result_text"}) From 4c9b4195c7ca31cb5f5b04e0fb5e7389c3c327b5 Mon Sep 17 00:00:00 2001 From: chsaiujwal <69893826+chsaiujwal@users.noreply.github.com> Date: Thu, 17 Jun 2021 09:23:49 +0530 Subject: [PATCH 083/106] Create git.py --- git.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 git.py diff --git a/git.py b/git.py new file mode 100644 index 0000000..0484457 --- /dev/null +++ b/git.py @@ -0,0 +1,23 @@ +import logging +import os +import requests +from main_startup.core.decorators import friday_on_cmd +from main_startup.helper_func.basic_helpers import edit_or_reply, get_text + + +@friday_on_cmd( + ["git", "github"], + cmd_help={ + "help": "Search In GitHub", + "example": "{ch}git ", + }, +) +async def git(client, message): + engine = message.Engine + pablo = await edit_or_reply(message, engine.get_string("PROCESSING")) + args = get_text(message) + if not args: + await pablo.edit(engine.get_string("INPUT_REQ").format("Search Text")) + return + + From 77ce13e9dc9a2b5665787b15972aed29ebf9dac6 Mon Sep 17 00:00:00 2001 From: chsaiujwal <69893826+chsaiujwal@users.noreply.github.com> Date: Thu, 17 Jun 2021 09:36:19 +0530 Subject: [PATCH 084/106] Update git.py --- git.py | 46 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/git.py b/git.py index 0484457..5b247a5 100644 --- a/git.py +++ b/git.py @@ -6,7 +6,7 @@ @friday_on_cmd( - ["git", "github"], + ["git"], cmd_help={ "help": "Search In GitHub", "example": "{ch}git ", @@ -19,5 +19,45 @@ async def git(client, message): if not args: await pablo.edit(engine.get_string("INPUT_REQ").format("Search Text")) return - - + r = requests.get("https://api.github.com/search/repositories", params= f"q={args}") + lool = r.json() + if lool.get("total_count")==0: + await pablo.edit(engine.get_string("F_404")) + return + elif lool.get("total_count")==1: + lol = lool.get("items") + qw = lol[0] + txt = f""" +Name: {qw.get("name")} +Full Name: {qw.get("full_name")} +Link: {qw.get("html_url")} +Description: {qw.get("description")} +Language: {qw.get("language")} +Fork Count: {qw.get("forks_count")} +Open Issues: {qw.get("open_issues")} +""" + await pablo.edit(txt) + return + else: + lol = lool.get("items") + qw = lol[0] + txt = f""" +Name: {qw.get("name")} +Full Name: {qw.get("full_name")} +Link: {qw.get("html_url")} +Description: {qw.get("description")} +Language: {qw.get("language")} +Fork Count: {qw.get("forks_count")} +Open Issues: {qw.get("open_issues")} +""" + qw = lol[1] + txt += f""" +Name: {qw.get("name")} +Full Name: {qw.get("full_name")} +Link: {qw.get("html_url")} +Description: {qw.get("description")} +Language: {qw.get("language")} +Fork Count: {qw.get("forks_count")} +Open Issues: {qw.get("open_issues")} +""" + await pablo.edit(qw) From 3747ac6ca96b47d871193c5083dd203053205699 Mon Sep 17 00:00:00 2001 From: chsaiujwal <69893826+chsaiujwal@users.noreply.github.com> Date: Thu, 17 Jun 2021 09:37:22 +0530 Subject: [PATCH 085/106] Update git.py --- git.py | 26 +------------------------- 1 file changed, 1 insertion(+), 25 deletions(-) diff --git a/git.py b/git.py index 5b247a5..44b6e1a 100644 --- a/git.py +++ b/git.py @@ -24,20 +24,6 @@ async def git(client, message): if lool.get("total_count")==0: await pablo.edit(engine.get_string("F_404")) return - elif lool.get("total_count")==1: - lol = lool.get("items") - qw = lol[0] - txt = f""" -Name: {qw.get("name")} -Full Name: {qw.get("full_name")} -Link: {qw.get("html_url")} -Description: {qw.get("description")} -Language: {qw.get("language")} -Fork Count: {qw.get("forks_count")} -Open Issues: {qw.get("open_issues")} -""" - await pablo.edit(txt) - return else: lol = lool.get("items") qw = lol[0] @@ -50,14 +36,4 @@ async def git(client, message): Fork Count: {qw.get("forks_count")} Open Issues: {qw.get("open_issues")} """ - qw = lol[1] - txt += f""" -Name: {qw.get("name")} -Full Name: {qw.get("full_name")} -Link: {qw.get("html_url")} -Description: {qw.get("description")} -Language: {qw.get("language")} -Fork Count: {qw.get("forks_count")} -Open Issues: {qw.get("open_issues")} -""" - await pablo.edit(qw) + await pablo.edit(txt) From 635f85fec99e56dcc3289a00d7a6df6aa100c4c7 Mon Sep 17 00:00:00 2001 From: chsaiujwal <69893826+chsaiujwal@users.noreply.github.com> Date: Thu, 17 Jun 2021 09:37:47 +0530 Subject: [PATCH 086/106] Update git.py --- git.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git.py b/git.py index 44b6e1a..acdebb6 100644 --- a/git.py +++ b/git.py @@ -25,7 +25,7 @@ async def git(client, message): await pablo.edit(engine.get_string("F_404")) return else: - lol = lool.get("items") + lol = lool.get("items") qw = lol[0] txt = f""" Name: {qw.get("name")} From d2a791a2cfb6c9a4045641683d709f928ae295e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Thu, 17 Jun 2021 09:55:09 +0530 Subject: [PATCH 087/106] Update git.py --- git.py | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/git.py b/git.py index acdebb6..a8b8f52 100644 --- a/git.py +++ b/git.py @@ -19,21 +19,31 @@ async def git(client, message): if not args: await pablo.edit(engine.get_string("INPUT_REQ").format("Search Text")) return - r = requests.get("https://api.github.com/search/repositories", params= f"q={args}") + r = requests.get("https://api.github.com/search/repositories", params={"q": args}) lool = r.json() - if lool.get("total_count")==0: + if lool.get("total_count") == 0: await pablo.edit(engine.get_string("F_404")) return else: lol = lool.get("items") qw = lol[0] txt = f""" -Name: {qw.get("name")} -Full Name: {qw.get("full_name")} -Link: {qw.get("html_url")} -Description: {qw.get("description")} -Language: {qw.get("language")} -Fork Count: {qw.get("forks_count")} -Open Issues: {qw.get("open_issues")} +Name : {qw.get("name")} +Full Name : {qw.get("full_name")} +Link : {qw.get("html_url")} +Fork Count : {qw.get("forks_count")} +Open Issues : {qw.get("open_issues")} """ + if qw.get("description"): + txt += f'Description : {qw.get("description")}' + if qw.get("language"): + txt += f'Language : {qw.get("language")}' + if qw.get("size"): + txt += f'Size : {qw.get("size")}' + if qw.get("score"): + txt += f'Score : {qw.get("score")}' + if qw.get("created_at"): + txt += f'Created At : {qw.get("created_at")}' + ìf qw.get("archived") == True: + txt += f'This Project is Archived" await pablo.edit(txt) From 3bc5f78bcf4526293e61eb0a40165b339bc2da3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Thu, 17 Jun 2021 09:56:17 +0530 Subject: [PATCH 088/106] Update git.py --- git.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git.py b/git.py index a8b8f52..f072cb5 100644 --- a/git.py +++ b/git.py @@ -46,4 +46,4 @@ async def git(client, message): txt += f'Created At : {qw.get("created_at")}' ìf qw.get("archived") == True: txt += f'This Project is Archived" - await pablo.edit(txt) + await pablo.edit(txt, disabled_web_preview=True) From 7ff8475eb4cd218ca50dfe026deef50d85f2f079 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Thu, 17 Jun 2021 10:00:47 +0530 Subject: [PATCH 089/106] Update git.py --- git.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git.py b/git.py index f072cb5..61f4981 100644 --- a/git.py +++ b/git.py @@ -44,6 +44,6 @@ async def git(client, message): txt += f'Score : {qw.get("score")}' if qw.get("created_at"): txt += f'Created At : {qw.get("created_at")}' - ìf qw.get("archived") == True: + if qw.get("archived") == True: txt += f'This Project is Archived" await pablo.edit(txt, disabled_web_preview=True) From a8ccc6898ac13ae5745e20514b64fd1cd16ff4f8 Mon Sep 17 00:00:00 2001 From: chsaiujwal <69893826+chsaiujwal@users.noreply.github.com> Date: Thu, 17 Jun 2021 10:05:00 +0530 Subject: [PATCH 090/106] Update git.py --- git.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git.py b/git.py index 61f4981..5591984 100644 --- a/git.py +++ b/git.py @@ -45,5 +45,5 @@ async def git(client, message): if qw.get("created_at"): txt += f'Created At : {qw.get("created_at")}' if qw.get("archived") == True: - txt += f'This Project is Archived" + txt += f"This Project is Archived" await pablo.edit(txt, disabled_web_preview=True) From eacb7cf95a78c16cc509a56fb5537e06dc3039d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Thu, 17 Jun 2021 10:09:26 +0530 Subject: [PATCH 091/106] Update git.py --- git.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git.py b/git.py index 5591984..91889fa 100644 --- a/git.py +++ b/git.py @@ -46,4 +46,4 @@ async def git(client, message): txt += f'Created At : {qw.get("created_at")}' if qw.get("archived") == True: txt += f"This Project is Archived" - await pablo.edit(txt, disabled_web_preview=True) + await pablo.edit(txt, disable_web_preview=True) From 4549ad324307614ce6e21619ba8a832a7c91c396 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Thu, 17 Jun 2021 10:12:35 +0530 Subject: [PATCH 092/106] Rename git.py to github_search.py --- git.py => github_search.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename git.py => github_search.py (100%) diff --git a/git.py b/github_search.py similarity index 100% rename from git.py rename to github_search.py From 4179a976b936143dea46f872fef78d9e0616a1fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Thu, 17 Jun 2021 10:21:53 +0530 Subject: [PATCH 093/106] Update github_search.py --- github_search.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/github_search.py b/github_search.py index 91889fa..0e3fc95 100644 --- a/github_search.py +++ b/github_search.py @@ -1,3 +1,12 @@ +# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. +# +# This file is part of < https://github.com/DevsExpo/FridayUserBot > project, +# and is released under the "GNU v3.0 License Agreement". +# Please see < https://github.com/DevsExpo/blob/master/LICENSE > +# +# All rights reserved. + + import logging import os import requests @@ -46,4 +55,4 @@ async def git(client, message): txt += f'Created At : {qw.get("created_at")}' if qw.get("archived") == True: txt += f"This Project is Archived" - await pablo.edit(txt, disable_web_preview=True) + await pablo.edit(txt, disable_web_page_preview=True) From ccdc5adbe073083bf88d43e939ec6acc7ce381f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Thu, 17 Jun 2021 10:55:53 +0530 Subject: [PATCH 094/106] Update dl_.py --- helper_files/dl_.py | 47 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/helper_files/dl_.py b/helper_files/dl_.py index 3d4facf..8f6d08c 100644 --- a/helper_files/dl_.py +++ b/helper_files/dl_.py @@ -8,14 +8,55 @@ import re import aiohttp +import base64 from fake_useragent import UserAgent from bs4 import BeautifulSoup from lxml import etree +from main_startup.helper_func.basic_helpers import run_in_exc from xtraplugins.helper_files.dl_helpers import api_request, find_between, base64_url_decode, decrypt_attr, base64_to_a32, parse_url class AnyDL: def __init__(self): self.dl_path = "./main_startup/downloads" + + @run_in_exc + def one_dl(self, url): + data_bytes64 = base64.b64encode(bytes(onedrive_link, 'utf-8')) + dbs_ = data_bytes64.decode('utf-8').replace('/','_').replace('+','-').rstrip("=") + fina_url = f"https://api.onedrive.com/v1.0/shares/u!{dbs_}/root/content" + return fina_url + + @run_in_exc + def dropbox_dl(self, url): + url = "https://dl.dropboxusercontent.com" + url.split("https://www.dropbox.com")[1] + return url + + @run_in_exc + def gdrive(self, url): + drive = 'https://drive.google.com' + file_id = '' + if url.find('view') != -1: + file_id = url.split('/')[-2] + elif url.find('open?id=') != -1: + file_id = url.split('open?id=')[1].strip() + elif url.find('uc?id=') != -1: + file_id = url.split('uc?id=')[1].strip() + if file_id == '': + return None + url = f'{drive}/uc?export=download&id={file_id}' + download = requests.get(url, stream=True, allow_redirects=False) + cookies = download.cookies + dl_url = download.headers.get("location") + if not dl_url: + page = BeautifulSoup(download.content, 'lxml') + export = drive + page.find('a', {'id': 'uc-download-url'}).get('href') + name = page.find('span', {'class': 'uc-name-size'}).text + response = requests.get(export, stream=True, allow_redirects=False, cookies=cookies) + dl_url = response.headers['location'] + if 'accounts.google.com' in dl_url: + return None + return dl_url + async def mega_dl(self, url): path = parse_url(url).split('!') @@ -47,7 +88,7 @@ async def media_fire_dl(self, media_fire_url): async with aiohttp.ClientSession(headers=headers) as session: async with session.get(media_fire_url) as resp: if resp.status != 200: - return resp.status + return None b_ = BeautifulSoup(await resp.read(), 'html.parser') dom = etree.HTML(str(b_)) file_url = dom.xpath('//*[@id="downloadButton"]')[0].get("href") @@ -65,7 +106,7 @@ async def anon_files_dl(self, anon_url): async with aiohttp.ClientSession(headers=headers) as session: async with session.get(anon_url) as resp: if resp.status != 200: - return resp.status + return None b_ = BeautifulSoup(await resp.read(), 'lxml') file_url = b_.find("a", {"id": "download-url"}).get("href") file_name = b_.find("h1", {"class": "text-center text-wordwrap"}).text @@ -73,4 +114,4 @@ async def anon_files_dl(self, anon_url): file_size = find_between(r"\(", r"\)", file_size) return file_url, file_size, file_name - \ No newline at end of file + From 187930ed47a790344f9497b5ea9fce5d31a3fbac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Thu, 17 Jun 2021 17:31:08 +0530 Subject: [PATCH 095/106] Update dl_.py --- helper_files/dl_.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/helper_files/dl_.py b/helper_files/dl_.py index 8f6d08c..9fe5cc0 100644 --- a/helper_files/dl_.py +++ b/helper_files/dl_.py @@ -10,6 +10,7 @@ import aiohttp import base64 from fake_useragent import UserAgent +import requests from bs4 import BeautifulSoup from lxml import etree from main_startup.helper_func.basic_helpers import run_in_exc @@ -24,6 +25,9 @@ def one_dl(self, url): data_bytes64 = base64.b64encode(bytes(onedrive_link, 'utf-8')) dbs_ = data_bytes64.decode('utf-8').replace('/','_').replace('+','-').rstrip("=") fina_url = f"https://api.onedrive.com/v1.0/shares/u!{dbs_}/root/content" + r_ = requests.head(fina_url).status_code + if r_ != 200: + return None return fina_url @run_in_exc @@ -41,12 +45,12 @@ def gdrive(self, url): file_id = url.split('open?id=')[1].strip() elif url.find('uc?id=') != -1: file_id = url.split('uc?id=')[1].strip() - if file_id == '': - return None url = f'{drive}/uc?export=download&id={file_id}' download = requests.get(url, stream=True, allow_redirects=False) cookies = download.cookies - dl_url = download.headers.get("location") + dl_url = None + if download.headers: + dl_url = download.headers.get("location") if not dl_url: page = BeautifulSoup(download.content, 'lxml') export = drive + page.find('a', {'id': 'uc-download-url'}).get('href') @@ -55,7 +59,7 @@ def gdrive(self, url): dl_url = response.headers['location'] if 'accounts.google.com' in dl_url: return None - return dl_url + return dl_url, name async def mega_dl(self, url): From ce92c3610cd6828330ce4dc447aab3002dc78373 Mon Sep 17 00:00:00 2001 From: chsaiujwal <69893826+chsaiujwal@users.noreply.github.com> Date: Mon, 21 Jun 2021 16:32:07 +0530 Subject: [PATCH 096/106] Create advice.py --- advice.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 advice.py diff --git a/advice.py b/advice.py new file mode 100644 index 0000000..d8e54d9 --- /dev/null +++ b/advice.py @@ -0,0 +1,19 @@ +from main_startup.core.decorators import friday_on_cmd +from main_startup.helper_func.basic_helpers import edit_or_reply, get_text +import requests + +@friday_on_cmd( + ["advice"], + cmd_help={ + "help": "Gives You Simple Advice", + "example": "{ch}advice", + }, +) +async def advice(client, message): + engine = message.Engine + pablo = await edit_or_reply(message, engine.get_string("PROCESSING")) + r = requests.get("https://api.adviceslip.com/advice") + await pablo.edit(r.json()["slip"]["advice"]) + + + From 194a71b3cec503bf4b29ba4b0b182ec767bc84bd Mon Sep 17 00:00:00 2001 From: chsaiujwal <69893826+chsaiujwal@users.noreply.github.com> Date: Tue, 22 Jun 2021 07:54:37 +0530 Subject: [PATCH 097/106] Create user-agent-info.py --- user-agent-info.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 user-agent-info.py diff --git a/user-agent-info.py b/user-agent-info.py new file mode 100644 index 0000000..e3e6566 --- /dev/null +++ b/user-agent-info.py @@ -0,0 +1,31 @@ +from main_startup.core.decorators import friday_on_cmd +from main_startup.helper_func.basic_helpers import edit_or_reply, get_text +import requests + + +@friday_on_cmd( + ["ua", "user_agent"], + cmd_help={ + "help": "Get Info From user agent", + "example": "{ch}ua (user agent)", + }, +) +async def useragenti(client, message): + engine = message.Engine + pablo = await edit_or_reply(message, engine.get_string("PROCESSING")) + tex_t = get_text(message) + if not tex_t: + await stark.edit(engine.get_string("INPUT_REQ").format("User Agent")) + return + ue = tex_t + data = {"ua" : ue} + r = requests.post("https://api.apicagent.com", data = data) + Lol = r.json() + await pablo.edit(f""" +Browser: {Lol["client"]["name"]} +Browser Version: {Lol["client"]["version"]} +device Brand: {Lol["device"]["brand"]} +device Model: {Lol["device"]["model"]} +OS: {Lol["os"]["name"]} +OS version: {Lol["os"]["version"]} +""") From 43d4779002eb54868f1f5290f926502f2bc5a77a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 4 Jul 2021 11:50:43 +0530 Subject: [PATCH 098/106] Update any_dl.py --- any_dl.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/any_dl.py b/any_dl.py index a44ae28..db7a33d 100644 --- a/any_dl.py +++ b/any_dl.py @@ -194,6 +194,21 @@ async def download_(client, message): dl_client = AnyDL() url = get_text(message) msg = message.reply_to_message or message + if 'drive.google.com' in url: + try: + link = re.findall(r'\bhttps?://drive\.google\.com\S+', url)[0] + except IndexError: + return await s.edit("`No Drive Url Links Found!`") + try: + file_url, file_name = await dl_client.media_fire_dl(url) + except BaseException as e: + return await s.edit(f"**Failed To GET Direct Link ::** `{e}`") + if file_url == None: + return await s.edit(f"**Failed To GET Direct Link**") + file = await download_file(s, file_url, file_name) + caption = f"File Downloaded & Uploaded \nFile Name : {file_name}" + await upload_file(client, msg, s, file, caption) + return os.remove(file) if "mediafire.com" in url: try: link = re.findall(r'\bhttps?://.*mediafire\.com\S+', url)[0] From 9e5179873b4bb494b35bde064a398b80a72e963a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 4 Jul 2021 11:50:52 +0530 Subject: [PATCH 099/106] Update dl_.py --- helper_files/dl_.py | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/helper_files/dl_.py b/helper_files/dl_.py index 9fe5cc0..7d89148 100644 --- a/helper_files/dl_.py +++ b/helper_files/dl_.py @@ -19,21 +19,6 @@ class AnyDL: def __init__(self): self.dl_path = "./main_startup/downloads" - - @run_in_exc - def one_dl(self, url): - data_bytes64 = base64.b64encode(bytes(onedrive_link, 'utf-8')) - dbs_ = data_bytes64.decode('utf-8').replace('/','_').replace('+','-').rstrip("=") - fina_url = f"https://api.onedrive.com/v1.0/shares/u!{dbs_}/root/content" - r_ = requests.head(fina_url).status_code - if r_ != 200: - return None - return fina_url - - @run_in_exc - def dropbox_dl(self, url): - url = "https://dl.dropboxusercontent.com" + url.split("https://www.dropbox.com")[1] - return url @run_in_exc def gdrive(self, url): @@ -61,7 +46,6 @@ def gdrive(self, url): return None return dl_url, name - async def mega_dl(self, url): path = parse_url(url).split('!') if path == None: From 351e732efa41858953f6f4e39611a3c808155a99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 4 Jul 2021 11:51:56 +0530 Subject: [PATCH 100/106] Update advice.py --- advice.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/advice.py b/advice.py index d8e54d9..9d7a103 100644 --- a/advice.py +++ b/advice.py @@ -1,3 +1,11 @@ +# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. +# +# This file is part of < https://github.com/DevsExpo/FridayUserBot > project, +# and is released under the "GNU v3.0 License Agreement". +# Please see < https://github.com/DevsExpo/blob/master/LICENSE > +# +# All rights reserved. + from main_startup.core.decorators import friday_on_cmd from main_startup.helper_func.basic_helpers import edit_or_reply, get_text import requests @@ -14,6 +22,3 @@ async def advice(client, message): pablo = await edit_or_reply(message, engine.get_string("PROCESSING")) r = requests.get("https://api.adviceslip.com/advice") await pablo.edit(r.json()["slip"]["advice"]) - - - From 1e2ec4f8758b122cc601c0be7fe22337960459c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 4 Jul 2021 11:52:30 +0530 Subject: [PATCH 101/106] Update user-agent-info.py --- user-agent-info.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/user-agent-info.py b/user-agent-info.py index e3e6566..393ed0f 100644 --- a/user-agent-info.py +++ b/user-agent-info.py @@ -1,3 +1,11 @@ +# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. +# +# This file is part of < https://github.com/DevsExpo/FridayUserBot > project, +# and is released under the "GNU v3.0 License Agreement". +# Please see < https://github.com/DevsExpo/blob/master/LICENSE > +# +# All rights reserved. + from main_startup.core.decorators import friday_on_cmd from main_startup.helper_func.basic_helpers import edit_or_reply, get_text import requests @@ -15,7 +23,7 @@ async def useragenti(client, message): pablo = await edit_or_reply(message, engine.get_string("PROCESSING")) tex_t = get_text(message) if not tex_t: - await stark.edit(engine.get_string("INPUT_REQ").format("User Agent")) + await pablo.edit(engine.get_string("INPUT_REQ").format("User Agent")) return ue = tex_t data = {"ua" : ue} @@ -24,8 +32,8 @@ async def useragenti(client, message): await pablo.edit(f""" Browser: {Lol["client"]["name"]} Browser Version: {Lol["client"]["version"]} -device Brand: {Lol["device"]["brand"]} -device Model: {Lol["device"]["model"]} +Device Brand: {Lol["device"]["brand"]} +Device Model: {Lol["device"]["model"]} OS: {Lol["os"]["name"]} OS version: {Lol["os"]["version"]} """) From 728cc1adcf4a03fdff9b1614ded79489c6ead347 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 4 Jul 2021 11:52:49 +0530 Subject: [PATCH 102/106] Delete xvideo.py --- xvideo.py | 71 ------------------------------------------------------- 1 file changed, 71 deletions(-) delete mode 100644 xvideo.py diff --git a/xvideo.py b/xvideo.py deleted file mode 100644 index c3ee2b4..0000000 --- a/xvideo.py +++ /dev/null @@ -1,71 +0,0 @@ -import requests -import bs4 - -from main_startup.core.decorators import friday_on_cmd -from main_startup.helper_func.basic_helpers import edit_or_reply, get_text - - -@friday_on_cmd( - ["xvideo"], - cmd_help={ - "help": "Get direct Downloadable", - "example": "{ch}xvideo xvideo_link", - }, -) -async def xvid(client, message): - editer= await edit_or_reply(message, "`Please Wait.....`") - msg = get_text(message) - if not msg: - await editer.edit("`Please Enter Valid Input`") - return - try: - req = requests.get(msg) - soup = bs4.BeautifulSoup(req.content, 'html.parser') - - soups = soup.find("div",{"id":"video-player-bg"}) - link ="" - for a in soups.find_all('a', href=True): - link = a["href"] - await editer.edit(f"HERE IS YOUR LINK:\n`{link}`") - except: - await editer.edit("Something went wrong") - - - - - -@friday_on_cmd( - ["xsearch"], - cmd_help={ - "help": "Xvideo Searcher", - "example": "{ch}xsearch query", - }, -) - -async def xvidsearch(client, message): - editer= await edit_or_reply(message, "`Please Wait.....`") - msg = get_text(message) - if not msg: - await editer.edit("`Please Enter Valid Input`") - return - try: - qu = msg.replace(" ","+") - page= requests.get(f"https://www.xvideos.com/?k={qu}").content - soup = bs4.BeautifulSoup(page, 'html.parser') - col= soup.findAll("div",{"class":"thumb"}) - - links= "" - - for i in col: - a = i.find("a") - link = a.get('href') - - semd = link.split("/")[2] - - links += f"• {semd.upper()}\n" - await editer.edit(links,parse_mode="HTML") - - - except: - await editer.edit("Something Went Wrong") - From 04a53e0964b382ebcd42056d3f19844c4dad3df6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Sun, 4 Jul 2021 11:59:57 +0530 Subject: [PATCH 103/106] Update any_dl.py --- any_dl.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/any_dl.py b/any_dl.py index db7a33d..696989b 100644 --- a/any_dl.py +++ b/any_dl.py @@ -200,7 +200,7 @@ async def download_(client, message): except IndexError: return await s.edit("`No Drive Url Links Found!`") try: - file_url, file_name = await dl_client.media_fire_dl(url) + file_url, file_name = await dl_client.gdrive(url) except BaseException as e: return await s.edit(f"**Failed To GET Direct Link ::** `{e}`") if file_url == None: From feaa746be6d3b92ebfc99c804a087470da80cf33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Thu, 22 Jul 2021 10:41:33 +0530 Subject: [PATCH 104/106] Update req.txt --- req.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/req.txt b/req.txt index 6815838..5d9c258 100644 --- a/req.txt +++ b/req.txt @@ -1,6 +1,6 @@ lxml wikipedia -pytgcalls +pytgcalls[pyrogram] mal-api git+https://github.com/StarkGang/maigret git+https://github.com/starkgang/shazamio From 6e724a8d82c1426b9f9096901df114e03ded3729 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=82=B9=E3=82=BF=E3=83=BC=E3=82=AF=E3=82=AE=E3=83=A3?= =?UTF-8?q?=E3=83=B3=E3=82=B0?= Date: Thu, 22 Jul 2021 10:54:18 +0530 Subject: [PATCH 105/106] Update music_player.py --- music_player.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/music_player.py b/music_player.py index b3e49e6..e932aa9 100644 --- a/music_player.py +++ b/music_player.py @@ -24,7 +24,7 @@ import calendar from main_startup.core.decorators import friday_on_cmd from main_startup.helper_func.basic_helpers import edit_or_reply, get_text, humanbytes, time_formatter, run_in_exc -from pytgcalls import GroupCall, GroupCallAction +from pytgcalls import GroupCallFactory, GroupCallFileAction import signal import random import string @@ -193,13 +193,13 @@ async def play_m(client, message): if os.path.exists(audio_original): os.remove(audio_original) if not group_call: - group_call = GroupCall(client, play_on_repeat=False) + group_call = GroupCallFactory(client).get_file_group_call() GPC[(message.chat.id, client.me.id)] = group_call try: await group_call.start(message.chat.id) except BaseException as e: return await u_s.edit(f"**Error While Joining VC:** `{e}`") - group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) + group_call.add_handler(playout_ended_handler, GroupCallFileAction.PLAYOUT_ENDED) group_call.input_filename = raw_file_name return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") elif not group_call.is_connected: @@ -207,7 +207,7 @@ async def play_m(client, message): await group_call.start(message.chat.id) except BaseException as e: return await u_s.edit(f"**Error While Joining VC:** `{e}`") - group_call.add_handler(playout_ended_handler, GroupCallAction.PLAYOUT_ENDED) + group_call.add_handler(playout_ended_handler, GroupCallFileAction.PLAYOUT_ENDED) group_call.input_filename = raw_file_name return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!") else: From ff32b20115560b7122928751dc16182c0b5d81fd Mon Sep 17 00:00:00 2001 From: Sourcery AI <> Date: Thu, 10 Mar 2022 14:25:05 +0000 Subject: [PATCH 106/106] 'Refactored by Sourcery' --- Cricket_info.py | 4 +- any_dl.py | 87 +++++++++++++++------------- carbon.py | 4 +- cc_tools.py | 12 ++-- collage.py | 12 ++-- fban.py | 40 ++++++------- github_search.py | 2 +- harem.py | 9 +-- helper_files/dl_.py | 6 +- helper_files/dl_helpers.py | 67 +++++++++++----------- imdb.py | 18 ++---- music_player.py | 112 ++++++++++++++++++------------------- rom_search.py | 4 +- shazam.py | 2 +- 14 files changed, 190 insertions(+), 189 deletions(-) diff --git a/Cricket_info.py b/Cricket_info.py index 660cbbe..77ec2bc 100644 --- a/Cricket_info.py +++ b/Cricket_info.py @@ -28,9 +28,7 @@ async def _(client, message): page = await resp.text() soup = BeautifulSoup(page, "html.parser") result = soup.find_all("description") - Sed = "" - for match in result: - Sed += match.get_text() + "\n\n" + Sed = "".join(match.get_text() + "\n\n" for match in result) await edit_or_reply( message, f"Match information Gathered Successfully\n\n\n{Sed}", diff --git a/any_dl.py b/any_dl.py index 696989b..1f5153e 100644 --- a/any_dl.py +++ b/any_dl.py @@ -28,12 +28,12 @@ async def download_file(message, url, file_name): async with aiohttp.ClientSession() as session: async with session.get(url) as r: total_length = r.headers.get('content-length') or r.headers.get("Content-Length") - dl = 0 if total_length is None: f.write(await r.read()) else: total_length = int(total_length) - async for chunk in r.content.iter_chunked(max(int(total_length/500), (1024*1024)*2)): + dl = 0 + async for chunk in r.content.iter_chunked(max(total_length // 500, (1024*1024)*2)): dl += len(chunk) e_ = time.time() diff = e_ - c_ @@ -44,9 +44,23 @@ async def download_file(message, url, file_name): estimated_total_time = elapsed_time + time_to_completion f.write(chunk) progress_str = "{0}{1} {2}%\n".format( - "".join(["▰" for i in range(math.floor(percentage / 10))]), - "".join(["▱" for i in range(10 - math.floor(percentage / 10))]), - round(percentage, 2)) + "".join( + [ + "▰" + for _ in range(math.floor(percentage / 10)) + ] + ), + "".join( + [ + "▱" + for _ in range( + 10 - math.floor(percentage / 10) + ) + ] + ), + round(percentage, 2), + ) + r_ = f"Downloading This File \nFile : {file_name} \nFile Size : {humanbytes(total_length)} \nDownloaded : {humanbytes(dl)} \n{progress_str} \n\nSpeed : {humanbytes(round(speed))}/ps \nETA : {time_formatter(estimated_total_time)}" try: await message.edit(r_) @@ -85,9 +99,7 @@ async def upload_file(client, reply_message, message, file_path, caption): async def send_file(client, r_msg, file, capt, e_msg): c_time = time.time() file_name = os.path.basename(file) - send_as_thumb = False - if os.path.exists("./main_startup/Cache/thumb.jpg"): - send_as_thumb = True + send_as_thumb = bool(os.path.exists("./main_startup/Cache/thumb.jpg")) if file.endswith(image_ext): await r_msg.reply_video( file, @@ -157,24 +169,23 @@ async def send_file(client, r_msg, file, capt, e_msg): progress=progress, progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), ) + elif send_as_thumb: + await r_msg.reply_document( + file, + quote=True, + thumb="./main_startup/Cache/thumb.jpg", + caption=capt, + progress=progress, + progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), + ) else: - if send_as_thumb: - await r_msg.reply_document( - file, - quote=True, - thumb="./main_startup/Cache/thumb.jpg", - caption=capt, - progress=progress, - progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), - ) - else: - await r_msg.reply_document( - file, - quote=True, - caption=capt, - progress=progress, - progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), - ) + await r_msg.reply_document( + file, + quote=True, + caption=capt, + progress=progress, + progress_args=(e_msg, c_time, f"`Uploading {file_name}!`", file_name), + ) def file_list(path, lisT): pathlib.Path(path) @@ -203,8 +214,8 @@ async def download_(client, message): file_url, file_name = await dl_client.gdrive(url) except BaseException as e: return await s.edit(f"**Failed To GET Direct Link ::** `{e}`") - if file_url == None: - return await s.edit(f"**Failed To GET Direct Link**") + if file_url is None: + return await s.edit("**Failed To GET Direct Link**") file = await download_file(s, file_url, file_name) caption = f"File Downloaded & Uploaded \nFile Name : {file_name}" await upload_file(client, msg, s, file, caption) @@ -218,8 +229,8 @@ async def download_(client, message): file_url, file_name, file_size, file_upload_date, caption_, scan_result = await dl_client.media_fire_dl(url) except BaseException as e: return await s.edit(f"**Failed To GET Direct Link ::** `{e}`") - if file_url == None: - return await s.edit(f"**Failed To GET Direct Link**") + if file_url is None: + return await s.edit("**Failed To GET Direct Link**") file = await download_file(s, file_url, file_name) caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size} \nFile Upload Date : {file_upload_date} \nFile Scan Result : {scan_result} \n{caption_}" await upload_file(client, msg, s, file, caption) @@ -235,8 +246,8 @@ async def download_(client, message): file_url, file_name, file_size = await dl_client.mega_dl(link) except BaseException as e: return await s.edit(f"**Failed To GET Direct Link ::** `{e}`") - if file_url == None: - return await s.edit(f"**Failed To GET Direct Link**") + if file_url is None: + return await s.edit("**Failed To GET Direct Link**") file = await download_file(s, file_url, file_name) file_size = humanbytes(file_size) caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size}" @@ -251,12 +262,9 @@ async def download_(client, message): file_url, file_size, file_name = await dl_client.anon_files_dl(link) except BaseException as e: return await s.edit(f"**Failed To GET Direct Link ::** `{e}`") - if file_url == None: - return await s.edit(f"**Failed To GET Direct Link**") + if file_url is None: + return await s.edit("**Failed To GET Direct Link**") file = await download_file(s, file_url, file_name) - caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size}" - await upload_file(client, msg, s, file, caption) - return os.remove(file) else: url_ = url.split('|') if len(url_) != 2: @@ -268,7 +276,8 @@ async def download_(client, message): except BaseException as e: return await s.edit(f"**Failed To Download ::** `{e}`") file_size = humanbytes(os.stat(file).st_size) - caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size}" - await upload_file(client, msg, s, file, caption) - return os.remove(file) + + caption = f"File Downloaded & Uploaded \nFile Name : {file_name} \nFile Size : {file_size}" + await upload_file(client, msg, s, file, caption) + return os.remove(file) diff --git a/carbon.py b/carbon.py index 728e40a..be7e93e 100644 --- a/carbon.py +++ b/carbon.py @@ -35,10 +35,10 @@ def make_carbon(code, driver, lang="auto"): type_ = '//*[@id="__next"]/main/div[2]/div[2]/div[1]/div[1]/div/span[2]' em = "export-menu" png_xpath = '//*[@id="export-png"]' - four_x_path = '//*[@id="__next"]/main/div[2]/div[2]/div[1]/div[3]/div[4]/div[3]/div[2]/div[3]/div/button[3]' + four_x_path = '//*[@id="__next"]/main/div[2]/div[2]/div[1]/div[3]/div[4]/div[3]/div[2]/div[3]/div/button[3]' color_used_xpath = '/html/body/div[1]/main/div[2]/div[2]/div[1]/div[1]/div/span[2]/input' random_int = random.randint(1, 29) - value_ = "downshift-0-item-" + str(random_int) + value_ = f"downshift-0-item-{str(random_int)}" wait = WebDriverWait(driver, 20) wait.until(EC.visibility_of_element_located((By.XPATH, type_))).click() wait.until(EC.visibility_of_element_located((By.ID, value_))).click() diff --git a/cc_tools.py b/cc_tools.py index b6b7774..c6c9745 100644 --- a/cc_tools.py +++ b/cc_tools.py @@ -53,7 +53,7 @@ def namso_gen(bin, no_of_result=15): button_xpath = '/html/body/div/div/div/main/div/div/div[3]/div[1]/form/div[5]/button' w.until(EC.visibility_of_element_located((By.XPATH, bin_xpath))).send_keys(bin) elem3 = w.until(EC.visibility_of_element_located((By.XPATH, no_of_r_xpath))) - for i in range(2): + for _ in range(2): elem3.send_keys(Keys.BACKSPACE) elem3 = w.until(EC.visibility_of_element_located((By.XPATH, no_of_r_xpath))) elem3.send_keys(no_of_result) @@ -97,9 +97,13 @@ async def ns_gen(client, message): await msg.edit(t, parse_mode="md") def stark_finder(to_find, from_find): - if re.search(r"( |^|[^\w])" + re.escape(to_find) + r"( |$|[^\w])", from_find, flags=re.IGNORECASE): - return True - return False + return bool( + re.search( + f"( |^|[^\\w]){re.escape(to_find)}( |$|[^\\w])", + from_find, + flags=re.IGNORECASE, + ) + ) my_code = { 400: "『! Invalid Key !』", diff --git a/collage.py b/collage.py index a9411e7..9ef620b 100644 --- a/collage.py +++ b/collage.py @@ -21,7 +21,7 @@ async def create_s_collage(file_path, filename, width, stark_h): """Create Image Collage""" - img_stark = [filepath for filepath in pathlib.Path(file_path).glob("**/*")] + img_stark = list(pathlib.Path(file_path).glob("**/*")) margin_size = 2 while True: img_stark_list = list(img_stark) @@ -45,10 +45,12 @@ async def create_s_collage(file_path, filename, width, stark_h): stark_h -= 10 else: break - out_lol_h = 0 - for meisnub, sedlife in ujwal_liness: - if sedlife: - out_lol_h += int(stark_h / meisnub) + margin_size + out_lol_h = sum( + int(stark_h / meisnub) + margin_size + for meisnub, sedlife in ujwal_liness + if sedlife + ) + if not out_lol_h: return None final_image = Image.new('RGB', (width, int(out_lol_h)), (35, 35, 35)) diff --git a/fban.py b/fban.py index b136537..5ffbc48 100644 --- a/fban.py +++ b/fban.py @@ -179,32 +179,32 @@ async def fetch_all_fed(client, message): pass await asyncio.sleep(7) sed = (await client.get_history("@MissRose_bot", 1))[0] - if sed.media: - fed_file = await sed.download() - file = open(fed_file, "r") - lines = file.readlines() - for line in lines: - try: - fed_list.append(line[:36]) - except BaseException: - pass - os.remove(fed_file) - else: + if not sed.media: return None + fed_file = await sed.download() + file = open(fed_file, "r") + lines = file.readlines() + for line in lines: + try: + fed_list.append(line[:36]) + except BaseException: + pass + os.remove(fed_file) else: X = ok.text lol = X.splitlines() if "you are the owner" in X.lower(): for lo in lol: - if "you are the owner" not in lo.lower(): - if "you are admin" not in lo.lower(): - if lo[:36] != "": - if not lo.startswith("-"): - fed_list.append(lo[:36]) - else: - fed_list.append(lo[2:38]) + if ( + "you are the owner" not in lo.lower() + and "you are admin" not in lo.lower() + and lo[:36] != "" + ): + if not lo.startswith("-"): + fed_list.append(lo[:36]) + else: + fed_list.append(lo[2:38]) else: Y = X[44:].splitlines() - for lol in Y: - fed_list.append(lol[2:38]) + fed_list.extend(lol[2:38] for lol in Y) return fed_list diff --git a/github_search.py b/github_search.py index 0e3fc95..2cc4953 100644 --- a/github_search.py +++ b/github_search.py @@ -54,5 +54,5 @@ async def git(client, message): if qw.get("created_at"): txt += f'Created At : {qw.get("created_at")}' if qw.get("archived") == True: - txt += f"This Project is Archived" + txt += "This Project is Archived" await pablo.edit(txt, disable_web_page_preview=True) diff --git a/harem.py b/harem.py index 27eda17..c7c574d 100644 --- a/harem.py +++ b/harem.py @@ -87,10 +87,7 @@ async def remove_nsfw(client, message): async def is_harem_enabled(f, client, message): if Config.ENABLE_WAIFU_FOR_ALL_CHATS: return bool(True) - if await is_chat_in_db(int(message.chat.id)): - return bool(True) - else: - return bool(False) + return bool(True) if await is_chat_in_db(int(message.chat.id)) else bool(False) async def harem_event(f, client, message): if not message: @@ -117,11 +114,11 @@ def get_data(img): harem_event = filters.create(func=harem_event, name="harem_event") is_harem_enabled = filters.create(func=is_harem_enabled, name="is_harem_enabled") -@listen(filters.user([int(792028928)]) & ~filters.edited & is_harem_enabled & harem_event & filters.group) +@listen(filters.user([792028928]) & ~filters.edited & is_harem_enabled & harem_event & filters.group) async def harem_catcher(client, message): img = await message.download() fetchUrl = await get_data(img) - match = await ParseSauce(fetchUrl + "&preferences?hl=en&fg=1#languages") + match = await ParseSauce(f'{fetchUrl}&preferences?hl=en&fg=1#languages') guessp = match["best_guess"] if not guessp: return logging.info("(Waifu Catch Failed.) \nERROR : 404: Waifu Not Found.") diff --git a/helper_files/dl_.py b/helper_files/dl_.py index 7d89148..75c3276 100644 --- a/helper_files/dl_.py +++ b/helper_files/dl_.py @@ -33,9 +33,7 @@ def gdrive(self, url): url = f'{drive}/uc?export=download&id={file_id}' download = requests.get(url, stream=True, allow_redirects=False) cookies = download.cookies - dl_url = None - if download.headers: - dl_url = download.headers.get("location") + dl_url = download.headers.get("location") if download.headers else None if not dl_url: page = BeautifulSoup(download.content, 'lxml') export = drive + page.find('a', {'id': 'uc-download-url'}).get('href') @@ -48,7 +46,7 @@ def gdrive(self, url): async def mega_dl(self, url): path = parse_url(url).split('!') - if path == None: + if path is None: return None, None, None file_handle = path[0] file_key = path[1] diff --git a/helper_files/dl_helpers.py b/helper_files/dl_helpers.py index afe248d..d7ffc99 100644 --- a/helper_files/dl_helpers.py +++ b/helper_files/dl_helpers.py @@ -44,47 +44,46 @@ def base64_to_a32(s): return str_to_a32(base64_url_decode(s)) def parse_url(url): - if '/file/' in url: - url = url.replace(' ', '') - file_id = re.findall(r'\W\w\w\w\w\w\w\w\w\W', url)[0][1:-1] - id_index = re.search(file_id, url).end() - key = url[id_index + 1:] - return f'{file_id}!{key}' - elif '!' in url: - match = re.findall(r'/#!(.*)', url) - path = match[0] - return path - else: - return None + if '/file/' in url: + url = url.replace(' ', '') + file_id = re.findall(r'\W\w\w\w\w\w\w\w\w\W', url)[0][1:-1] + id_index = re.search(file_id, url).end() + key = url[id_index + 1:] + return f'{file_id}!{key}' + elif '!' in url: + match = re.findall(r'/#!(.*)', url) + return match[0] + else: + return None async def download_file(url): - path = parse_url(url).split('!') - if path == None: - return None, None, None - file_handle = path[0] - file_key = path[1] - file_key = base64_to_a32(file_key) - file_data = await api_request({ - 'a': 'g', - 'g': 1, - 'p': file_handle - }) - k = (file_key[0] ^ file_key[4], file_key[1] ^ file_key[5], - file_key[2] ^ file_key[6], file_key[3] ^ file_key[7]) - if 'g' not in file_data: - return None, None, None - file_url = file_data['g'] - file_size = file_data['s'] - attribs = base64_url_decode(file_data['at']) - attribs = decrypt_attr(attribs, k) - file_name = attribs['n'] - return file_name,file_size, file_url + path = parse_url(url).split('!') + if path is None: + return None, None, None + file_handle = path[0] + file_key = path[1] + file_key = base64_to_a32(file_key) + file_data = await api_request({ + 'a': 'g', + 'g': 1, + 'p': file_handle + }) + k = (file_key[0] ^ file_key[4], file_key[1] ^ file_key[5], + file_key[2] ^ file_key[6], file_key[3] ^ file_key[7]) + if 'g' not in file_data: + return None, None, None + file_url = file_data['g'] + file_size = file_data['s'] + attribs = base64_url_decode(file_data['at']) + attribs = decrypt_attr(attribs, k) + file_name = attribs['n'] + return file_name,file_size, file_url async def api_request(data): sequence_num = random.randint(0, 0xFFFFFFFF) if not isinstance(data, list): data = [data] - url = f'https://g.api.mega.co.nz/cs' + url = 'https://g.api.mega.co.nz/cs' params = {'id': sequence_num} async with aiohttp.ClientSession() as session: response = await session.post(url, data=json.dumps(data), params=params) diff --git a/imdb.py b/imdb.py index a651a02..49af634 100644 --- a/imdb.py +++ b/imdb.py @@ -25,7 +25,6 @@ async def get_content(url): "example": "{ch}imdb joker", } ) - async def _(client,message): query = get_text(message) msg = await edit_or_reply(message, "`Searching For Movie..`") @@ -33,7 +32,7 @@ async def _(client,message): if not query: await msg.edit("`Please Give Me An Input.`") return - url = "https://www.imdb.com/find?ref_=nv_sr_fn&q=" + query + "&s=all" + url = f"https://www.imdb.com/find?ref_=nv_sr_fn&q={query}&s=all" r = await get_content(url) soup = BeautifulSoup(r, "lxml") o_ = soup.find("td", {"class": "result_text"}) @@ -47,21 +46,17 @@ async def _(client,message): if r_json.get("@type"): res_str += f"\nType : {r_json['@type']} \n" if r_json.get("name"): - res_str += f"Name : {r_json['name']} \n" + res_str += f"Name : {r_json['name']} \n" if r_json.get("contentRating"): res_str += f"Content Rating : {r_json['contentRating']} \n" if r_json.get("genre"): all_genre = r_json['genre'] - genre = "" - for i in all_genre: - genre += f"{i}, " + genre = "".join(f"{i}, " for i in all_genre) genre = genre[:-2] res_str += f"Genre : {genre} \n" if r_json.get("actor"): all_actors = r_json['actor'] - actors = "" - for i in all_actors: - actors += f"{i['name']}, " + actors = "".join(f"{i['name']}, " for i in all_actors) actors = actors[:-2] res_str += f"Actors : {actors} \n" if r_json.get("trailer"): @@ -81,9 +76,8 @@ async def _(client,message): res_str += f"Date Published : {r_json['datePublished']} \n" if r_json.get("aggregateRating"): res_str += f"Rating Count : {r_json['aggregateRating']['ratingCount']} \nRating Value : {r_json['aggregateRating']['ratingValue']} \n" - res_str += f"URL : {url}" - thumb = r_json.get('image') - if thumb: + res_str += f"URL : {url}" + if thumb := r_json.get('image'): await msg.delete() return await reply.reply_photo(thumb, caption=res_str) await msg.edit(res_str) diff --git a/music_player.py b/music_player.py index e932aa9..46d24f0 100644 --- a/music_player.py +++ b/music_player.py @@ -48,7 +48,6 @@ async def pl(client, message): group_call = GPC.get((message.chat.id, client.me.id)) play = await edit_or_reply(message, "`Please Wait!`") song = f"**PlayList in {message.chat.title}** \n" - sno = 0 s = s_dict.get((message.chat.id, client.me.id)) if not group_call: return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") @@ -59,9 +58,8 @@ async def pl(client, message): return await play.edit("`Voice Chat Not Connected. So How Am i Supposed To Give You Playlist?`") if group_call.is_connected: song += f"**Currently Playing :** `{group_call.song_name}` \n\n" - for i in s: - sno += 1 - song += f"**{sno} ▶** [{i['song_name']}]({i['url']}) `| {i['singer']} | {i['dur']}` \n\n" + for sno, i in enumerate(s, start=1): + song += f"**{sno} ▶** [{i['song_name']}]({i['url']}) `| {i['singer']} | {i['dur']}` \n\n" await play.edit(song) async def get_chat_(client, chat_): @@ -71,7 +69,7 @@ async def get_chat_(client, chat_): return (await client.get_chat(int(chat_))).id except ValueError: chat_ = chat_.split("-100")[1] - chat_ = '-' + str(chat_) + chat_ = f'-{str(chat_)}' return int(chat_) async def playout_ended_handler(group_call, filename): @@ -113,10 +111,10 @@ async def ski_p(client, message): s = s_dict.get((message.chat.id, client.me.id)) if not group_call: await m_.edit("`Is Group Call Even Connected?`") - return + return if not group_call.is_connected: await m_.edit("`Is Group Call Even Connected?`") - return + return if not no_t_s: return await m_.edit("`Give Me Valid List Key Len.`") if no_t_s == "current": @@ -127,14 +125,14 @@ async def ski_p(client, message): name = str(s[0]['song_name']) prev = group_call.song_name group_call.input_filename = next_s - return await m_.edit(f"`Skipped {prev}. Now Playing {name}!`") + return await m_.edit(f"`Skipped {prev}. Now Playing {name}!`") else: if not s: return await m_.edit("`There is No Playlist!`") if not no_t_s.isdigit(): return await m_.edit("`Input Should Be In Digits.`") no_t_s = int(no_t_s) - if int(no_t_s) == 0: + if no_t_s == 0: return await m_.edit("`0? What?`") no_t_s = int(no_t_s - 1) try: @@ -153,39 +151,45 @@ async def ski_p(client, message): async def play_m(client, message): group_call = GPC.get((message.chat.id, client.me.id)) u_s = await edit_or_reply(message, "`Processing..`") - input_str = get_text(message) - if not input_str: - if not message.reply_to_message: - return await u_s.edit_text("`Reply To A File To PLay It.`") - if message.reply_to_message.audio: - await u_s.edit_text("`Please Wait, Let Me Download This File!`") - audio = message.reply_to_message.audio - audio_original = await message.reply_to_message.download() - vid_title = audio.title or audio.file_name - uploade_r = message.reply_to_message.audio.performer or "Unknown Artist." - dura_ = message.reply_to_message.audio.duration - dur = datetime.timedelta(seconds=dura_) - raw_file_name = ''.join([random.choice(string.ascii_lowercase) for i in range(5)]) + ".raw" - url = message.reply_to_message.link - else: - return await u_s.edit("`Reply To A File To PLay It.`") + if input_str := get_text(message): + search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1) + rt = search.result() + result_s = rt.get("search_result") + if not result_s: + return await u_s.edit(f"`No Song Found Matching With Query - {input_str}, Please Try Giving Some Other Name.`") + url = result_s[0]["link"] + dur = result_s[0]["duration"] + vid_title = result_s[0]["title"] + yt_id = result_s[0]["id"] + uploade_r = result_s[0]["channel"] + start = time.time() + try: + audio_original = await yt_dl(url, client, message, start) + except BaseException as e: + return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") + raw_file_name = ( + ''.join([random.choice(string.ascii_lowercase) for _ in range(5)]) + + ".raw" + ) + else: - search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1) - rt = search.result() - result_s = rt.get("search_result") - if not result_s: - return await u_s.edit(f"`No Song Found Matching With Query - {input_str}, Please Try Giving Some Other Name.`") - url = result_s[0]["link"] - dur = result_s[0]["duration"] - vid_title = result_s[0]["title"] - yt_id = result_s[0]["id"] - uploade_r = result_s[0]["channel"] - start = time.time() - try: - audio_original = await yt_dl(url, client, message, start) - except BaseException as e: - return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`") - raw_file_name = ''.join([random.choice(string.ascii_lowercase) for i in range(5)]) + ".raw" + if not message.reply_to_message: + return await u_s.edit_text("`Reply To A File To PLay It.`") + if not message.reply_to_message.audio: + return await u_s.edit("`Reply To A File To PLay It.`") + await u_s.edit_text("`Please Wait, Let Me Download This File!`") + audio = message.reply_to_message.audio + audio_original = await message.reply_to_message.download() + vid_title = audio.title or audio.file_name + uploade_r = message.reply_to_message.audio.performer or "Unknown Artist." + dura_ = message.reply_to_message.audio.duration + dur = datetime.timedelta(seconds=dura_) + raw_file_name = ( + ''.join([random.choice(string.ascii_lowercase) for _ in range(5)]) + + ".raw" + ) + + url = message.reply_to_message.link try: raw_file_name = await convert_to_raw(audio_original, raw_file_name) except BaseException as e: @@ -273,8 +277,7 @@ def yt_dl(url, client, message, start): } with YoutubeDL(opts) as ytdl: ytdl_data = ytdl.extract_info(url, download=True) - file_name = str(ytdl_data['id']) + ".mp3" - return file_name + return str(ytdl_data['id']) + ".mp3" RD_ = {} FFMPEG_PROCESSES = {} @@ -286,12 +289,11 @@ def yt_dl(url, client, message, start): cmd_help={"help": "Play Radio.", "example": "{ch}pradio (radio url)"}, ) async def radio_s(client, message): - g_s_ = GPC.get((message.chat.id, client.me.id)) - if g_s_: + if g_s_ := GPC.get((message.chat.id, client.me.id)): if g_s_.is_connected: await g_s_.stop() del GPC[(message.chat.id, client.me.id)] - s = await edit_or_reply(message, "`Please Wait.`") + s = await edit_or_reply(message, "`Please Wait.`") input_filename = f"radio_{message.chat.id}.raw" radio_url = get_text(message) if not radio_url: @@ -322,12 +324,10 @@ async def radio_s(client, message): ) async def stop_radio(client, message): msg = await edit_or_reply(message, "`Please Wait.`") - group_call = RD_.get((message.chat.id, client.me.id)) - if group_call: - if group_call.is_connected: - await group_call.stop() - else: - return await msg.edit("`Is Vc is Connected?`") + if not (group_call := RD_.get((message.chat.id, client.me.id))): + return await msg.edit("`Is Vc is Connected?`") + if group_call.is_connected: + await group_call.stop() else: return await msg.edit("`Is Vc is Connected?`") process = FFMPEG_PROCESSES.get((message.chat.id, client.me.id)) @@ -362,12 +362,12 @@ async def wow_dont_stop_songs(client, message): group_call = GPC.get((message.chat.id, client.me.id)) if not group_call: await edit_or_reply(message, "`Is Group Call Even Connected?`") - return + return if not group_call.is_connected: await edit_or_reply(message, "`Is Group Call Even Connected?`") - return + return group_call.resume_playout() - await edit_or_reply(message, f"`▶️ Resumed.`") + await edit_or_reply(message, "`▶️ Resumed.`") @friday_on_cmd( @@ -421,7 +421,7 @@ async def rejoinvcpls(client, message): await edit_or_reply(message, "`Is Group Call Even Connected?`") return await group_call.reconnect() - await edit_or_reply(message, f"`Rejoined! - Vc`") + await edit_or_reply(message, "`Rejoined! - Vc`") @friday_on_cmd( diff --git a/rom_search.py b/rom_search.py index dd6e1e7..7a6adfc 100644 --- a/rom_search.py +++ b/rom_search.py @@ -115,7 +115,7 @@ async def m_(client, message): if not query: return await e_.edit("`Please Give Me An Query.`") href = await get_url(query) - if href == None: + if href is None: return await e_.edit("`No Results Matching You Query.`") url, device_name, version, size, rs_date, type_, package_name = await fetch_data(href) final_ = f"MIUI Search \nModel : {device_name} \nVersion : {version} \nSize : {size} \nRelease Date : {rs_date} \nType : {type_} \nPackage Name : {package_name} \nDownload : {ch_}udl {url}" @@ -134,7 +134,7 @@ async def rm_s(client, message): if not query: return await e_.edit("`Please Give Me An Query.`") file_url, r_date, size, system, device = await realme_rom_search(query) - if file_url == None: + if file_url is None: return await e_.edit("`No Results Matching You Query.`") final_ = f"RealMeRom Search \nDevice : {device} \nSystem : {system} \nSize : {size} \nRelease Date : {r_date} \nDownload : {ch_}udl {file_url}" await message.edit(final_) diff --git a/shazam.py b/shazam.py index ecc9769..1f5a1f3 100644 --- a/shazam.py +++ b/shazam.py @@ -66,7 +66,7 @@ async def shazam_(client, message): size_ = humanbytes(os.stat(music_file).st_size) dur = datetime.timedelta(seconds=dur) thumb, by, title = await shazam(music_file) - if title == None: + if title is None: return await msg.edit("`No Results Found.`") etime = time.time() t_k = round(etime - stime)