diff --git a/assistant/callbackstuffs.py b/assistant/callbackstuffs.py index 15598fe..17e1e5b 100644 --- a/assistant/callbackstuffs.py +++ b/assistant/callbackstuffs.py @@ -37,6 +37,7 @@ GDrive = GDriveManager() if GDriveManager else None uploader = CatboxUploader() # --------------------------------------------------------------------# + def text_to_url(event): """function to get media url (with|without) Webpage""" if isinstance(event.media, MessageMediaWebPage): @@ -325,6 +326,7 @@ async def update(eve): await bash("pip3 install -r requirements.txt --break-system-packages") execl(sys.executable, sys.executable, "-m", "pyUltroid") + @callback(re.compile("changes(.*)"), owner=True) async def changes(okk): match = okk.data_match.group(1).decode("utf-8") @@ -559,7 +561,9 @@ async def emoji(event): var = "EMOJI_IN_HELP" name = f"Emoji in `{HNDLR}help` menu" async with event.client.conversation(pru) as conv: - await conv.send_message("Send emoji u want to set πŸ™ƒ.\n\nUse /cancel to cancel.") + await conv.send_message( + "Send emoji u want to set πŸ™ƒ.\n\nUse /cancel to cancel." + ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message diff --git a/assistant/games.py b/assistant/games.py index e2b86ea..7098518 100644 --- a/assistant/games.py +++ b/assistant/games.py @@ -37,6 +37,7 @@ aki_photo = "https://graph.org/file/3cc8825c029fd0cab9edc.jpg" akipyLOGS = getLogger("akipy") + @ultroid_cmd(pattern="akinator") async def akina(e): sta = Akinator() @@ -86,7 +87,7 @@ async def doai(e): async def okah(e): try: mk = e.pattern_match.group(1).decode("utf-8").split("_") - #akipyLOGS.info(f"Parsed values: {mk}") + # akipyLOGS.info(f"Parsed values: {mk}") if len(mk) < 3: akipyLOGS.error("Pattern match did not return enough parts.") @@ -108,7 +109,10 @@ async def okah(e): # Game is not won yet, continue asking questions buttons = [ [Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Yes", "No", "Idk"]], - [Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Probably", "Probably Not"]], + [ + Button.inline(o, f"aka_{ch}_{mid}_{o}") + for o in ["Probably", "Probably Not"] + ], ] await e.edit(gm.question, buttons=buttons) @@ -140,6 +144,7 @@ async def eiagx(e): GIMAGE = "https://graph.org/file/1c51015bae5205a65fd69.jpg" + @asst_cmd(pattern="startgame", owner=True) async def magic(event): buttons = [ @@ -244,10 +249,17 @@ async def choose_cata(event): if TRIVIA_CHATS[chat].get("cancel") is not None: break ansi = str(uuid.uuid1()).split("-")[0].encode() - opts = [PollAnswer(TextWithEntities(unescape(q["correct_answer"]), entities=[]), ansi)] + opts = [ + PollAnswer( + TextWithEntities(unescape(q["correct_answer"]), entities=[]), ansi + ) + ] [ opts.append( - PollAnswer(TextWithEntities(unescape(a), entities=[]), str(uuid.uuid1()).split("-")[0].encode()) + PollAnswer( + TextWithEntities(unescape(a), entities=[]), + str(uuid.uuid1()).split("-")[0].encode(), + ) ) for a in q["incorrect_answers"] ] @@ -256,8 +268,7 @@ async def choose_cata(event): Poll( 0, TextWithEntities( - f"[{copper+1}]. " + unescape(q["question"]), - entities=[] + f"[{copper + 1}]. " + unescape(q["question"]), entities=[] ), answers=opts, public_voters=True, diff --git a/assistant/ytdl.py b/assistant/ytdl.py index 1099690..7ed2500 100644 --- a/assistant/ytdl.py +++ b/assistant/ytdl.py @@ -272,7 +272,7 @@ async def _(event): description = description if description != "" else "None" text = f"**Title: [{title}]({_yt_base_url}{vid_id})**\n\n" text += f"`πŸ“ Description: {description}\n\n" - text += f"γ€Œ Duration: {time_formatter(int(duration)*1000)} 」\n" + text += f"γ€Œ Duration: {time_formatter(int(duration) * 1000)} 」\n" text += f"γ€Œ Artist: {artist} 」\n" text += f"γ€Œ Views: {views} 」\n" text += f"γ€Œ Likes: {likes} 」\n" diff --git a/multi_client.py b/multi_client.py index a53cfe7..72a3770 100644 --- a/multi_client.py +++ b/multi_client.py @@ -5,6 +5,7 @@ import sys vars = ["API_ID", "API_HASH", "SESSION"] + def _check(z): new = [] for var in vars: @@ -14,6 +15,7 @@ def _check(z): new.append(ent) return True, new + for z in range(5): n = str(z + 1) if z == 0: @@ -21,7 +23,17 @@ for z in range(5): fine, out = _check(str(z)) if fine: subprocess.Popen( - [sys.executable, "-m", "pyUltroid", out[0], out[1], out[2], out[3], out[4], n], + [ + sys.executable, + "-m", + "pyUltroid", + out[0], + out[1], + out[2], + out[3], + out[4], + n, + ], stdin=None, stderr=None, stdout=None, @@ -36,4 +48,3 @@ except Exception as er: print(er) finally: loop.close() - diff --git a/plugins/_chatactions.py b/plugins/_chatactions.py index 3ae1c90..be9f4eb 100644 --- a/plugins/_chatactions.py +++ b/plugins/_chatactions.py @@ -56,7 +56,7 @@ async def DummyHandler(ult): # force subscribe if ( udB.get_key("FORCESUB") - and ((ult.user_joined or ult.user_added)) + and (ult.user_joined or ult.user_added) and get_forcesetting(ult.chat_id) ): user = await ult.get_user() @@ -92,7 +92,7 @@ async def DummyHandler(ult): view_messages=False, ) await ult.respond( - f'**@UltroidBans:** Banned user detected and banned!\n`{str(is_banned)}`.\nBan reason: {is_banned["reason"]}', + f"**@UltroidBans:** Banned user detected and banned!\n`{str(is_banned)}`.\nBan reason: {is_banned['reason']}", ) except BaseException: diff --git a/plugins/_inline.py b/plugins/_inline.py index 211e723..276b984 100644 --- a/plugins/_inline.py +++ b/plugins/_inline.py @@ -345,12 +345,12 @@ def page_num(index, key): [ Button.inline( "Β« PʀᴇᴠΙͺᴏᴜs", - data=f"uh_{key}_{index-1}", + data=f"uh_{key}_{index - 1}", ), Button.inline("Β« Bα΄€α΄„α΄‹ Β»", data="open"), Button.inline( "Nᴇxα΄› Β»", - data=f"uh_{key}_{index+1}", + data=f"uh_{key}_{index + 1}", ), ] ) diff --git a/plugins/admintools.py b/plugins/admintools.py index a6f8e63..5575973 100644 --- a/plugins/admintools.py +++ b/plugins/admintools.py @@ -398,6 +398,7 @@ async def _(e): except Exception as er: return await e.eor(str(er), time=5) + @ultroid_cmd(pattern="pinned", manager=True, groups_only=True) async def djshsh(event): chat = await event.get_chat() diff --git a/plugins/afk.py b/plugins/afk.py index 74e06eb..5ce9364 100644 --- a/plugins/afk.py +++ b/plugins/afk.py @@ -27,7 +27,7 @@ from . import ( udB, ultroid_bot, ultroid_cmd, - upload_file + upload_file, ) old_afk_msg = [] diff --git a/plugins/aiwrapper.py b/plugins/aiwrapper.py index ee63749..bdbd752 100644 --- a/plugins/aiwrapper.py +++ b/plugins/aiwrapper.py @@ -37,14 +37,14 @@ ENDPOINTS = { "gpt": "https://api.openai.com/v1/chat/completions", "antr": "https://api.anthropic.com/v1/messages", "gemini": "https://generativelanguage.googleapis.com/v1beta/chat/completions", - "deepseek": "https://api.deepseek.com/chat/completions" + "deepseek": "https://api.deepseek.com/chat/completions", } DEFAULT_MODELS = { "gpt": "gpt-4o-mini", "antr": "claude-3-opus-20240229", "gemini": "gemini-1.5-flash", - "deepseek": "deepseek-chat" + "deepseek": "deepseek-chat", } @@ -54,7 +54,7 @@ def get_model(provider): "gpt": "OPENAI_MODEL", "antr": "ANTHROPIC_MODEL", "gemini": "GEMINI_MODEL", - "deepseek": "DEEPSEEK_MODEL" + "deepseek": "DEEPSEEK_MODEL", } return udB.get_key(model_keys[provider]) or DEFAULT_MODELS[provider] @@ -66,7 +66,7 @@ async def stream_response(msg, text): words = text.split() chunks = [] current_chunk = [] - + for word in words: current_chunk.append(word) if len(" ".join(current_chunk)) > 100: @@ -74,7 +74,7 @@ async def stream_response(msg, text): current_chunk = [word] if current_chunk: chunks.append(" ".join(current_chunk)) - + for chunk in chunks: current += chunk + " " try: @@ -90,13 +90,13 @@ async def get_ai_response(provider, prompt, api_key, stream=False): try: headers = {"Content-Type": "application/json"} model = get_model(provider) - + if provider == "gpt": headers["Authorization"] = f"Bearer {api_key}" data = { "model": model, "messages": [{"role": "user", "content": prompt}], - "stream": stream + "stream": stream, } if not stream: response = await async_searcher( @@ -104,23 +104,27 @@ async def get_ai_response(provider, prompt, api_key, stream=False): headers=headers, post=True, json=data, - re_json=True + re_json=True, ) yield response["choices"][0]["message"]["content"] return - + async with aiohttp.ClientSession() as session: async with session.post( - ENDPOINTS[provider], - headers=headers, - json=data + ENDPOINTS[provider], headers=headers, json=data ) as resp: async for line in resp.content: if line: try: - json_line = json.loads(line.decode('utf-8').strip().strip('data:').strip()) - if 'choices' in json_line and json_line['choices']: - content = json_line['choices'][0].get('delta', {}).get('content', '') + json_line = json.loads( + line.decode("utf-8").strip().strip("data:").strip() + ) + if "choices" in json_line and json_line["choices"]: + content = ( + json_line["choices"][0] + .get("delta", {}) + .get("content", "") + ) if content: yield content except Exception: @@ -132,7 +136,7 @@ async def get_ai_response(provider, prompt, api_key, stream=False): data = { "model": model, "messages": [{"role": "user", "content": prompt}], - "stream": stream + "stream": stream, } if not stream: response = await async_searcher( @@ -140,23 +144,21 @@ async def get_ai_response(provider, prompt, api_key, stream=False): headers=headers, post=True, json=data, - re_json=True + re_json=True, ) yield response["content"][0]["text"] return - + async with aiohttp.ClientSession() as session: async with session.post( - ENDPOINTS[provider], - headers=headers, - json=data + ENDPOINTS[provider], headers=headers, json=data ) as resp: async for line in resp.content: if line: try: - json_line = json.loads(line.decode('utf-8').strip()) - if 'content' in json_line: - content = json_line['content'][0]['text'] + json_line = json.loads(line.decode("utf-8").strip()) + if "content" in json_line: + content = json_line["content"][0]["text"] if content: yield content except Exception: @@ -168,11 +170,11 @@ async def get_ai_response(provider, prompt, api_key, stream=False): "model": model, "messages": [ {"role": "system", "content": "You are a helpful assistant."}, - {"role": "user", "content": prompt} + {"role": "user", "content": prompt}, ], - "stream": stream + "stream": stream, } - + if not stream: try: response = await async_searcher( @@ -180,15 +182,20 @@ async def get_ai_response(provider, prompt, api_key, stream=False): headers=headers, post=True, json=data, - re_json=True + re_json=True, ) if "error" in response: error = response["error"] if error.get("code") == 429: retry_delay = None for detail in error.get("details", []): - if detail.get("@type") == "type.googleapis.com/google.rpc.RetryInfo": - retry_delay = detail.get("retryDelay", "60s").rstrip("s") + if ( + detail.get("@type") + == "type.googleapis.com/google.rpc.RetryInfo" + ): + retry_delay = detail.get( + "retryDelay", "60s" + ).rstrip("s") error_msg = f"⚠️ Rate limit exceeded. Please try again in {retry_delay} seconds." if "free_tier" in str(error): error_msg += "\nConsider upgrading to a paid tier for higher quotas." @@ -205,16 +212,21 @@ async def get_ai_response(provider, prompt, api_key, stream=False): async with aiohttp.ClientSession() as session: try: async with session.post( - ENDPOINTS[provider], - headers=headers, - json=data + ENDPOINTS[provider], headers=headers, json=data ) as resp: if resp.status == 429: error_data = await resp.json() retry_delay = "60" - for detail in error_data.get("error", {}).get("details", []): - if detail.get("@type") == "type.googleapis.com/google.rpc.RetryInfo": - retry_delay = detail.get("retryDelay", "60s").rstrip("s") + for detail in error_data.get("error", {}).get( + "details", [] + ): + if ( + detail.get("@type") + == "type.googleapis.com/google.rpc.RetryInfo" + ): + retry_delay = detail.get( + "retryDelay", "60s" + ).rstrip("s") yield f"⚠️ Rate limit exceeded. Please try again in {retry_delay} seconds." return @@ -225,15 +237,22 @@ async def get_ai_response(provider, prompt, api_key, stream=False): async for line in resp.content: if line: - text = line.decode('utf-8').strip() - if text.startswith('data: '): + text = line.decode("utf-8").strip() + if text.startswith("data: "): data = text[6:] # Remove 'data: ' prefix - if data == '[DONE]': + if data == "[DONE]": break try: json_data = json.loads(data) - if 'choices' in json_data and json_data['choices']: - content = json_data['choices'][0].get('delta', {}).get('content', '') + if ( + "choices" in json_data + and json_data["choices"] + ): + content = ( + json_data["choices"][0] + .get("delta", {}) + .get("content", "") + ) if content: yield content except json.JSONDecodeError: @@ -247,7 +266,7 @@ async def get_ai_response(provider, prompt, api_key, stream=False): data = { "model": model, "messages": [{"role": "user", "content": prompt}], - "stream": stream + "stream": stream, } if not stream: response = await async_searcher( @@ -255,23 +274,25 @@ async def get_ai_response(provider, prompt, api_key, stream=False): headers=headers, post=True, json=data, - re_json=True + re_json=True, ) yield response["choices"][0]["message"]["content"] return - + async with aiohttp.ClientSession() as session: async with session.post( - ENDPOINTS[provider], - headers=headers, - json=data + ENDPOINTS[provider], headers=headers, json=data ) as resp: async for line in resp.content: if line: try: - json_line = json.loads(line.decode('utf-8').strip()) - if 'choices' in json_line and json_line['choices']: - content = json_line['choices'][0].get('delta', {}).get('content', '') + json_line = json.loads(line.decode("utf-8").strip()) + if "choices" in json_line and json_line["choices"]: + content = ( + json_line["choices"][0] + .get("delta", {}) + .get("content", "") + ) if content: yield content except Exception: @@ -291,11 +312,13 @@ async def gemini_ai(event): api_key = udB.get_key("GEMINI_API_KEY") if not api_key: - return await event.eor("⚠️ Please set Gemini API key using `setdb GEMINI_API_KEY your_api_key`") + return await event.eor( + "⚠️ Please set Gemini API key using `setdb GEMINI_API_KEY your_api_key`" + ) msg = await event.eor("πŸ€” Thinking...") model = get_model("gemini") - + header = ( "πŸ€– **Google Gemini**\n" f"**Model:** `{model}`\n" @@ -303,7 +326,7 @@ async def gemini_ai(event): f"**πŸ” Prompt:**\n{prompt}\n\n" "**πŸ’‘ Response:**\n" ) - + if event.client.me.bot: await msg.edit(header) response = "" @@ -318,9 +341,10 @@ async def gemini_ai(event): async for chunk in get_ai_response("gemini", prompt, api_key, stream=True): response += chunk try: - await msg.edit(header + response) + await msg.edit(header + response) except Exception: - pass + pass + @ultroid_cmd(pattern="antr( (.*)|$)") async def anthropic_ai(event): @@ -331,11 +355,13 @@ async def anthropic_ai(event): api_key = udB.get_key("ANTHROPIC_KEY") if not api_key: - return await event.eor("⚠️ Please set Anthropic API key using `setdb ANTHROPIC_KEY your_api_key`") + return await event.eor( + "⚠️ Please set Anthropic API key using `setdb ANTHROPIC_KEY your_api_key`" + ) msg = await event.eor("πŸ€” Thinking...") model = get_model("antr") - + formatted_response = ( "🧠 **Anthropic Claude**\n" f"**Model:** `{model}`\n" @@ -343,7 +369,7 @@ async def anthropic_ai(event): f"**πŸ” Prompt:**\n{prompt}\n\n" f"**πŸ’‘ Response:**\n" ) - + if event.client.me.bot: await msg.edit(formatted_response) response = "" @@ -362,6 +388,7 @@ async def anthropic_ai(event): except Exception: pass + @ultroid_cmd(pattern="gpt( (.*)|$)") async def openai_ai(event): """Use OpenAI GPT""" @@ -371,11 +398,13 @@ async def openai_ai(event): api_key = udB.get_key("OPENAI_API_KEY") if not api_key: - return await event.eor("⚠️ Please set GPT API key using `setdb OPENAI_API_KEY your_api_key`") + return await event.eor( + "⚠️ Please set GPT API key using `setdb OPENAI_API_KEY your_api_key`" + ) msg = await event.eor("πŸ€” Thinking...") model = get_model("gpt") - + header = ( "🌟 **OpenAI GPT**\n" f"**Model:** `{model}`\n" @@ -383,7 +412,7 @@ async def openai_ai(event): f"**πŸ” Prompt:**\n{prompt}\n\n" "**πŸ’‘ Response:**\n" ) - + if event.client.me.bot: await msg.edit(header) response = "" @@ -394,7 +423,7 @@ async def openai_ai(event): except Exception: pass else: - response ="" + response = "" async for chunk in get_ai_response("gpt", prompt, api_key, stream=True): response += chunk try: @@ -402,6 +431,7 @@ async def openai_ai(event): except Exception: pass + @ultroid_cmd(pattern="deepseek( (.*)|$)") async def deepseek_ai(event): """Use DeepSeek AI""" @@ -411,11 +441,13 @@ async def deepseek_ai(event): api_key = udB.get_key("DEEPSEEK_API_KEY") if not api_key: - return await event.eor("⚠️ Please set DeepSeek API key using `setdb DEEPSEEK_API_KEY your_api_key`") + return await event.eor( + "⚠️ Please set DeepSeek API key using `setdb DEEPSEEK_API_KEY your_api_key`" + ) msg = await event.eor("πŸ€” Thinking...") model = get_model("deepseek") - + formatted_response = ( "πŸ€– **DeepSeek AI**\n" f"**Model:** `{model}`\n" @@ -423,7 +455,7 @@ async def deepseek_ai(event): f"**πŸ” Prompt:**\n{prompt}\n\n" f"**πŸ’‘ Response:**\n" ) - + if event.client.me.bot: await msg.edit(formatted_response) response = "" @@ -442,4 +474,3 @@ async def deepseek_ai(event): await msg.edit(formatted_response + response) except Exception: pass - diff --git a/plugins/audiotools.py b/plugins/audiotools.py index 40343bb..bbb38e0 100644 --- a/plugins/audiotools.py +++ b/plugins/audiotools.py @@ -26,7 +26,7 @@ from . import ( mediainfo, stdr, time_formatter, - ultroid_cmd + ultroid_cmd, ) __doc__ = get_help("help_audiotools") @@ -149,7 +149,11 @@ async def ex_aud(e): f_time = time.time() try: n_file, _ = await e.client.fast_uploader( - out_file, show_progress=True, event=e, message="Uploading...", to_delete=True + out_file, + show_progress=True, + event=e, + message="Uploading...", + to_delete=True, ) except FileNotFoundError: diff --git a/plugins/autopic.py b/plugins/autopic.py index 30a048b..3241800 100644 --- a/plugins/autopic.py +++ b/plugins/autopic.py @@ -24,24 +24,24 @@ __doc__ = get_help("help_autopic") async def get_google_images(query: str): """Extract image URLs from Google Images search results with fallbacks""" - + headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" } - + search_url = f"https://www.google.com/search?q={query}&tbm=isch" - + # Domains to exclude excluded_domains = [ - 'gstatic.com', - 'google.com', - 'googleusercontent.com', - 'ssl.google.com' + "gstatic.com", + "google.com", + "googleusercontent.com", + "ssl.google.com", ] - + def is_valid_url(url): return not any(domain in url.lower() for domain in excluded_domains) - + try: async with aiohttp.ClientSession() as session: async with session.get(search_url, headers=headers) as response: @@ -53,7 +53,7 @@ async def get_google_images(query: str): search_match = re.search(search_pattern, html, re.DOTALL) if search_match: search_content = search_match.group(1) - url_pattern = r'https://[^\"]*?\.(?:jpg|jpeg|png|webp)' + url_pattern = r"https://[^\"]*?\.(?:jpg|jpeg|png|webp)" url_matches = re.finditer(url_pattern, search_content, re.IGNORECASE) for url_match in url_matches: url = url_match.group(0) @@ -66,7 +66,7 @@ async def get_google_images(query: str): matches = re.finditer(pattern, html, re.DOTALL) for match in matches: div_content = match.group(1) - url_pattern = r'https://[^\"]*?\.(?:jpg|jpeg|png|webp)' + url_pattern = r"https://[^\"]*?\.(?:jpg|jpeg|png|webp)" url_matches = re.finditer(url_pattern, div_content, re.IGNORECASE) for url_match in url_matches: url = url_match.group(0) @@ -84,7 +84,7 @@ async def get_google_images(query: str): # Final fallback to data URLs if still no results if not img_urls: - pattern = r'data:image/(?:jpeg|png|webp);base64,[^\"]*' + pattern = r"data:image/(?:jpeg|png|webp);base64,[^\"]*" matches = re.finditer(pattern, html, re.IGNORECASE) for match in matches: url = match.group(0) @@ -92,7 +92,7 @@ async def get_google_images(query: str): img_urls.append(url) return img_urls - + except Exception as e: print(f"Error fetching Google images: {e}") return [] @@ -117,7 +117,9 @@ async def autopic(e): for lie in images: if udB.get_key("AUTOPIC") != search: return - download_path, stime = await fast_download(lie, "resources/downloads/autopic.jpg") + download_path, stime = await fast_download( + lie, "resources/downloads/autopic.jpg" + ) img = Image.open(download_path) img.save("resources/downloads/autopic.jpg") file = await e.client.upload_file("resources/downloads/autopic.jpg") diff --git a/plugins/beautify.py b/plugins/beautify.py index e8ecf61..0a10d8f 100644 --- a/plugins/beautify.py +++ b/plugins/beautify.py @@ -137,7 +137,7 @@ async def pass_on(ult): if not theme and spli[1] in RaySoTheme: theme = spli[1] except Exception as sam: - LOGS.exception(sam) + LOGS.exception(sam) if not text: await proc.eor("No text to beautify!") return diff --git a/plugins/converter.py b/plugins/converter.py index 201ff76..688d8e6 100644 --- a/plugins/converter.py +++ b/plugins/converter.py @@ -148,6 +148,7 @@ async def uconverter(event): return await xx.delete() + @ultroid_cmd( pattern="doc( (.*)|$)", ) diff --git a/plugins/devtools.py b/plugins/devtools.py index efb71c2..d982575 100644 --- a/plugins/devtools.py +++ b/plugins/devtools.py @@ -45,7 +45,7 @@ fn = functions ) async def _(e): xx = await e.eor(get_string("com_1")) - x, y = await bash("neofetch|sed 's/\x1B\\[[0-9;\\?]*[a-zA-Z]//g' >> neo.txt") + x, y = await bash("neofetch|sed 's/\x1b\\[[0-9;\\?]*[a-zA-Z]//g' >> neo.txt") if y and y.endswith("NOT_FOUND"): return await xx.edit(f"Error: `{y}`") with open("neo.txt", "r", encoding="utf-8") as neo: @@ -323,29 +323,28 @@ def _stringify(text=None, *args, **kwargs): async def aexec(code, event): # Create a dedicated namespace for execution exec_globals = { - 'print': _stringify, - 'p': _stringify, - 'message': event, - 'event': event, - 'client': event.client, - 'reply': await event.get_reply_message(), - 'chat': event.chat_id, - 'u': u, - '__builtins__': __builtins__, - '__name__': __name__ + "print": _stringify, + "p": _stringify, + "message": event, + "event": event, + "client": event.client, + "reply": await event.get_reply_message(), + "chat": event.chat_id, + "u": u, + "__builtins__": __builtins__, + "__name__": __name__, } - + # Format the async function definition - wrapped_code = ( - 'async def __aexec(e, client):\n' + - '\n'.join(f' {line}' for line in code.split('\n')) + wrapped_code = "async def __aexec(e, client):\n" + "\n".join( + f" {line}" for line in code.split("\n") ) - + try: # Execute the wrapped code in our custom namespace exec(wrapped_code, exec_globals) # Get the defined async function - func = exec_globals['__aexec'] + func = exec_globals["__aexec"] # Execute it with proper parameters return await func(event, event.client) except Exception as e: diff --git a/plugins/downloadupload.py b/plugins/downloadupload.py index d5f5e30..aae22b4 100644 --- a/plugins/downloadupload.py +++ b/plugins/downloadupload.py @@ -66,7 +66,7 @@ async def down(event): ) except InvalidURL: return await msg.eor("`Invalid URL provided :(`", time=5) - await msg.eor(f"`{filename}` `downloaded in {time_formatter(d*1000)}.`") + await msg.eor(f"`{filename}` `downloaded in {time_formatter(d * 1000)}.`") @ultroid_cmd( @@ -194,7 +194,7 @@ async def _(event): force_document=force_doc, thumb=thumb, attributes=attributes, - caption=f"`Uploaded` `{files}` `in {time_formatter(_*1000)}`", + caption=f"`Uploaded` `{files}` `in {time_formatter(_ * 1000)}`", reply_to=event.reply_to_msg_id or event, ) s += 1 @@ -217,6 +217,6 @@ async def _(event): force_document=force_doc, thumb=thumb, attributes=attributes, - caption=f"`Uploaded` `{result}` `in {time_formatter(_*1000)}`", + caption=f"`Uploaded` `{result}` `in {time_formatter(_ * 1000)}`", ) await msg.try_delete() diff --git a/plugins/gdrive.py b/plugins/gdrive.py index bafffbd..4683d6d 100644 --- a/plugins/gdrive.py +++ b/plugins/gdrive.py @@ -52,7 +52,7 @@ async def gdown(event): if not status: return await eve.edit(response) await eve.edit( - f"`Downloaded ``{response}`` in {time_formatter((time.time() - _start)*1000)}`" + f"`Downloaded ``{response}`` in {time_formatter((time.time() - _start) * 1000)}`" ) diff --git a/plugins/giftools.py b/plugins/giftools.py index 5c8d0d2..bd30bf8 100644 --- a/plugins/giftools.py +++ b/plugins/giftools.py @@ -23,6 +23,7 @@ β€’`{i}gif ` Send video regarding to query. """ + import os import random import time diff --git a/plugins/glitch.py b/plugins/glitch.py index e4ee4df..68c71d2 100644 --- a/plugins/glitch.py +++ b/plugins/glitch.py @@ -10,6 +10,7 @@ β€’`{i}glitch ` gives a glitchy gif. """ + import os from . import bash, get_string, mediainfo, ultroid_cmd diff --git a/plugins/globaltools.py b/plugins/globaltools.py index a81744a..e8aefb8 100644 --- a/plugins/globaltools.py +++ b/plugins/globaltools.py @@ -36,6 +36,7 @@ `gpromote @username all sar` ~ promote the user in all group & channel β€’ `{i}gdemote` - `demote user globally` """ + import asyncio import os @@ -327,7 +328,7 @@ async def _(e): chats += 1 except FloodWaitError as fw: LOGS.info( - f"[FLOOD_WAIT_ERROR] : on Ungban\nSleeping for {fw.seconds+10}" + f"[FLOOD_WAIT_ERROR] : on Ungban\nSleeping for {fw.seconds + 10}" ) await asyncio.sleep(fw.seconds + 10) try: @@ -407,7 +408,7 @@ async def _(e): chats += 1 except FloodWaitError as fw: LOGS.info( - f"[FLOOD_WAIT_ERROR] : on GBAN Command\nSleeping for {fw.seconds+10}" + f"[FLOOD_WAIT_ERROR] : on GBAN Command\nSleeping for {fw.seconds + 10}" ) await asyncio.sleep(fw.seconds + 10) try: @@ -463,10 +464,8 @@ async def gcast(event): not keym.contains(chat) and int(f"-100{str(chat)}") not in NOSPAM_CHAT and ( - ( - event.text[2:7] != "admin" - or (x.entity.admin_rights or x.entity.creator) - ) + event.text[2:7] != "admin" + or (x.entity.admin_rights or x.entity.creator) ) ): try: diff --git a/plugins/greetings.py b/plugins/greetings.py index 27053ef..8afaa68 100644 --- a/plugins/greetings.py +++ b/plugins/greetings.py @@ -30,6 +30,7 @@ β€’ `{i}thankmembers on/off` Send a thank you sticker on hitting a members count of 100*x in your groups. """ + import os from . import upload_file as uf diff --git a/plugins/imagetools.py b/plugins/imagetools.py index 22fd011..cb1aa37 100644 --- a/plugins/imagetools.py +++ b/plugins/imagetools.py @@ -52,6 +52,7 @@ β€’ `{i}pixelator ` Create a Pixelated Image.. """ + import os from . import LOGS, con diff --git a/plugins/locks.py b/plugins/locks.py index edbdc6b..2e09f9c 100644 --- a/plugins/locks.py +++ b/plugins/locks.py @@ -13,6 +13,7 @@ β€’ `{i}unlock ` UNLOCK the Used Setting in Used Group. """ + from telethon.tl.functions.messages import EditChatDefaultBannedRightsRequest from pyUltroid.fns.admins import lock_unlock diff --git a/plugins/logo.py b/plugins/logo.py index 551104f..d1b19b6 100644 --- a/plugins/logo.py +++ b/plugins/logo.py @@ -13,6 +13,7 @@ Or Reply To Font File, To write with that font. """ + import glob import os import random @@ -49,20 +50,20 @@ async def logo_gen(event): bg_ = await temp.download_media() if not bg_: SRCH = [ - "background", - "neon", - "anime", - "art", - "bridges", - "streets", - "computer", - "cyberpunk", - "nature", - "abstract", - "exoplanet", - "magic", - "3d render", - ] + "background", + "neon", + "anime", + "art", + "bridges", + "streets", + "computer", + "cyberpunk", + "nature", + "abstract", + "exoplanet", + "magic", + "3d render", + ] res = await unsplashsearch(random.choice(SRCH), limit=1) bg_, _ = await download_file(res[0], "resources/downloads/logo.png") newimg = "resources/downloads/unsplash-temp.jpg" diff --git a/plugins/mediatools.py b/plugins/mediatools.py index 4e8667b..10b035e 100644 --- a/plugins/mediatools.py +++ b/plugins/mediatools.py @@ -14,6 +14,7 @@ Rotate any video/photo/media.. Note : for video it should be angle of 90's """ + import os import time from datetime import datetime as dt diff --git a/plugins/misc.py b/plugins/misc.py index e82b670..538fb8f 100644 --- a/plugins/misc.py +++ b/plugins/misc.py @@ -51,7 +51,7 @@ async def diela(e): bt = bs(ct, "html.parser", from_encoding="utf-8") ml = bt.find_all("a", "js-link-target", href=re.compile("daysoftheyear.com/days")) for eve in ml[:5]: - te += f'β€’ [{eve.text}]({eve["href"]})\n' + te += f"β€’ [{eve.text}]({eve['href']})\n" await m.edit(te, link_preview=False) diff --git a/plugins/mute.py b/plugins/mute.py index cb7c3d6..71792d9 100644 --- a/plugins/mute.py +++ b/plugins/mute.py @@ -26,6 +26,7 @@ d- days Mute user in current chat with time. """ + from telethon import events from telethon.utils import get_display_name diff --git a/plugins/nightmode.py b/plugins/nightmode.py index 4a0edd9..7b1769d 100644 --- a/plugins/nightmode.py +++ b/plugins/nightmode.py @@ -117,7 +117,9 @@ async def open_grp(): ), ) ) - await ultroid_bot.send_message(chat, "**NightMode Off**\n\nGroup Opened πŸ₯³.") + await ultroid_bot.send_message( + chat, "**NightMode Off**\n\nGroup Opened πŸ₯³." + ) except Exception as er: LOGS.info(er) diff --git a/plugins/notes.py b/plugins/notes.py index 4bceefe..cd51745 100644 --- a/plugins/notes.py +++ b/plugins/notes.py @@ -20,6 +20,7 @@ set notes in group so all can use it. type `#(Keyword of note)` to get it """ + import os from . import upload_file as uf diff --git a/plugins/pdftools.py b/plugins/pdftools.py index 6be4c33..717656c 100644 --- a/plugins/pdftools.py +++ b/plugins/pdftools.py @@ -25,6 +25,7 @@ β€’ `{i}pdsend ` Merge & send the pdf, collected from .pdsave. """ + import glob import os import shutil diff --git a/plugins/polls.py b/plugins/polls.py index 95423a6..75aa930 100644 --- a/plugins/polls.py +++ b/plugins/polls.py @@ -18,6 +18,7 @@ Get the quiz poll where answerno is the number of option which is correct """ + from telethon.tl.types import InputMediaPoll, Poll, PollAnswer, TextWithEntities from . import get_string, ultroid_cmd @@ -57,10 +58,20 @@ async def uri_poll(e): if len(option) <= 1: return await e.eor("`Options Should be More than 1..`", time=5) m = await e.eor(get_string("com_1")) - OUT = [PollAnswer(TextWithEntities(option[on], entities=[]), str(on).encode()) for on in range(len(option))] + OUT = [ + PollAnswer(TextWithEntities(option[on], entities=[]), str(on).encode()) + for on in range(len(option)) + ] await e.respond( file=InputMediaPoll( - Poll(20, TextWithEntities(ques, entities=[]), OUT, multiple_choice=mpp, public_voters=publ, quiz=quizo), + Poll( + 20, + TextWithEntities(ques, entities=[]), + OUT, + multiple_choice=mpp, + public_voters=publ, + quiz=quizo, + ), correct_answers=karzo, ), ) diff --git a/plugins/profile.py b/plugins/profile.py index 32f9207..da650e5 100644 --- a/plugins/profile.py +++ b/plugins/profile.py @@ -25,6 +25,7 @@ Ex: `{i}poto 10` - uploads starting 10 pfps of user. Upload the photo of Chat/User if Available. """ + import os from telethon.tl.functions.account import UpdateProfileRequest diff --git a/plugins/qrcode.py b/plugins/qrcode.py index f31b337..f54bb81 100644 --- a/plugins/qrcode.py +++ b/plugins/qrcode.py @@ -16,6 +16,7 @@ β€’ `{i}qrdecode ` `It decodes the qrcode.` """ + import os from pyUltroid import ULTConfig diff --git a/plugins/resize.py b/plugins/resize.py index e346a75..71d75b2 100644 --- a/plugins/resize.py +++ b/plugins/resize.py @@ -14,6 +14,7 @@ To resize image on x, y axis. eg. `{i}resize 690 960` """ + from PIL import Image from . import HNDLR, eor, get_string, os, ultroid_cmd diff --git a/plugins/schedulemsg.py b/plugins/schedulemsg.py index 5a6f0dd..54bfd1f 100644 --- a/plugins/schedulemsg.py +++ b/plugins/schedulemsg.py @@ -12,6 +12,7 @@ eg. `{i}schedule Hello 100` It deliver msg after 100 sec. eg. `{i}schedule Hello 1h` It deliver msg after an hour. """ + from datetime import timedelta from pyUltroid.fns.admins import ban_time diff --git a/plugins/search.py b/plugins/search.py index 020e08c..c144c39 100644 --- a/plugins/search.py +++ b/plugins/search.py @@ -23,6 +23,7 @@ β€’ `{i}reverse` Reply an Image or sticker to find its sauce. """ + import os import requests diff --git a/plugins/snips.py b/plugins/snips.py index a7c7aae..35d7d0c 100644 --- a/plugins/snips.py +++ b/plugins/snips.py @@ -19,6 +19,7 @@ β€’ Use : type `$(ur snip word)` get setted reply. """ + import os from . import upload_file as uf diff --git a/plugins/specialtools.py b/plugins/specialtools.py index 52a448b..edfd519 100644 --- a/plugins/specialtools.py +++ b/plugins/specialtools.py @@ -31,6 +31,7 @@ β€’ `{i}wall ` Search Hd Wallpaper as Per ur Wish.. """ + import os import time from datetime import datetime as dt @@ -62,6 +63,7 @@ from .beautify import all_col File = [] scraper = create_scraper() + @ultroid_cmd( pattern="getaudio$", ) @@ -251,48 +253,49 @@ Zodiac -: {sign} reply_to=event.reply_to_msg_id, ) + session = Session() + @ultroid_cmd(pattern="sticker( (.*)|$)") async def _(event): x = event.pattern_match.group(1).strip() if not x: return await event.eor("`Give something to search`") uu = await event.eor(get_string("com_1")) - + headers = { - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" } - + max_retries = 3 retry_count = 0 - + while retry_count < max_retries: try: response = scraper.get( - f"https://combot.org/telegram/stickers?q={x}", - headers=headers + f"https://combot.org/telegram/stickers?q={x}", headers=headers ).content - + # Check if response contains Cloudflare challenge if "Just a moment..." in response.decode(): retry_count += 1 - await asyncio.sleep(2) # Wait before retry + await asyncio.sleep(2) # Wait before retry continue - + z = bs(response, "html.parser") packs = z.find_all("a", {"class": "stickerset__title"}) - + if not packs: return await uu.edit(get_string("spcltool_9")) - - break # Success - exit loop - + + break # Success - exit loop + except Exception as er: retry_count += 1 await asyncio.sleep(2) continue - + if retry_count >= max_retries: return await uu.edit("`Failed to fetch stickers after multiple retries`") try: @@ -311,10 +314,11 @@ async def _(event): for href, title in sticks.items(): a += f"{title}\n" await uu.edit(a, parse_mode="html") - + except Exception as e: await uu.edit(f"`Error: {str(e)}`\nTry again later.") + @ultroid_cmd(pattern="wall( (.*)|$)") async def wall(event): inp = event.pattern_match.group(1).strip() diff --git a/plugins/stickertools.py b/plugins/stickertools.py index 95839b2..52fb340 100644 --- a/plugins/stickertools.py +++ b/plugins/stickertools.py @@ -22,6 +22,7 @@ β€’ `{i}round ` To extract round sticker. """ + import glob import io import os diff --git a/plugins/stories.py b/plugins/stories.py index 3cecb19..a66f659 100644 --- a/plugins/stories.py +++ b/plugins/stories.py @@ -22,7 +22,14 @@ from . import ultroid_cmd, get_string, LOGS from telethon import TelegramClient from telethon.tl.functions.channels import GetFullChannelRequest -from telethon.tl.types import User, UserFull, InputPeerSelf, InputPrivacyValueAllowAll, Channel, InputUserSelf +from telethon.tl.types import ( + User, + UserFull, + InputPeerSelf, + InputPrivacyValueAllowAll, + Channel, + InputUserSelf, +) from telethon.tl.functions.stories import SendStoryRequest, GetStoriesByIDRequest from telethon.tl.functions.users import GetFullUserRequest from telethon.events import NewMessage @@ -37,14 +44,12 @@ async def setStory(event: NewMessage.Event): msg = await event.eor(get_string("com_1")) try: await event.client( - SendStoryRequest( - InputPeerSelf(), - reply.media, - privacy_rules=[ - InputPrivacyValueAllowAll() - ] + SendStoryRequest( + InputPeerSelf(), + reply.media, + privacy_rules=[InputPrivacyValueAllowAll()], + ) ) - ) await msg.eor("πŸ”₯ **Story is Live!**", time=5) except Exception as er: await msg.edit(f"__ERROR: {er}__") @@ -55,31 +60,28 @@ async def setStory(event: NewMessage.Event): async def downloadUserStories(event: NewMessage.Event): replied = await event.get_reply_message() message = await event.eor(get_string("com_1")) - + try: text_input = event.text.split(maxsplit=1)[1] # Check if input is a Telegram story link story_link_pattern = r"https?://t\.me/([^/]+)/s/(\d+)" match = re.match(story_link_pattern, text_input) - + if match: # Extract username and story ID from link username = match.group(1) story_id = int(match.group(2)) - + try: # Get the entity for the username entity = await event.client.get_entity(username) - + # Using GetStoriesByIDRequest to fetch the specific story stories_response = await event.client( - GetStoriesByIDRequest( - entity.id, - id=[story_id] - ) + GetStoriesByIDRequest(entity.id, id=[story_id]) ) print(stories_response) - + if not stories_response.stories: return await message.eor("ERROR: Story not found or expired!") @@ -87,23 +89,20 @@ async def downloadUserStories(event: NewMessage.Event): for story in stories_response.stories: client: TelegramClient = event.client file = await client.download_media(story.media) - caption = story.caption if hasattr(story, 'caption') else "" - await message.reply( - caption, - file=file - ) + caption = story.caption if hasattr(story, "caption") else "" + await message.reply(caption, file=file) os.remove(file) - + return await message.eor("**Uploaded Story!**", time=5) except Exception as er: await message.eor(f"ERROR while fetching story: __{er}__") LOGS.exception(er) return - + # If not a story link, proceed with the original functionality username = text_input - + except IndexError as er: LOGS.exception if replied and isinstance(replied.sender, User): @@ -112,12 +111,12 @@ async def downloadUserStories(event: NewMessage.Event): return await message.eor( "Please reply to a user, provide username or story link!" ) - + with suppress(ValueError): username = int(username) stories = None - + try: entity = await event.client.get_entity(username) if isinstance(entity, Channel): @@ -128,7 +127,7 @@ async def downloadUserStories(event: NewMessage.Event): else: full_user: UserFull = ( await event.client(GetFullUserRequest(id=username)) - ).full_user + ).full_user stories = full_user.stories except Exception as er: await message.eor(f"ERROR: __{er}__") @@ -140,11 +139,8 @@ async def downloadUserStories(event: NewMessage.Event): for story in stories.stories[:5]: client: TelegramClient = event.client file = await client.download_media(story.media) - caption = story.caption if hasattr(story, 'caption') else "" - await message.reply( - caption, - file=file - ) + caption = story.caption if hasattr(story, "caption") else "" + await message.reply(caption, file=file) os.remove(file) - await message.eor("**Uploaded Stories!**", time=5) \ No newline at end of file + await message.eor("**Uploaded Stories!**", time=5) diff --git a/plugins/tools.py b/plugins/tools.py index 9d57810..10720f2 100644 --- a/plugins/tools.py +++ b/plugins/tools.py @@ -33,6 +33,7 @@ β€’ `{i}webshot ` Get a screenshot of the webpage. """ + import glob import io import os @@ -323,7 +324,7 @@ async def _(e): tfls = "0 B" if not hb(fos + fls): ttol = "0 B" - text += f"\n\n`Folders` : `{foc}` : `{tfos}`\n`Files` : `{flc}` : `{tfls}`\n`Total` : `{flc+foc}` : `{ttol}`" + text += f"\n\n`Folders` : `{foc}` : `{tfos}`\n`Files` : `{flc}` : `{tfls}`\n`Total` : `{flc + foc}` : `{ttol}`" try: if (flc + foc) > 100: text = text.replace("`", "") @@ -335,7 +336,6 @@ async def _(e): await e.delete() - def sanga_seperator(sanga_list): string = "".join(info[info.find("\n") + 1 :] for info in sanga_list) string = re.sub(r"^$\n", "", string, flags=re.MULTILINE) @@ -460,4 +460,3 @@ async def webss(event): ) os.remove(pic) await xx.delete() - diff --git a/plugins/twitter.py b/plugins/twitter.py index 06613ce..dff2772 100644 --- a/plugins/twitter.py +++ b/plugins/twitter.py @@ -32,29 +32,34 @@ twitter_client = None # Get path to cookies file COOKIES_FILE = "resources/auth/twitter_cookies.json" + async def get_client(): global twitter_client if twitter_client: return twitter_client - - if not all(udB.get_key(key) for key in ["TWITTER_USERNAME", "TWITTER_EMAIL", "TWITTER_PASSWORD"]): - raise Exception("Set TWITTER_USERNAME, TWITTER_EMAIL and TWITTER_PASSWORD in vars first!") - + + if not all( + udB.get_key(key) + for key in ["TWITTER_USERNAME", "TWITTER_EMAIL", "TWITTER_PASSWORD"] + ): + raise Exception( + "Set TWITTER_USERNAME, TWITTER_EMAIL and TWITTER_PASSWORD in vars first!" + ) + # Create auth directory if it doesn't exist os.makedirs(os.path.dirname(COOKIES_FILE), exist_ok=True) - + client = Client() await client.login( auth_info_1=udB.get_key("TWITTER_USERNAME"), - auth_info_2=udB.get_key("TWITTER_EMAIL"), + auth_info_2=udB.get_key("TWITTER_EMAIL"), password=udB.get_key("TWITTER_PASSWORD"), - cookies_file=COOKIES_FILE + cookies_file=COOKIES_FILE, ) twitter_client = client return client - @ultroid_cmd(pattern="tw( (.*)|$)") async def tweet_cmd(event): """Post a tweet""" @@ -66,7 +71,9 @@ async def tweet_cmd(event): try: client = await get_client() tweet = await client.create_tweet(text=text) - await msg.edit(f"✨ **Successfully Posted!**\n\nπŸ”— https://x.com/{tweet.user.screen_name}/status/{tweet.id}") + await msg.edit( + f"✨ **Successfully Posted!**\n\nπŸ”— https://x.com/{tweet.user.screen_name}/status/{tweet.id}" + ) except Exception as e: await msg.edit(f"❌ **Error:**\n`{str(e)}`") @@ -82,6 +89,7 @@ async def twitter_details(event): try: client = await get_client() from urllib.parse import urlparse + parsed_url = urlparse(match) if parsed_url.hostname in ["twitter.com", "x.com"]: tweet_id = parsed_url.path.split("/")[-1].split("?")[0] @@ -96,7 +104,7 @@ async def twitter_details(event): text += f"πŸ”„ **Retweets:** `{tweet.metrics.retweets}`\n" text += f"πŸ’¬ **Replies:** `{tweet.metrics.replies}`\n" text += f"πŸ‘ **Views:** `{tweet.metrics.views}`\n" - + await msg.edit(text) except Exception as e: await msg.edit(f"❌ **Error:**\n`{str(e)}`") @@ -122,19 +130,16 @@ async def twitter_user(event): text += f"🐦 **Total Tweets:** `{user.statuses_count}`\n" text += f"πŸ“ **Location:** `{user.location or 'Not Set'}`\n" text += f"βœ… **Verified:** `{user.verified}`\n" - + if user.profile_image_url: image_url = user.profile_image_url.replace("_normal.", ".") await event.client.send_file( - event.chat_id, - file=image_url, - caption=text, - force_document=False + event.chat_id, file=image_url, caption=text, force_document=False ) await msg.delete() else: await msg.edit(text) - + except Exception as e: await msg.edit(f"❌ **Error:**\n`{str(e)}`") @@ -155,7 +160,7 @@ async def twitter_media(event): tweet_id = match tweet = await client.get_tweet_by_id(tweet_id) - + if not hasattr(tweet, "media"): return await msg.edit("πŸ˜• `No media found in tweet!`") @@ -169,30 +174,33 @@ async def twitter_media(event): for media in tweet.media: if media.type == "photo": await event.client.send_file( - event.chat_id, + event.chat_id, media.url, - caption=caption if media_count == 0 else None # Only add caption to first media + caption=caption + if media_count == 0 + else None, # Only add caption to first media ) media_count += 1 elif media.type == "video": if hasattr(media, "video_info") and isinstance(media.video_info, dict): variants = media.video_info.get("variants", []) mp4_variants = [ - v for v in variants + v + for v in variants if v.get("content_type") == "video/mp4" and "bitrate" in v ] if mp4_variants: best_video = max(mp4_variants, key=lambda x: x["bitrate"]) - video_caption = caption if media_count == 0 else "" # Only add tweet text to first media + video_caption = ( + caption if media_count == 0 else "" + ) # Only add tweet text to first media if video_caption: - video_caption += f"\nπŸŽ₯ Video Quality: {best_video['bitrate']/1000:.0f}kbps" + video_caption += f"\nπŸŽ₯ Video Quality: {best_video['bitrate'] / 1000:.0f}kbps" else: - video_caption = f"πŸŽ₯ Video Quality: {best_video['bitrate']/1000:.0f}kbps" - + video_caption = f"πŸŽ₯ Video Quality: {best_video['bitrate'] / 1000:.0f}kbps" + await event.client.send_file( - event.chat_id, - best_video["url"], - caption=video_caption + event.chat_id, best_video["url"], caption=video_caption ) media_count += 1 diff --git a/plugins/utilities.py b/plugins/utilities.py index 20cd792..1cdc9c7 100644 --- a/plugins/utilities.py +++ b/plugins/utilities.py @@ -266,9 +266,7 @@ async def _(event): done, data = await get_paste(message) if not done and data.get("error"): return await xx.eor(data["error"]) - reply_text = ( - f"β€’ **Pasted to SpaceBin :** [Space]({data['link']})\nβ€’ **Raw Url :** : [Raw]({data['raw']})" - ) + reply_text = f"β€’ **Pasted to SpaceBin :** [Space]({data['link']})\nβ€’ **Raw Url :** : [Raw]({data['raw']})" try: if event.client._bot: return await xx.eor(reply_text) @@ -718,13 +716,17 @@ async def get_video_duration(file_path): print("Error running ffprobe:", e) return None + async def get_thumbnail(file_path, thumbnail_path): try: await asyncio.create_subprocess_exec( "ffmpeg", - "-i", file_path, - "-ss", "00:00:04", - "-vframes", "1", # Extract a single frame as the thumbnail + "-i", + file_path, + "-ss", + "00:00:04", + "-vframes", + "1", # Extract a single frame as the thumbnail thumbnail_path, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, @@ -732,13 +734,14 @@ async def get_thumbnail(file_path, thumbnail_path): except Exception as e: print(f"Error extracting thumbnail: {e}") + @ultroid_cmd(pattern="getmsg( ?(.*)|$)") async def get_restricted_msg(event): match = event.pattern_match.group(1).strip() if not match: await event.eor("`Please provide a link!`", time=5) return - + xx = await event.eor("`Loading...`") chat, msg = get_chat_and_msgid(match) if not (chat and msg): @@ -748,40 +751,45 @@ async def get_restricted_msg(event): "`https://t.me/c/1313492028/3`\n" "`tg://openmessage?user_id=1234567890&message_id=1`" ) - + try: input_entity = await event.client.get_input_entity(chat) message = await event.client.get_messages(input_entity, ids=msg) except BaseException as er: return await event.eor(f"**ERROR**\n`{er}`") - + if not message: return await event.eor("`Message not found or may not exist.`") - + try: await event.client.send_message(event.chat_id, message) await xx.try_delete() return except ChatForwardsRestrictedError: pass - + if message.media: if isinstance(message.media, (MessageMediaPhoto, MessageMediaDocument)): - media_path, _ = await event.client.fast_downloader(message.document, show_progress=True, event=xx, message=get_string("com_5")) + media_path, _ = await event.client.fast_downloader( + message.document, + show_progress=True, + event=xx, + message=get_string("com_5"), + ) caption = message.text or "" attributes = [] if message.video: duration = await get_video_duration(media_path.name) - + width, height = 0, 0 for attribute in message.document.attributes: if isinstance(attribute, DocumentAttributeVideo): width = attribute.w height = attribute.h break - + thumb_path = media_path.name + "_thumb.jpg" await get_thumbnail(media_path.name, thumb_path) @@ -794,7 +802,9 @@ async def get_restricted_msg(event): ) ) await xx.edit(get_string("com_6")) - media_path, _ = await event.client.fast_uploader(media_path.name, event=xx, show_progress=True, to_delete=True) + media_path, _ = await event.client.fast_uploader( + media_path.name, event=xx, show_progress=True, to_delete=True + ) try: await event.client.send_file( @@ -826,4 +836,3 @@ async def get_restricted_msg(event): await event.eor("`Cannot process this type of media.`") else: await event.eor("`No media found in the message.`") - diff --git a/plugins/warn.py b/plugins/warn.py index 8d3a525..70a7c77 100644 --- a/plugins/warn.py +++ b/plugins/warn.py @@ -89,9 +89,9 @@ async def warn(e): ok = await ultroid_bot.get_entity(user) user = inline_mention(ok) r = r.split("|$|") - text = f"User {user} Got {action} Due to {count+1} Warns.\n\n" + text = f"User {user} Got {action} Due to {count + 1} Warns.\n\n" for x in range(c): - text += f"β€’**{x+1}.** {r[x]}\n" + text += f"β€’**{x + 1}.** {r[x]}\n" await e.eor(text) return reset_warn(e.chat_id, ok.id) add_warn(e.chat_id, user, count + 1, r) @@ -99,7 +99,7 @@ async def warn(e): user = inline_mention(ok) await eor( e, - f"**WARNING :** {count+1}/{number}\n**To :**{user}\n**Be Careful !!!**\n\n**Reason** : {reason}", + f"**WARNING :** {count + 1}/{number}\n**To :**{user}\n**Be Careful !!!**\n\n**Reason** : {reason}", ) @@ -156,7 +156,7 @@ async def twarns(e): r = r.split("|$|") text = f"User {user} Got {c} Warns.\n\n" for x in range(c): - text += f"β€’**{x+1}.** {r[x]}\n" + text += f"β€’**{x + 1}.** {r[x]}\n" await e.eor(text) else: await e.eor("`No Warnings`") diff --git a/plugins/weather.py b/plugins/weather.py index 2642033..87855dd 100644 --- a/plugins/weather.py +++ b/plugins/weather.py @@ -51,12 +51,14 @@ async def get_timezone(offset_seconds, use_utc=False): return f"{m} ({timezone}{sign}{hours:02d})" return "Timezone not found" + async def getWindinfo(speed: str, degree: str) -> str: dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] ix = round(degree / (360.00 / len(dirs))) kmph = str(float(speed) * 3.6) + " km/h" return f"[{dirs[ix % len(dirs)]}] {kmph}" + async def get_air_pollution_data(latitude, longitude, api_key): url = f"http://api.openweathermap.org/data/2.5/air_pollution?lat={latitude}&lon={longitude}&appid={api_key}" async with aiohttp.ClientSession() as session: diff --git a/plugins/words.py b/plugins/words.py index 22e5f8d..bc062a3 100644 --- a/plugins/words.py +++ b/plugins/words.py @@ -19,6 +19,7 @@ β€’ `{i}ud ` Fetch word defenition from urbandictionary. """ + import io from pyUltroid.fns.misc import get_synonyms_or_antonyms @@ -35,7 +36,7 @@ async def mean(event): url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{wrd}" out = await async_searcher(url, re_json=True) try: - return await event.eor(f'**{out["title"]}**') + return await event.eor(f"**{out['title']}**") except (KeyError, TypeError): pass defi = out[0]["meanings"][0]["definitions"][0] diff --git a/plugins/youtube.py b/plugins/youtube.py index fc129c0..3743ae3 100644 --- a/plugins/youtube.py +++ b/plugins/youtube.py @@ -19,6 +19,7 @@ β€’ `{i}ytsv <(youtube) search query>` Search and download video from youtube. """ + from pyUltroid.fns.ytdl import download_yt, get_yt_link from . import get_string, requests, ultroid_cmd diff --git a/plugins/ziptools.py b/plugins/ziptools.py index ab2674c..9c94ea4 100644 --- a/plugins/ziptools.py +++ b/plugins/ziptools.py @@ -22,6 +22,7 @@ To set Password: `{i}dozip ` """ + import os import time diff --git a/pyUltroid/__main__.py b/pyUltroid/__main__.py index 9de436f..95acd70 100644 --- a/pyUltroid/__main__.py +++ b/pyUltroid/__main__.py @@ -94,7 +94,7 @@ def main(): pass LOGS.info( - f"Took {time_formatter((time.time() - start_time)*1000)} to start β€’ULTROIDβ€’" + f"Took {time_formatter((time.time() - start_time) * 1000)} to start β€’ULTROIDβ€’" ) LOGS.info(suc_msg) diff --git a/pyUltroid/_misc/_decorators.py b/pyUltroid/_misc/_decorators.py index 94cea82..370be28 100644 --- a/pyUltroid/_misc/_decorators.py +++ b/pyUltroid/_misc/_decorators.py @@ -113,7 +113,7 @@ def ultroid_cmd( except FloodWaitError as fwerr: await asst.send_message( udB.get_key("LOG_CHANNEL"), - f"`FloodWaitError:\n{str(fwerr)}\n\nSleeping for {tf((fwerr.seconds + 10)*1000)}`", + f"`FloodWaitError:\n{str(fwerr)}\n\nSleeping for {tf((fwerr.seconds + 10) * 1000)}`", ) await ultroid_bot.disconnect() await asyncio.sleep(fwerr.seconds + 10) diff --git a/pyUltroid/_misc/_wrappers.py b/pyUltroid/_misc/_wrappers.py index 6625ec4..c11e904 100644 --- a/pyUltroid/_misc/_wrappers.py +++ b/pyUltroid/_misc/_wrappers.py @@ -26,7 +26,7 @@ async def eor(event, text=None, time=None, link_preview=False, edit_time=None, * text, link_preview=link_preview, reply_to=reply_to, - **args + **args, ) else: try: @@ -52,7 +52,7 @@ async def eod(event, text=None, **kwargs): async def _try_delete(event): try: return await event.delete() - except (MessageDeleteForbiddenError): + except MessageDeleteForbiddenError: pass except BaseException as er: from . import LOGS diff --git a/pyUltroid/exceptions.py b/pyUltroid/exceptions.py index bdba015..76c56d5 100644 --- a/pyUltroid/exceptions.py +++ b/pyUltroid/exceptions.py @@ -10,13 +10,10 @@ Exceptions which can be raised by py-Ultroid Itself. """ -class pyUltroidError(Exception): - ... +class pyUltroidError(Exception): ... -class DependencyMissingError(ImportError): - ... +class DependencyMissingError(ImportError): ... -class RunningAsFunctionLibError(pyUltroidError): - ... +class RunningAsFunctionLibError(pyUltroidError): ... diff --git a/pyUltroid/fns/FastTelethon.py b/pyUltroid/fns/FastTelethon.py index d400a20..4140c06 100644 --- a/pyUltroid/fns/FastTelethon.py +++ b/pyUltroid/fns/FastTelethon.py @@ -173,7 +173,7 @@ class ParallelTransferrer: def _get_connection_count( file_size: int, ) -> int: - full_size = 100 * (1024 ** 2) + full_size = 100 * (1024**2) if file_size > full_size: return 20 return math.ceil((file_size / full_size) * 20) @@ -283,7 +283,7 @@ class ParallelTransferrer: connection_count = connection_count or self._get_connection_count(file_size) part_size = (part_size_kb or utils.get_appropriated_part_size(file_size)) * 1024 part_count = (file_size + part_size - 1) // part_size - is_large = file_size > 10 * (1024 ** 2) + is_large = file_size > 10 * (1024**2) await self._init_upload(connection_count, file_id, part_count, is_large) return part_size, part_count, is_large diff --git a/pyUltroid/fns/admins.py b/pyUltroid/fns/admins.py index eb9551b..eec531f 100644 --- a/pyUltroid/fns/admins.py +++ b/pyUltroid/fns/admins.py @@ -138,7 +138,7 @@ def lock_unlock(query, lock=True): rights = types.ChatBannedRights(None) _do = lock if query == "msgs": - for i in ["send_messages", "invite_users", "pin_messages" "change_info"]: + for i in ["send_messages", "invite_users", "pin_messageschange_info"]: setattr(rights, i, _do) elif query == "media": setattr(rights, "send_media", _do) diff --git a/pyUltroid/fns/misc.py b/pyUltroid/fns/misc.py index 85369b1..4cb8fa1 100644 --- a/pyUltroid/fns/misc.py +++ b/pyUltroid/fns/misc.py @@ -62,6 +62,7 @@ except ImportError: uploader = CatboxUploader() + async def randomchannel( tochat, channel, range1, range2, caption=None, client=ultroid_bot ): @@ -195,7 +196,7 @@ async def unsplashsearch(query, limit=None, shuf=True): all_ = res.find_all("img", srcset=re.compile("images.unsplash.com/photo")) if shuf: shuffle(all_) - return list(map(lambda e: e['src'], all_[:limit])) + return list(map(lambda e: e["src"], all_[:limit])) # ---------------- Random User Gen ---------------- diff --git a/pyUltroid/fns/tools.py b/pyUltroid/fns/tools.py index daceef3..cfedf12 100644 --- a/pyUltroid/fns/tools.py +++ b/pyUltroid/fns/tools.py @@ -118,7 +118,7 @@ async def metadata(file): raise DependencyMissingError( f"'{_}' is not installed!\nInstall it to use this command." ) - + data = {} _info = json.loads(out)["media"] if not _info: @@ -391,61 +391,48 @@ class LogoHelper: async def get_paste(data: str, extension: str = "txt"): try: url = "https://spaceb.in/api/" - res = await async_searcher(url, json={"content": data, "extension": extension}, post=True, re_json=True) + res = await async_searcher( + url, json={"content": data, "extension": extension}, post=True, re_json=True + ) return True, { "link": f"https://spaceb.in/{res['payload']['id']}", - "raw": f"https://spaceb.in/{res['payload']['id']}/raw" + "raw": f"https://spaceb.in/{res['payload']['id']}/raw", } except Exception: try: url = "https://dpaste.org/api/" data = { - 'format': 'json', - 'content': data.encode('utf-8'), - 'lexer': extension, - 'expires': '604800', # expire in week + "format": "json", + "content": data.encode("utf-8"), + "lexer": extension, + "expires": "604800", # expire in week } res = await async_searcher(url, data=data, post=True, re_json=True) - return True, { - "link": res["url"], - "raw": f'{res["url"]}/raw' - } + return True, {"link": res["url"], "raw": f"{res['url']}/raw"} except Exception as e: LOGS.info(e) - return None, { - "link": None, - "raw": None, - "error": str(e) - } + return None, {"link": None, "raw": None, "error": str(e)} + # https://stackoverflow.com/a/74563494 async def get_google_images(query): """Get image results from Google Custom Search API. - + Args: query (str): Search query string - + Returns: list: List of dicts containing image info (title, link, source, thumbnail, original) """ LOGS.info(f"Searching Google Images for: {query}") - + # Google Custom Search API credentials google_keys = [ - { - "key": "AIzaSyAj75v6vHWLJdJaYcj44tLz7bdsrh2g7Y0", - "cx": "712a54749d99a449e" - }, - { - "key": "AIzaSyDFQQwPLCzcJ9FDao-B7zDusBxk8GoZ0HY", - "cx": "001bbd139705f44a6" - }, - { - "key": "AIzaSyD0sRNZUa8-0kq9LAREDAFKLNO1HPmikRU", - "cx": "4717c609c54e24250" - } + {"key": "AIzaSyAj75v6vHWLJdJaYcj44tLz7bdsrh2g7Y0", "cx": "712a54749d99a449e"}, + {"key": "AIzaSyDFQQwPLCzcJ9FDao-B7zDusBxk8GoZ0HY", "cx": "001bbd139705f44a6"}, + {"key": "AIzaSyD0sRNZUa8-0kq9LAREDAFKLNO1HPmikRU", "cx": "4717c609c54e24250"}, ] key_index = random.randint(0, len(google_keys) - 1) GOOGLE_API_KEY = google_keys[key_index]["key"] @@ -460,35 +447,39 @@ async def get_google_images(query): "&searchType=image" "&num=10" # Number of results ) - + # Make API request response = await async_searcher(url, re_json=True) print("response") if not response or "items" not in response: LOGS.error("No results from Google Custom Search API") return [] - + # Process results google_images = [] for item in response["items"]: try: - google_images.append({ - "title": item.get("title", ""), - "link": item.get("contextLink", ""), # Page containing image - "source": item.get("displayLink", ""), - "thumbnail": item.get("image", {}).get("thumbnailLink", item["link"]), - "original": item["link"] # Original image URL - }) + google_images.append( + { + "title": item.get("title", ""), + "link": item.get("contextLink", ""), # Page containing image + "source": item.get("displayLink", ""), + "thumbnail": item.get("image", {}).get( + "thumbnailLink", item["link"] + ), + "original": item["link"], # Original image URL + } + ) except Exception as e: LOGS.warning(f"Failed to process image result: {str(e)}") continue - + # Randomize results order random.shuffle(google_images) - + LOGS.info(f"Found {len(google_images)} images for query: {query}") return google_images - + except Exception as e: LOGS.exception(f"Error in get_google_images: {str(e)}") return [] @@ -507,6 +498,7 @@ async def get_chatbot_reply(message): except Exception: LOGS.info(f"**ERROR:**`{format_exc()}`") + def check_filename(filroid): if os.path.exists(filroid): no = 1 @@ -724,7 +716,6 @@ def translate(text, lang_tgt="en", lang_src="auto", timeout=60, detect=False): return (text, None) if detect else text - def cmd_regex_replace(cmd): return ( cmd.replace("$", "") @@ -744,8 +735,7 @@ def cmd_regex_replace(cmd): # ------------------------# -class LottieException(Exception): - ... +class LottieException(Exception): ... class TgConverter: @@ -762,7 +752,7 @@ class TgConverter: ) else: er, out = await bash(f"lottie_convert.py '{file}' '{out_path}'") - + if er: LOGS.error(f"Error in animated_sticker conversion: {er}") if throw: @@ -806,7 +796,7 @@ class TgConverter: try: image = Image.open(photo) original_size = (image.width, image.height) - + if (image.width and image.height) < 512: size1 = image.width size2 = image.height @@ -825,7 +815,7 @@ class TgConverter: else: maxsize = (512, 512) image.thumbnail(maxsize) - + LOGS.info(f"Resized image from {original_size} to {image.size}") return image except Exception as e: @@ -839,7 +829,9 @@ class TgConverter: input_, name=output[:-5], remove=remove ) if output.endswith(".gif"): - out, er = await bash(f"ffmpeg -i '{input_}' -an -sn -c:v copy '{output}.mp4' -y") + out, er = await bash( + f"ffmpeg -i '{input_}' -an -sn -c:v copy '{output}.mp4' -y" + ) LOGS.info(f"FFmpeg output: {out}, Error: {er}") else: out, er = await bash(f"ffmpeg -i '{input_}' '{output}' -y") @@ -856,7 +848,7 @@ class TgConverter: _ = await metadata(file) name += ".webm" h, w = _["height"], _["width"] - + if h == w and h != 512: h, w = 512, 512 if h != 512 or w != 512: @@ -864,19 +856,19 @@ class TgConverter: h, w = 512, -1 if w > h: h, w = -1, 512 - + await bash( f'ffmpeg -i "{file}" -preset fast -an -to 00:00:03 -crf 30 -bufsize 256k -b:v {_["bitrate"]} -vf "scale={w}:{h},fps=30" -c:v libvpx-vp9 "{name}" -y' ) - + if remove and os.path.exists(file): os.remove(file) LOGS.info(f"Removed original file: {file}") - + if os.path.exists(name): LOGS.info(f"Successfully created webm: {name}") return name - + LOGS.error(f"Webm creation failed - output file not created: {name}") return None except Exception as e: @@ -891,37 +883,39 @@ class TgConverter: if not input_: LOGS.error("Input file is None") return None - + if not os.path.exists(input_): LOGS.error(f"Input file does not exist: {input_}") return None - + try: import cv2 except ImportError: - raise DependencyMissingError("This function needs 'cv2' to be installed.") - + raise DependencyMissingError( + "This function needs 'cv2' to be installed." + ) + img = cv2.VideoCapture(input_) success, frame = img.read() - + if not success: LOGS.error(f"Failed to read frame from {input_}") return None - + cv2.imwrite(name, frame) img.release() - + if not os.path.exists(name): LOGS.error(f"Failed to save image: {name}") return None - + if remove and os.path.exists(input_): os.remove(input_) LOGS.info(f"Removed original file: {input_}") - + LOGS.info(f"Successfully converted to image: {name}") return name - + except Exception as e: LOGS.exception(f"Error in to_image conversion: {str(e)}") return None @@ -936,11 +930,11 @@ class TgConverter: ): """Convert between different file formats.""" LOGS.info(f"Converting {input_file} to {convert_to or allowed_formats}") - + if not input_file: LOGS.error("Input file is None") return None - + if not os.path.exists(input_file): LOGS.error(f"Input file does not exist: {input_file}") return None @@ -977,8 +971,10 @@ class TgConverter: input_file, convert_to="gif", remove_old=remove_old ) if gif_file: - return await TgConverter.create_webm(gif_file, outname, remove=True) - + return await TgConverter.create_webm( + gif_file, outname, remove=True + ) + # Json -> Tgs elif ext == "json": if recycle_type("tgs"): @@ -986,7 +982,7 @@ class TgConverter: return await TgConverter.animated_sticker( input_file, name, remove=remove_old ) - + # Video to Something elif ext in ["webm", "mp4", "gif"]: for exte in ["webm", "mp4", "gif"]: @@ -997,14 +993,16 @@ class TgConverter: ) if result: return result - + for exte in ["png", "jpg", "jpeg", "webp"]: if recycle_type(exte): name = outname + "." + exte - result = TgConverter.to_image(input_file, name, remove=remove_old) + result = TgConverter.to_image( + input_file, name, remove=remove_old + ) if result: return result - + # Image to Something elif ext in ["jpg", "jpeg", "png", "webp"]: for extn in ["png", "webp", "ico"]: @@ -1020,7 +1018,7 @@ class TgConverter: except Exception as e: LOGS.error(f"Failed to convert image to {extn}: {str(e)}") continue - + for extn in ["webm", "gif", "mp4"]: if recycle_type(extn): name = outname + "." + extn @@ -1038,10 +1036,12 @@ class TgConverter: return await TgConverter.ffmpeg_convert( input_file, name, remove=remove_old ) - - LOGS.error(f"No valid conversion found for {input_file} to {convert_to or allowed_formats}") + + LOGS.error( + f"No valid conversion found for {input_file} to {convert_to or allowed_formats}" + ) return None - + except Exception as e: LOGS.exception(f"Error in convert: {str(e)}") return None diff --git a/pyUltroid/fns/ytdl.py b/pyUltroid/fns/ytdl.py index c4d97d1..d33ef65 100644 --- a/pyUltroid/fns/ytdl.py +++ b/pyUltroid/fns/ytdl.py @@ -33,7 +33,7 @@ async def ytdl_progress(k, start_time, event): + f"Total Size: {humanbytes(k['total_bytes'])}\n" + f"Downloaded: {humanbytes(k['downloaded_bytes'])}\n" + f"Speed: {humanbytes(k['speed'])}/s\n" - + f"ETA: {time_formatter(k['eta']*1000)}`" + + f"ETA: {time_formatter(k['eta'] * 1000)}`" ) if round((time.time() - start_time) % 10.0) == 0: try: diff --git a/pyUltroid/startup/BaseClient.py b/pyUltroid/startup/BaseClient.py index 603121b..f31661c 100644 --- a/pyUltroid/startup/BaseClient.py +++ b/pyUltroid/startup/BaseClient.py @@ -114,7 +114,7 @@ class UltroidClient(TelegramClient): by_bot = self._bot size = os.path.getsize(file) # Don't show progress bar when file size is less than 5MB. - if size < 5 * 2 ** 20: + if size < 5 * 2**20: show_progress = False if use_cache and self._cache and self._cache.get("upload_cache"): for files in self._cache["upload_cache"]: @@ -171,7 +171,7 @@ class UltroidClient(TelegramClient): if show_progress: event = kwargs["event"] # Don't show progress bar when file size is less than 10MB. - if file.size < 10 * 2 ** 20: + if file.size < 10 * 2**20: show_progress = False import mimetypes diff --git a/pyUltroid/startup/__init__.py b/pyUltroid/startup/__init__.py index 8d8063a..df8cacd 100644 --- a/pyUltroid/startup/__init__.py +++ b/pyUltroid/startup/__init__.py @@ -73,7 +73,6 @@ if run_as_module: handlers=[FileHandler(file), StreamHandler()], ) try: - import coloredlogs coloredlogs.install(level=None, logger=LOGS, fmt=_LOG_FORMAT) diff --git a/pyUltroid/startup/funcs.py b/pyUltroid/startup/funcs.py index f5338fa..93eca32 100644 --- a/pyUltroid/startup/funcs.py +++ b/pyUltroid/startup/funcs.py @@ -90,6 +90,7 @@ async def autoupdate_local_database(): def update_envs(): """Update Var. attributes to udB""" from .. import udB + _envs = [*list(os.environ)] if ".env" in os.listdir("."): [_envs.append(_) for _ in list(RepositoryEnv(config._find_file(".")).data)] @@ -411,7 +412,7 @@ async def plug(plugin_channels): f.write("from plugins import *\n\nbot = ultroid_bot") LOGS.info("β€’ Loading Plugins from Plugin Channel(s) β€’") for chat in plugin_channels: - LOGS.info(f"{'β€’'*4} {chat}") + LOGS.info(f"{'β€’' * 4} {chat}") try: async for x in ultroid_bot.iter_messages( chat, search=".py", filter=InputMessagesFilterDocument, wait_time=10 @@ -432,7 +433,6 @@ async def plug(plugin_channels): LOGS.exception(er) - async def ready(): from .. import asst, udB, ultroid_bot diff --git a/pyUltroid/startup/loader.py b/pyUltroid/startup/loader.py index 5f49114..6975589 100644 --- a/pyUltroid/startup/loader.py +++ b/pyUltroid/startup/loader.py @@ -46,7 +46,6 @@ def _after_load(loader, module, plugin_name=""): def load_other_plugins(addons=None, pmbot=None, manager=None, vcbot=None): - # for official _exclude = udB.get_key("EXCLUDE_OFFICIAL") or config("EXCLUDE_OFFICIAL", None) _exclude = _exclude.split() if _exclude else [] diff --git a/resources/session/ssgen.py b/resources/session/ssgen.py index e3522cf..c30f663 100644 --- a/resources/session/ssgen.py +++ b/resources/session/ssgen.py @@ -56,6 +56,7 @@ def telethon_session(): try: spinner("tele") import telethon + x = "\bFound an existing installation of Telethon...\nSuccessfully Imported.\n\n" except ImportError: print("Installing Telethon...") @@ -123,7 +124,7 @@ def pyro_session(): os.system("pip install pyrogram tgcrypto") x = "\bDone. Installed and imported Pyrogram." from pyrogram import Client - + clear_screen() print(ULTROID) print(x) @@ -132,7 +133,9 @@ def pyro_session(): API_ID, API_HASH = get_api_id_and_hash() print("Enter phone number when asked.\n\n") try: - with Client(name="ultroid", api_id=API_ID, api_hash=API_HASH, in_memory=True) as pyro: + with Client( + name="ultroid", api_id=API_ID, api_hash=API_HASH, in_memory=True + ) as pyro: ss = pyro.export_session_string() pyro.send_message( "me", @@ -141,8 +144,10 @@ def pyro_session(): print("Session has been sent to your saved messages!") exit(0) except Exception as er: - print("Unexpected error occurred while creating session, make sure to validate your inputs.") - print(er) + print( + "Unexpected error occurred while creating session, make sure to validate your inputs." + ) + print(er) def main(): diff --git a/resources/startup/_termux.py b/resources/startup/_termux.py index 95a6527..fea3ec5 100644 --- a/resources/startup/_termux.py +++ b/resources/startup/_termux.py @@ -230,7 +230,7 @@ print( {Fore.YELLOW}# Installing other non mandatory requirements. (You can Install them, if you want command using them to work!){Fore.RESET} -{'- '.join(list(OPT_PACKAGES.keys()))} +{"- ".join(list(OPT_PACKAGES.keys()))} Enter [ A = Ask for each, I = Install all, S = Skip, E = Exit]""" ) diff --git a/resources/startup/locals.py b/resources/startup/locals.py index 024cef3..463119f 100644 --- a/resources/startup/locals.py +++ b/resources/startup/locals.py @@ -21,7 +21,6 @@ a = r""" def start(): - clear_screen() check_for_py()