From 2aa93bb4d51563a15bcecc647596b1bb762eafba Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Tue, 30 Jul 2024 11:52:58 +0700 Subject: [PATCH] style: format code with isort, Ruff Formatter and Yapf (#300) * style: format code with isort, Ruff Formatter and Yapf This commit fixes the style issues introduced in f9f107e according to the output from isort, Ruff Formatter and Yapf. Details: None * refactor: autofix issues in 2 files Resolved issues in the following files with DeepSource Autofix: 1. misskaty/plugins/download_upload.py 2. misskaty/plugins/nightmodev2.py * style: format code with isort, Ruff Formatter and Yapf This commit fixes the style issues introduced in 1bc1345 according to the output from isort, Ruff Formatter and Yapf. Details: https://github.com/yasirarism/MissKatyPyro/pull/300 * refactor: autofix issues in 2 files Resolved issues in the following files with DeepSource Autofix: 1. misskaty/plugins/dev.py 2. misskaty/plugins/misc_tools.py * style: format code with isort, Ruff Formatter and Yapf This commit fixes the style issues introduced in 58d2f1a according to the output from isort, Ruff Formatter and Yapf. Details: https://github.com/yasirarism/MissKatyPyro/pull/300 --------- Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com> Co-authored-by: Yasir Aris M --- database/__init__.py | 9 +- database/feds_db.py | 11 +- database/greetings_db.py | 3 + database/notes_db.py | 2 +- misskaty/__init__.py | 8 +- misskaty/__main__.py | 21 +- misskaty/core/misskaty_patch/bound/message.py | 3 +- .../misskaty_patch/decorators/adminsOnly.py | 4 +- .../core/misskaty_patch/decorators/command.py | 2 +- .../methods/edit_message_text.py | 2 +- .../core/misskaty_patch/utils/get_user.py | 4 +- .../misskaty_patch/utils/handler_error.py | 4 +- misskaty/core/misskaty_patch/utils/utils.py | 1 + misskaty/helper/__init__.py | 4 +- misskaty/helper/files.py | 1 + misskaty/helper/http.py | 2 +- misskaty/helper/human_read.py | 4 +- misskaty/helper/kuso_utils.py | 105 ++++++++-- misskaty/helper/misc.py | 4 +- misskaty/helper/stickerset.py | 1 + misskaty/helper/tools.py | 46 +++-- misskaty/plugins/__init__.py | 11 +- misskaty/plugins/admin.py | 28 ++- misskaty/plugins/auto_approve.py | 9 +- misskaty/plugins/autoapprove.py | 23 +-- misskaty/plugins/ban_user_or_chat.py | 5 +- misskaty/plugins/blacklist_chat.py | 7 +- misskaty/plugins/broadcast.py | 4 +- misskaty/plugins/bypass.py | 16 +- misskaty/plugins/chatbot_ai.py | 37 ++-- misskaty/plugins/dev.py | 1 - misskaty/plugins/download_upload.py | 79 +++++--- misskaty/plugins/federation.py | 30 +-- misskaty/plugins/filter_request.py | 17 +- misskaty/plugins/filters.py | 46 +++-- misskaty/plugins/fun.py | 12 +- misskaty/plugins/genss.py | 21 +- misskaty/plugins/grup_tools.py | 6 +- misskaty/plugins/imdb_search.py | 92 ++++++--- misskaty/plugins/inline_search.py | 13 +- misskaty/plugins/json.py | 8 +- misskaty/plugins/locks.py | 3 +- misskaty/plugins/media_extractor.py | 9 +- misskaty/plugins/mediainfo.py | 25 ++- misskaty/plugins/misc_tools.py | 5 +- misskaty/plugins/nightmodev2.py | 5 +- misskaty/plugins/notes.py | 59 ++++-- misskaty/plugins/ocr.py | 9 +- misskaty/plugins/paste.py | 17 +- misskaty/plugins/ping.py | 11 +- misskaty/plugins/pypi_search.py | 9 +- misskaty/plugins/session_generator.py | 1 - misskaty/plugins/start_help.py | 44 +++-- misskaty/plugins/stickers.py | 2 +- misskaty/plugins/ubot_plugin.py | 9 +- misskaty/plugins/web_scraper.py | 182 ++++++++++++------ misskaty/plugins/webss.py | 4 +- misskaty/plugins/ytdl_plugins.py | 8 +- update.py | 4 +- utils.py | 6 +- 60 files changed, 747 insertions(+), 371 deletions(-) diff --git a/database/__init__.py b/database/__init__.py index 0da3654d..8f5eb260 100644 --- a/database/__init__.py +++ b/database/__init__.py @@ -1,9 +1,10 @@ """ - * @author yasir - * @date 2022-09-06 10:12:09 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved +* @author yasir +* @date 2022-09-06 10:12:09 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved """ + from async_pymongo import AsyncClient from misskaty.vars import DATABASE_NAME, DATABASE_URI diff --git a/database/feds_db.py b/database/feds_db.py index f5a19649..ad0da3e0 100644 --- a/database/feds_db.py +++ b/database/feds_db.py @@ -1,8 +1,9 @@ -import pytz from datetime import datetime -from misskaty.vars import SUDO -from database import dbname +import pytz + +from database import dbname +from misskaty.vars import SUDO fedsdb = dbname["federation"] @@ -32,9 +33,7 @@ async def get_feds_by_owner(owner_id): feds = await cursor.to_list(length=None) if not feds: return False - return [ - {"fed_id": fed["fed_id"], "fed_name": fed["fed_name"]} for fed in feds - ] + return [{"fed_id": fed["fed_id"], "fed_name": fed["fed_name"]} for fed in feds] async def transfer_owner(fed_id, current_owner_id, new_owner_id): diff --git a/database/greetings_db.py b/database/greetings_db.py index 6eb64d6c..c1327062 100644 --- a/database/greetings_db.py +++ b/database/greetings_db.py @@ -2,9 +2,11 @@ from database import dbname greetingdb = dbname["greetings"] + async def is_welcome(chat_id: int) -> bool: return bool(await greetingdb.find_one({"chat_id": chat_id})) + async def toggle_welcome(chat_id: int): if await is_welcome(chat_id): await greetingdb.delete_one({"chat_id": chat_id}) @@ -13,4 +15,5 @@ async def toggle_welcome(chat_id: int): await greetingdb.insert_one({"chat_id": chat_id}) return True + # todo other features for custom welcome here diff --git a/database/notes_db.py b/database/notes_db.py index b72b5e55..a195d44d 100644 --- a/database/notes_db.py +++ b/database/notes_db.py @@ -45,4 +45,4 @@ async def save_note(chat_id: int, name: str, note: dict): async def deleteall_notes(chat_id: int): - return await notesdb.delete_one({"chat_id": chat_id}) \ No newline at end of file + return await notesdb.delete_one({"chat_id": chat_id}) diff --git a/misskaty/__init__.py b/misskaty/__init__.py index 625fa85f..d343eadf 100644 --- a/misskaty/__init__.py +++ b/misskaty/__init__.py @@ -2,11 +2,13 @@ # * @date 2023-06-21 22:12:27 # * @projectName MissKatyPyro # * Copyright ©YasirPedia All rights reserved -import time, os, uvloop +import os +import time from asyncio import get_event_loop from faulthandler import enable as faulthandler_enable from logging import ERROR, INFO, StreamHandler, basicConfig, getLogger, handlers +import uvloop from apscheduler.jobstores.mongodb import MongoDBJobStore from apscheduler.schedulers.asyncio import AsyncIOScheduler from async_pymongo import AsyncClient @@ -28,7 +30,9 @@ basicConfig( format="[%(levelname)s] - [%(asctime)s - %(name)s - %(message)s] -> [%(module)s:%(lineno)d]", datefmt="%d-%b-%y %H:%M:%S", handlers=[ - handlers.RotatingFileHandler("MissKatyLogs.txt", mode="w+", maxBytes=5242880, backupCount=1), + handlers.RotatingFileHandler( + "MissKatyLogs.txt", mode="w+", maxBytes=5242880, backupCount=1 + ), StreamHandler(), ], ) diff --git a/misskaty/__main__.py b/misskaty/__main__.py index 33580207..9ab25ecf 100644 --- a/misskaty/__main__.py +++ b/misskaty/__main__.py @@ -1,9 +1,10 @@ """ - * @author yasir - * @date 2022-12-01 09:12:27 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved - """ +* @author yasir +* @date 2022-12-01 09:12:27 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved +""" + import asyncio import importlib import os @@ -15,7 +16,15 @@ from pyrogram import __version__, idle from pyrogram.raw.all import layer from database import dbname -from misskaty import BOT_NAME, BOT_USERNAME, HELPABLE, UBOT_NAME, app, scheduler, get_event_loop +from misskaty import ( + BOT_NAME, + BOT_USERNAME, + HELPABLE, + UBOT_NAME, + app, + get_event_loop, + scheduler, +) from misskaty.plugins import ALL_MODULES from misskaty.plugins.web_scraper import web from misskaty.vars import SUDO, USER_SESSION diff --git a/misskaty/core/misskaty_patch/bound/message.py b/misskaty/core/misskaty_patch/bound/message.py index 935206a1..885fe76a 100644 --- a/misskaty/core/misskaty_patch/bound/message.py +++ b/misskaty/core/misskaty_patch/bound/message.py @@ -6,8 +6,8 @@ from logging import getLogger from typing import Union from pyrogram.errors import ( - ChatAdminRequired, ChannelPrivate, + ChatAdminRequired, ChatSendPlainForbidden, ChatWriteForbidden, FloodWait, @@ -22,6 +22,7 @@ from pyrogram.types import Message LOGGER = getLogger("MissKaty") + @property def parse_cmd(msg): return msg.text.split(None, 1)[1] if len(msg.command) > 1 else None diff --git a/misskaty/core/misskaty_patch/decorators/adminsOnly.py b/misskaty/core/misskaty_patch/decorators/adminsOnly.py index 2a6e6542..e94b3c48 100644 --- a/misskaty/core/misskaty_patch/decorators/adminsOnly.py +++ b/misskaty/core/misskaty_patch/decorators/adminsOnly.py @@ -66,7 +66,9 @@ async def anonymous_admin_verification( try: member = await CallbackQuery.message.chat.get_member(CallbackQuery.from_user.id) except pyrogram.errors.exceptions.bad_request_400.UserNotParticipant: - return await CallbackQuery.answer("You're not member of this group.", show_alert=True) + return await CallbackQuery.answer( + "You're not member of this group.", show_alert=True + ) except pyrogram.errors.exceptions.forbidden_403.ChatAdminRequired: return await CallbackQuery.message.edit_text( "I must be admin to execute this task, or i will leave from this group.", diff --git a/misskaty/core/misskaty_patch/decorators/command.py b/misskaty/core/misskaty_patch/decorators/command.py index 46198467..0f4c82a6 100644 --- a/misskaty/core/misskaty_patch/decorators/command.py +++ b/misskaty/core/misskaty_patch/decorators/command.py @@ -21,7 +21,7 @@ def command( handler: typing.Optional[list] = None, filtercmd: typing.Union[pyrogram.filters.Filter] = None, *args, - **kwargs + **kwargs, ): """ ### `tgClient.command` diff --git a/misskaty/core/misskaty_patch/methods/edit_message_text.py b/misskaty/core/misskaty_patch/methods/edit_message_text.py index b35edfd1..73352daf 100644 --- a/misskaty/core/misskaty_patch/methods/edit_message_text.py +++ b/misskaty/core/misskaty_patch/methods/edit_message_text.py @@ -12,7 +12,7 @@ async def edit_message_text( text: str, del_in: int = 0, *args, - **kwargs + **kwargs, ) -> Union["Message", bool]: """\nExample: message.edit_text("hello") diff --git a/misskaty/core/misskaty_patch/utils/get_user.py b/misskaty/core/misskaty_patch/utils/get_user.py index 0cf6f0e5..18e8a882 100644 --- a/misskaty/core/misskaty_patch/utils/get_user.py +++ b/misskaty/core/misskaty_patch/utils/get_user.py @@ -23,7 +23,7 @@ import pyrogram async def get_user( - m: typing.Union[pyrogram.types.Message, pyrogram.types.CallbackQuery] + m: typing.Union[pyrogram.types.Message, pyrogram.types.CallbackQuery], ) -> pyrogram.types.User or bool: """ ### `tgEasy.get_user` @@ -75,7 +75,7 @@ async def get_user( async def get_user_adv( - m: typing.Union[pyrogram.types.Message, pyrogram.types.CallbackQuery] + m: typing.Union[pyrogram.types.Message, pyrogram.types.CallbackQuery], ) -> pyrogram.types.User or bool: """ ### `tgEasy.get_user_adv` diff --git a/misskaty/core/misskaty_patch/utils/handler_error.py b/misskaty/core/misskaty_patch/utils/handler_error.py index 0581dddb..f01d03a3 100644 --- a/misskaty/core/misskaty_patch/utils/handler_error.py +++ b/misskaty/core/misskaty_patch/utils/handler_error.py @@ -53,7 +53,9 @@ async def handle_error( f_errname = f"crash_{tgl_now.strftime('%d %B %Y')}.txt" LOGGER.error(traceback.format_exc()) with open(f_errname, "w+", encoding="utf-8") as log: - log.write(f"✍️ Message: {m.text or m.caption}\n👱‍♂️ User: {m.from_user.id if m.from_user else m.sender_chat.id}\n\n{traceback.format_exc()}") + log.write( + f"✍️ Message: {m.text or m.caption}\n👱‍♂️ User: {m.from_user.id if m.from_user else m.sender_chat.id}\n\n{traceback.format_exc()}" + ) log.close() if isinstance(m, pyrogram.types.Message): with contextlib.suppress(Exception): diff --git a/misskaty/core/misskaty_patch/utils/utils.py b/misskaty/core/misskaty_patch/utils/utils.py index 444d94c2..a442beab 100644 --- a/misskaty/core/misskaty_patch/utils/utils.py +++ b/misskaty/core/misskaty_patch/utils/utils.py @@ -17,6 +17,7 @@ GNU General Public License for more details. You should have received a copy of the GNU General Public License along with pyromod. If not, see . """ + from contextlib import asynccontextmanager, contextmanager from inspect import iscoroutinefunction from logging import getLogger diff --git a/misskaty/helper/__init__.py b/misskaty/helper/__init__.py index fe72798d..42d65aa5 100644 --- a/misskaty/helper/__init__.py +++ b/misskaty/helper/__init__.py @@ -3,8 +3,8 @@ from .files import * from .functions import * from .http import * from .human_read import * -from .localization import * from .kuso_utils import * +from .localization import * from .media_helper import * from .misc import * from .pyro_progress import * @@ -13,4 +13,4 @@ from .stickerset import * from .subscene_helper import * from .time_gap import * from .tools import * -from .ytdl_helper import * \ No newline at end of file +from .ytdl_helper import * diff --git a/misskaty/helper/files.py b/misskaty/helper/files.py index d8f8079f..06d78aec 100644 --- a/misskaty/helper/files.py +++ b/misskaty/helper/files.py @@ -17,6 +17,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ + import math import os diff --git a/misskaty/helper/http.py b/misskaty/helper/http.py index 92f0be57..612a4194 100644 --- a/misskaty/helper/http.py +++ b/misskaty/helper/http.py @@ -1,7 +1,7 @@ from asyncio import gather -from httpx import AsyncClient, Timeout from aiohttp import ClientSession +from httpx import AsyncClient, Timeout # Aiohttp Async Client session = ClientSession() diff --git a/misskaty/helper/human_read.py b/misskaty/helper/human_read.py index 92d790ac..36f00e69 100644 --- a/misskaty/helper/human_read.py +++ b/misskaty/helper/human_read.py @@ -8,7 +8,9 @@ def get_readable_file_size(size_in_bytes) -> str: while size_in_bytes >= 1024 and index < len(SIZE_UNITS) - 1: size_in_bytes /= 1024 index += 1 - return f"{size_in_bytes:.2f} {SIZE_UNITS[index]}" if index > 0 else f"{size_in_bytes}B" + return ( + f"{size_in_bytes:.2f} {SIZE_UNITS[index]}" if index > 0 else f"{size_in_bytes}B" + ) def get_readable_time(seconds: int) -> str: diff --git a/misskaty/helper/kuso_utils.py b/misskaty/helper/kuso_utils.py index 91daa1af..f0d39497 100644 --- a/misskaty/helper/kuso_utils.py +++ b/misskaty/helper/kuso_utils.py @@ -1,11 +1,11 @@ import logging import traceback from html import escape +from typing import Optional import chevron from bs4 import BeautifulSoup from telegraph.aio import Telegraph -from typing import Optional from misskaty import BOT_USERNAME from misskaty.helper.http import fetch @@ -26,23 +26,85 @@ async def kusonimeBypass(url: str): # title = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > p:nth-child(3) > strong")[0].text.strip() try: title = soup.find("h1", {"class": "jdlz"}).text # fix title njing haha - season = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(3)")[0].text.split(":").pop().strip() - tipe = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(5)")[0].text.split(":").pop().strip() - status_anime = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(6)")[0].text.split(":").pop().strip() - ep = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(7)")[0].text.split(":").pop().strip() - score = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(8)")[0].text.split(":").pop().strip() - duration = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(9)")[0].text.split(":").pop().strip() - rilis = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(10)")[0].text.split(":").pop().strip() + season = ( + soup.select( + "#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(3)" + )[0] + .text.split(":") + .pop() + .strip() + ) + tipe = ( + soup.select( + "#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(5)" + )[0] + .text.split(":") + .pop() + .strip() + ) + status_anime = ( + soup.select( + "#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(6)" + )[0] + .text.split(":") + .pop() + .strip() + ) + ep = ( + soup.select( + "#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(7)" + )[0] + .text.split(":") + .pop() + .strip() + ) + score = ( + soup.select( + "#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(8)" + )[0] + .text.split(":") + .pop() + .strip() + ) + duration = ( + soup.select( + "#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(9)" + )[0] + .text.split(":") + .pop() + .strip() + ) + rilis = ( + soup.select( + "#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(10)" + )[0] + .text.split(":") + .pop() + .strip() + ) except Exception: e = traceback.format_exc() LOGGER.error(e) - title, season, tipe, status_anime, ep, score, duration, rilis = "None", "None", "None", "None", 0, 0, 0, "None" + title, season, tipe, status_anime, ep, score, duration, rilis = ( + "None", + "None", + "None", + "None", + 0, + 0, + 0, + "None", + ) num = 1 genre = [] - for _genre in soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(2)"): + for _genre in soup.select( + "#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(2)" + ): gen = _genre.text.split(":").pop().strip().split(", ") genre = gen - for smokedl in soup.find("div", {"class": "dlbodz"}).find_all("div", {"class": "smokeddlrh"}): + for smokedl in soup.find("div", {"class": "dlbodz"}).find_all( + "div", {"class": "smokeddlrh"} + ): if not smokedl: continue mendata = {"name": title, "links": []} @@ -68,7 +130,9 @@ async def kusonimeBypass(url: str): mendata["links"].append({"quality": quality, "link_download": links}) data.append(mendata) num += 1 - for smokedl in soup.find("div", {"class": "dlbodz"}).find_all("div", {"class": "smokeddl"}): + for smokedl in soup.find("div", {"class": "dlbodz"}).find_all( + "div", {"class": "smokeddl"} + ): if not smokedl: continue mendata = {"name": title, "links": []} @@ -94,7 +158,22 @@ async def kusonimeBypass(url: str): mendata["links"].append({"quality": quality, "link_download": links}) data.append(mendata) num += 1 - result.update({"title": title, "thumb": thumb, "genre": genre, "genre_string": ", ".join(genre), "status_anime": status_anime, "season": season, "tipe": tipe, "ep": ep, "score": score, "duration": duration, "rilis": rilis, "data": data}) + result.update( + { + "title": title, + "thumb": thumb, + "genre": genre, + "genre_string": ", ".join(genre), + "status_anime": status_anime, + "season": season, + "tipe": tipe, + "ep": ep, + "score": score, + "duration": duration, + "rilis": rilis, + "data": data, + } + ) except Exception as e: if result: result.clear() diff --git a/misskaty/helper/misc.py b/misskaty/helper/misc.py index dc3a4f56..f4726cf4 100644 --- a/misskaty/helper/misc.py +++ b/misskaty/helper/misc.py @@ -76,9 +76,7 @@ def paginate_modules(page_n, module_dict, prefix, chat=None): ) ] else: - pairs = pairs[ - modulo_page * COLUMN_SIZE : COLUMN_SIZE * (modulo_page + 1) - ] + [ + pairs = pairs[modulo_page * COLUMN_SIZE : COLUMN_SIZE * (modulo_page + 1)] + [ ( EqInlineKeyboardButton( "Back", callback_data=f"{prefix}_home({modulo_page})" diff --git a/misskaty/helper/stickerset.py b/misskaty/helper/stickerset.py index 7b42f3d3..00048691 100644 --- a/misskaty/helper/stickerset.py +++ b/misskaty/helper/stickerset.py @@ -17,6 +17,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ + from typing import List from pyrogram import Client, errors, raw diff --git a/misskaty/helper/tools.py b/misskaty/helper/tools.py index aa339510..40dfec1a 100644 --- a/misskaty/helper/tools.py +++ b/misskaty/helper/tools.py @@ -4,17 +4,17 @@ import random import re import string import time -import cv2 -import numpy as np from http.cookies import SimpleCookie -from misskaty.core.decorator import asyncify from re import match as re_match from typing import Union from urllib.parse import urlparse +import cv2 +import numpy as np import psutil from misskaty import BOT_NAME, UBOT_NAME, botStartTime +from misskaty.core.decorator import asyncify from misskaty.helper.http import fetch from misskaty.helper.human_read import get_readable_time from misskaty.plugins import ALL_MODULES @@ -144,13 +144,13 @@ async def search_jw(movie_name: str, locale: Union[str, None] = "ID"): return m_t_ for item in response["results"]["data"]["popularTitles"]["edges"]: if item["node"]["content"]["title"] == movie_name: - t_m_ = [] - for offer in item["node"].get("offers", []): - url = offer["standardWebURL"] - if url not in t_m_: - p_o = get_provider(url) - m_t_ += f"{p_o} | " - t_m_.append(url) + t_m_ = [] + for offer in item["node"].get("offers", []): + url = offer["standardWebURL"] + if url not in t_m_: + p_o = get_provider(url) + m_t_ += f"{p_o} | " + t_m_.append(url) if m_t_ != "": m_t_ = m_t_[:-2].strip() break @@ -158,17 +158,19 @@ async def search_jw(movie_name: str, locale: Union[str, None] = "ID"): def isValidURL(str): - # Regex to check valid URL - regex = ("((http|https)://)(www.)?" + - "[a-zA-Z0-9@:%._\\+~#?&//=]" + - "{2,256}\\.[a-z]" + - "{2,6}\\b([-a-zA-Z0-9@:%" + - "._\\+~#?&//=]*)") + # Regex to check valid URL + regex = ( + "((http|https)://)(www.)?" + + "[a-zA-Z0-9@:%._\\+~#?&//=]" + + "{2,256}\\.[a-z]" + + "{2,6}\\b([-a-zA-Z0-9@:%" + + "._\\+~#?&//=]*)" + ) # Compile the ReGex p = re.compile(regex) - # If the string is empty + # If the string is empty # return false return False if str is None else bool((re.search(p, str))) @@ -189,16 +191,18 @@ def gen_trans_image(source, path): # apply morphology to remove isolated extraneous noise # use borderconstant of black since foreground touches the edges - kernel = np.ones((3,3), np.uint8) + kernel = np.ones((3, 3), np.uint8) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) # anti-alias the mask -- blur then stretch # blur alpha channel - mask = cv2.GaussianBlur(mask, (0,0), sigmaX=2, sigmaY=2, borderType = cv2.BORDER_DEFAULT) + mask = cv2.GaussianBlur( + mask, (0, 0), sigmaX=2, sigmaY=2, borderType=cv2.BORDER_DEFAULT + ) # linear stretch so that 127.5 goes to 0, but 255 stays 255 - mask = (2*(mask.astype(np.float32))-255.0).clip(0,255).astype(np.uint8) + mask = (2 * (mask.astype(np.float32)) - 255.0).clip(0, 255).astype(np.uint8) # put mask into alpha channel result = img.copy() @@ -207,4 +211,4 @@ def gen_trans_image(source, path): # save resulting masked image cv2.imwrite(path, result) - return path \ No newline at end of file + return path diff --git a/misskaty/plugins/__init__.py b/misskaty/plugins/__init__.py index e93a0f27..6d867b26 100644 --- a/misskaty/plugins/__init__.py +++ b/misskaty/plugins/__init__.py @@ -1,9 +1,10 @@ """ - * @author yasir - * @date 2022-12-01 09:12:27 - * @projectName MissKatyPyro - * Copyright ©YasirPedia All rights reserved - """ +* @author yasir +* @date 2022-12-01 09:12:27 +* @projectName MissKatyPyro +* Copyright ©YasirPedia All rights reserved +""" + import glob import importlib import sys diff --git a/misskaty/plugins/admin.py b/misskaty/plugins/admin.py index b643a178..e48e09d2 100644 --- a/misskaty/plugins/admin.py +++ b/misskaty/plugins/admin.py @@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ + import asyncio import os import re @@ -34,7 +35,7 @@ from pyrogram.errors import ( PeerIdInvalid, UsernameNotOccupied, ) -from pyrogram.types import ChatPermissions, ChatMember, ChatPrivileges, Message +from pyrogram.types import ChatMember, ChatPermissions, ChatPrivileges, Message from database.warn_db import add_warn, get_warn, remove_warns from misskaty import app @@ -206,7 +207,7 @@ async def banFunc(client, message, strings): try: user_id, reason = await extract_user_and_reason(message, sender_chat=True) except UsernameNotOccupied: - return await message.reply_msg("Sorry, i didn't know that user.") + return await message.reply_msg("Sorry, i didn't know that user.") if not user_id: return await message.reply_text(strings("user_not_found")) @@ -568,7 +569,9 @@ async def mute(client, message, strings): if reason: msg += strings("banned_reason").format(reas=reason) try: - await message.chat.restrict_member(user_id, permissions=ChatPermissions(all_perms=False)) + await message.chat.restrict_member( + user_id, permissions=ChatPermissions(all_perms=False) + ) await message.reply_text(msg, reply_markup=keyboard) except Exception as e: await message.reply_msg(str(e)) @@ -861,21 +864,28 @@ async def set_chat_photo(_, ctx: Message): os.remove(photo) -@app.on_message(filters.group & filters.command('mentionall', COMMAND_HANDLER)) +@app.on_message(filters.group & filters.command("mentionall", COMMAND_HANDLER)) async def mentionall(app: Client, msg: Message): user = await msg.chat.get_member(msg.from_user.id) - if user.status in (enums.ChatMemberStatus.OWNER, enums.ChatMemberStatus.ADMINISTRATOR): + if user.status in ( + enums.ChatMemberStatus.OWNER, + enums.ChatMemberStatus.ADMINISTRATOR, + ): total = [] async for member in app.get_chat_members(msg.chat.id): member: ChatMember if member.user.username: - total.append(f'@{member.user.username}') + total.append(f"@{member.user.username}") else: total.append(member.user.mention()) NUM = 4 for i in range(0, len(total), NUM): - message = ' '.join(total[i:i+NUM]) - await app.send_message(msg.chat.id, message, message_thread_id=msg.message_thread_id) + message = " ".join(total[i : i + NUM]) + await app.send_message( + msg.chat.id, message, message_thread_id=msg.message_thread_id + ) else: - await app.send_message(msg.chat.id, 'Admins only can do that !', reply_to_message_id=msg.id) + await app.send_message( + msg.chat.id, "Admins only can do that !", reply_to_message_id=msg.id + ) diff --git a/misskaty/plugins/auto_approve.py b/misskaty/plugins/auto_approve.py index ee8e99fc..ebf76ee3 100644 --- a/misskaty/plugins/auto_approve.py +++ b/misskaty/plugins/auto_approve.py @@ -1,9 +1,10 @@ """ - * @author yasir - * @date 2022-12-01 09:12:27 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved +* @author yasir +* @date 2022-12-01 09:12:27 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved """ + from pyrogram import filters from pyrogram.errors import UserAlreadyParticipant, UserIsBlocked from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup diff --git a/misskaty/plugins/autoapprove.py b/misskaty/plugins/autoapprove.py index ffaab8a0..7b05635a 100644 --- a/misskaty/plugins/autoapprove.py +++ b/misskaty/plugins/autoapprove.py @@ -1,5 +1,3 @@ -from database import dbname - from pyrogram import filters from pyrogram.types import ( CallbackQuery, @@ -9,9 +7,10 @@ from pyrogram.types import ( Message, ) +from database import dbname from misskaty import app -from misskaty.vars import SUDO, COMMAND_HANDLER from misskaty.core.decorator.permissions import adminsOnly, member_permissions +from misskaty.vars import COMMAND_HANDLER, SUDO approvaldb = dbname["autoapprove"] @@ -67,13 +66,7 @@ async def approval_cb(_, cb: CallbackQuery): if await approvaldb.count_documents({"chat_id": chat_id}) == 0: approvaldb.insert_one({"chat_id": chat_id}) keyboard_off = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - "Turn OFF", callback_data="approval_off" - ) - ] - ] + [[InlineKeyboardButton("Turn OFF", callback_data="approval_off")]] ) await cb.edit_message_text( "**Autoapproval for this chat: Enabled.**", @@ -83,13 +76,7 @@ async def approval_cb(_, cb: CallbackQuery): if await approvaldb.count_documents({"chat_id": chat_id}) > 0: approvaldb.delete_one({"chat_id": chat_id}) keyboard_on = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - "Turn ON", callback_data="approval_on" - ) - ] - ] + [[InlineKeyboardButton("Turn ON", callback_data="approval_on")]] ) await cb.edit_message_text( "**Autoapproval for this chat: Disabled.**", @@ -103,4 +90,4 @@ async def accept(_, message: ChatJoinRequest): chat = message.chat user = message.from_user if (await approvaldb.count_documents({"chat_id": chat.id})) > 0: - await app.approve_chat_join_request(chat_id=chat.id, user_id=user.id) \ No newline at end of file + await app.approve_chat_join_request(chat_id=chat.id, user_id=user.id) diff --git a/misskaty/plugins/ban_user_or_chat.py b/misskaty/plugins/ban_user_or_chat.py index 03c94055..5b9bef4e 100644 --- a/misskaty/plugins/ban_user_or_chat.py +++ b/misskaty/plugins/ban_user_or_chat.py @@ -1,4 +1,5 @@ from curses.ascii import isblank + from pyrogram import Client, filters from pyrogram.errors import ChannelPrivate, PeerIdInvalid from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message @@ -93,7 +94,9 @@ async def ban_a_user(bot, message): f"{k.mention} is already banned\nReason: {alesan['reason']}" ) await db.ban_user(k.id, reason) - await message.reply(f"Successfully banned user {k.mention}!!\nReason: {reason}") + await message.reply( + f"Successfully banned user {k.mention}!!\nReason: {reason}" + ) @app.on_message(filters.command("unbanuser", COMMAND_HANDLER) & filters.user(SUDO)) diff --git a/misskaty/plugins/blacklist_chat.py b/misskaty/plugins/blacklist_chat.py index 2ae5b7c2..24edfb9a 100644 --- a/misskaty/plugins/blacklist_chat.py +++ b/misskaty/plugins/blacklist_chat.py @@ -21,12 +21,13 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ + import re from datetime import datetime, timedelta from pyrogram import filters -from pyrogram.types import ChatPermissions from pyrogram.errors import ChatAdminRequired +from pyrogram.types import ChatPermissions from database.blacklist_db import ( delete_blacklist_filter, @@ -113,7 +114,9 @@ async def blacklist_filters_re(self, message): until_date=datetime.now() + timedelta(hours=1), ) except ChatAdminRequired: - return await message.reply("Please give me admin permissions to blacklist user", quote=False) + return await message.reply( + "Please give me admin permissions to blacklist user", quote=False + ) except Exception as err: self.log.info(f"ERROR Blacklist Chat: ID = {chat_id}, ERR = {err}") return diff --git a/misskaty/plugins/broadcast.py b/misskaty/plugins/broadcast.py index 546c5647..c4729d19 100644 --- a/misskaty/plugins/broadcast.py +++ b/misskaty/plugins/broadcast.py @@ -2,11 +2,11 @@ import asyncio import datetime import time +from async_pymongo import AsyncClient from pyrogram import filters from pyrogram.types import Message -from async_pymongo import AsyncClient -from misskaty import app, DATABASE_URI +from misskaty import DATABASE_URI, app from misskaty.vars import SUDO from utils import broadcast_messages diff --git a/misskaty/plugins/bypass.py b/misskaty/plugins/bypass.py index 41101025..66be6428 100644 --- a/misskaty/plugins/bypass.py +++ b/misskaty/plugins/bypass.py @@ -1,10 +1,11 @@ """ - * @author yasir - * @date 2022-12-01 09:12:27 - * @lastModified 2022-12-01 09:32:31 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved +* @author yasir +* @date 2022-12-01 09:12:27 +* @lastModified 2022-12-01 09:32:31 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved """ + import re import urllib.parse from urllib.parse import unquote @@ -16,7 +17,7 @@ from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message from misskaty import app from misskaty.core.decorator.errors import capture_err -from misskaty.helper import get_readable_file_size, fetch, rentry +from misskaty.helper import fetch, get_readable_file_size, rentry from misskaty.vars import COMMAND_HANDLER LIST_LINK = """ @@ -37,9 +38,8 @@ Supported Link: Credit: PyBypass """ + # Stopped development for this plugin since always changed time by time. - - async def pling_bypass(url): try: id_url = re.search(r"https?://(store.kde.org|www.pling.com)\/p\/(\d+)", url)[2] diff --git a/misskaty/plugins/chatbot_ai.py b/misskaty/plugins/chatbot_ai.py index 3c0d0ba7..0751fc8b 100644 --- a/misskaty/plugins/chatbot_ai.py +++ b/misskaty/plugins/chatbot_ai.py @@ -6,7 +6,7 @@ import asyncio import html import random -from openai import AsyncOpenAI, APIConnectionError, RateLimitError, APIStatusError +from openai import APIConnectionError, APIStatusError, AsyncOpenAI, RateLimitError from pyrogram import filters from pyrogram.errors import MessageTooLong from pyrogram.types import Message @@ -14,8 +14,7 @@ from pyrogram.types import Message from misskaty import app from misskaty.core import pyro_cooldown from misskaty.helper import check_time_gap, fetch, post_to_telegraph, use_chat_lang -from misskaty.vars import GOOGLEAI_KEY, COMMAND_HANDLER, OPENAI_KEY, SUDO - +from misskaty.vars import COMMAND_HANDLER, GOOGLEAI_KEY, OPENAI_KEY, SUDO __MODULE__ = "ChatBot" __HELP__ = """ @@ -25,7 +24,9 @@ __HELP__ = """ @app.on_message(filters.command("ai", COMMAND_HANDLER) & pyro_cooldown.wait(10)) -@app.on_bot_business_message(filters.command("ai", COMMAND_HANDLER) & pyro_cooldown.wait(10)) +@app.on_bot_business_message( + filters.command("ai", COMMAND_HANDLER) & pyro_cooldown.wait(10) +) @use_chat_lang() async def gemini_chatbot(_, ctx: Message, strings): if len(ctx.command) == 1: @@ -36,18 +37,20 @@ async def gemini_chatbot(_, ctx: Message, strings): return await ctx.reply_msg("GOOGLEAI_KEY env is missing!!!") msg = await ctx.reply_msg(strings("find_answers_str"), quote=True) try: - data = { - "query": ctx.text.split(maxsplit=1)[1], - "key": GOOGLEAI_KEY - } + data = {"query": ctx.text.split(maxsplit=1)[1], "key": GOOGLEAI_KEY} # Fetch from API beacuse my VPS is not supported - response = await fetch.post( - "https://yasirapi.eu.org/gemini", data=data - ) + response = await fetch.post("https://yasirapi.eu.org/gemini", data=data) if not response.json().get("candidates"): - await ctx.reply_msg("⚠️ Sorry, the prompt you sent maybe contains a forbidden word that is not permitted by AI.") + await ctx.reply_msg( + "⚠️ Sorry, the prompt you sent maybe contains a forbidden word that is not permitted by AI." + ) else: - await ctx.reply_msg(html.escape(response.json()["candidates"][0]["content"]["parts"][0]["text"])+'\nPowered by: Gemini Flash 1.5') + await ctx.reply_msg( + html.escape( + response.json()["candidates"][0]["content"]["parts"][0]["text"] + ) + + "\nPowered by: Gemini Flash 1.5" + ) await msg.delete() except Exception as e: await ctx.reply_msg(str(e)) @@ -101,9 +104,13 @@ async def openai_chatbot(_, ctx: Message, strings): await msg.edit_msg(f"The server could not be reached because {e.__cause__}") except RateLimitError as e: if "billing details" in str(e): - return await msg.edit_msg("This openai key from this bot has expired, please give openai key donation for bot owner.") + return await msg.edit_msg( + "This openai key from this bot has expired, please give openai key donation for bot owner." + ) await msg.edit_msg("You're got rate limit, please try again later.") except APIStatusError as e: - await msg.edit_msg(f"Another {e.status_code} status code was received with response {e.response}") + await msg.edit_msg( + f"Another {e.status_code} status code was received with response {e.response}" + ) except Exception as e: await msg.edit_msg(f"ERROR: {e}") diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py index f2e7719c..beda1b1d 100644 --- a/misskaty/plugins/dev.py +++ b/misskaty/plugins/dev.py @@ -34,7 +34,6 @@ from pyrogram.errors import ( FloodWait, MessageTooLong, PeerIdInvalid, - ReactionInvalid, ) from pyrogram.raw.types import UpdateBotStopped from pyrogram.types import ( diff --git a/misskaty/plugins/download_upload.py b/misskaty/plugins/download_upload.py index 97efc114..dd0ac584 100644 --- a/misskaty/plugins/download_upload.py +++ b/misskaty/plugins/download_upload.py @@ -3,17 +3,16 @@ # * @projectName MissKatyPyro # * Copyright ©YasirPedia All rights reserved import asyncio -import cloudscraper import math import os import re import time -from bs4 import BeautifulSoup -from cloudscraper import create_scraper from datetime import datetime from logging import getLogger from urllib.parse import unquote +from bs4 import BeautifulSoup +from cloudscraper import create_scraper from pyrogram import filters from pyrogram.file_id import FileId from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup @@ -183,32 +182,46 @@ async def instadl(_, message): msg = await message.reply("Trying download...") try: headers = { - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:105.0) Gecko/20100101 Firefox/105.0", - "Accept": "*/*", - "Accept-Language": "en-US,en;q=0.5", - "Accept-Encoding": "gzip, deflate, br", - "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", - "X-Requested-With": "XMLHttpRequest", - "Content-Length": "99", - "Origin": "https://saveig.app", - "Connection": "keep-alive", - "Referer": "https://saveig.app/id", - } - post = create_scraper().post("https://saveig.app/api/ajaxSearch", data={"q": link, "t": "media", "lang": "id"}, headers=headers) + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:105.0) Gecko/20100101 Firefox/105.0", + "Accept": "*/*", + "Accept-Language": "en-US,en;q=0.5", + "Accept-Encoding": "gzip, deflate, br", + "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", + "X-Requested-With": "XMLHttpRequest", + "Content-Length": "99", + "Origin": "https://saveig.app", + "Connection": "keep-alive", + "Referer": "https://saveig.app/id", + } + post = create_scraper().post( + "https://saveig.app/api/ajaxSearch", + data={"q": link, "t": "media", "lang": "id"}, + headers=headers, + ) if post.status_code not in [200, 401]: return await message.reply("Unknown error.") res = post.json() - if r := re.findall(r'href="(https?://(?!play\.google\.com|/)[^"]+)"', res["data"]): + if r := re.findall( + r'href="(https?://(?!play\.google\.com|/)[^"]+)"', res["data"] + ): res = r[0].replace("&", "&") - fname = (await fetch.head(res)).headers.get("content-disposition", "").split("filename=")[1] - is_img = (await fetch.head(res)).headers.get("content-type").startswith("image") + fname = ( + (await fetch.head(res)) + .headers.get("content-disposition", "") + .split("filename=")[1] + ) + is_img = ( + (await fetch.head(res)).headers.get("content-type").startswith("image") + ) if is_img: await message.reply_photo(res, caption=fname) else: await message.reply_video(res, caption=fname) await msg.delete() except Exception as e: - await message.reply(f"Failed to download instagram video..\n\nReason: {e}") + await message.reply( + f"Failed to download instagram video..\n\nReason: {e}" + ) await msg.delete() @@ -251,15 +264,29 @@ async def twitterdl(_, message): if post.status_code not in [200, 401]: return await msg.edit_msg("Unknown error.") soup = BeautifulSoup(post.text, "lxml") - cekdata = soup.find("a", {"pure-button pure-button-primary is-center u-bl dl-button download_link without_watermark vignette_active"}) + cekdata = soup.find( + "a", + { + "pure-button pure-button-primary is-center u-bl dl-button download_link without_watermark vignette_active" + }, + ) if not cekdata: - return await message.reply("ERROR: Oops! It seems that this tweet doesn't have a video! Try later or check your link") + return await message.reply( + "ERROR: Oops! It seems that this tweet doesn't have a video! Try later or check your link" + ) try: - fname = (await fetch.head(cekdata.get("href"))).headers.get("content-disposition", "").split("filename=")[1] + fname = ( + (await fetch.head(cekdata.get("href"))) + .headers.get("content-disposition", "") + .split("filename=")[1] + ) obj = SmartDL(cekdata.get("href"), progress_bar=False, timeout=15) obj.start() path = obj.get_dest() - await message.reply_video(path, caption=f"{fname}\n\nUploaded for {message.from_user.mention} [{message.from_user.id}]",) + await message.reply_video( + path, + caption=f"{fname}\n\nUploaded for {message.from_user.mention} [{message.from_user.id}]", + ) except Exception as er: LOGGER.error("ERROR: while fetching TwitterDL. %s", er) return await msg.edit_msg("ERROR: Got error while extracting link.") @@ -284,8 +311,10 @@ async def tiktokdl(_, message): "https://lovetik.com/api/ajax/search", data={"query": link} ) ).json() - fname = (await fetch.head(r["links"][0]["a"])).headers.get("content-disposition", "") - filename = unquote(fname.split('filename=')[1].strip('"').split('"')[0]) + fname = (await fetch.head(r["links"][0]["a"])).headers.get( + "content-disposition", "" + ) + filename = unquote(fname.split("filename=")[1].strip('"').split('"')[0]) await message.reply_video( r["links"][0]["a"], caption=f"Title: {filename}\nUploader: {r['author_name']}\n\nUploaded for {message.from_user.mention} [{message.from_user.id}]", diff --git a/misskaty/plugins/federation.py b/misskaty/plugins/federation.py index 681ac5b5..8e147686 100644 --- a/misskaty/plugins/federation.py +++ b/misskaty/plugins/federation.py @@ -23,20 +23,19 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ -import uuid import asyncio -from database.feds_db import * - -from misskaty import app, BOT_ID -from misskaty.vars import SUDO, LOG_GROUP_ID, COMMAND_HANDLER +import uuid from pyrogram import filters from pyrogram.enums import ChatMemberStatus, ChatType, ParseMode +from pyrogram.errors import FloodWait, PeerIdInvalid from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup -from misskaty.helper.functions import extract_user, extract_user_and_reason -from pyrogram.errors import FloodWait, PeerIdInvalid +from database.feds_db import * +from misskaty import BOT_ID, app from misskaty.core.decorator.errors import capture_err +from misskaty.helper.functions import extract_user, extract_user_and_reason +from misskaty.vars import COMMAND_HANDLER, LOG_GROUP_ID, SUDO __MODULE__ = "Federation" __HELP__ = """ @@ -451,7 +450,9 @@ async def get_all_fadmins_mentions(client, message): fadmin_ids = fed_info.get("fadmins", []) if not fadmin_ids: - return await message.reply_text(f"**Owner: {fed_info['owner_mention']}\n\nNo fadmins found in the federation.") + return await message.reply_text( + f"**Owner: {fed_info['owner_mention']}\n\nNo fadmins found in the federation." + ) user_mentions = [] for user_id in fadmin_ids: @@ -460,7 +461,10 @@ async def get_all_fadmins_mentions(client, message): user_mentions.append(f"● {user.mention}[`{user.id}`]") except Exception: user_mentions.append(f"● `Admin🥷`[`{user_id}`]") - reply_text = f"**Owner: {fed_info['owner_mention']}\n\nList of fadmins:**\n" + "\n".join(user_mentions) + reply_text = ( + f"**Owner: {fed_info['owner_mention']}\n\nList of fadmins:**\n" + + "\n".join(user_mentions) + ) await message.reply_text(reply_text) @@ -572,7 +576,9 @@ async def fban_user(client, message): chat = message.chat from_user = message.from_user if message.chat.type == ChatType.PRIVATE: - return await message.reply_text("This command is specific to groups, not our pm!.") + return await message.reply_text( + "This command is specific to groups, not our pm!." + ) fed_id = await get_fed_id(chat.id) if not fed_id: return await message.reply_text("**This chat is not a part of any federation.") @@ -592,7 +598,9 @@ async def fban_user(client, message): try: user = await app.get_users(user_id) except PeerIdInvalid: - return await message.reply_msg("Sorry, i never meet this user. So i cannot fban.") + return await message.reply_msg( + "Sorry, i never meet this user. So i cannot fban." + ) if not user_id: return await message.reply_text("I can't find that user.") if user_id in all_admins or user_id in SUDO: diff --git a/misskaty/plugins/filter_request.py b/misskaty/plugins/filter_request.py index 0b7fadd1..f92553ca 100644 --- a/misskaty/plugins/filter_request.py +++ b/misskaty/plugins/filter_request.py @@ -24,8 +24,10 @@ from .ytdl_plugins import YT_DB chat = [-1001128045651, -1001255283935, -1001455886928] REQUEST_DB = {} + # This modules is only working for my movies group to help collect a list of film requests by members. + # @app.on_message(filters.regex(r"alamu'?ala[iy]ku+m", re.I) & filters.chat(chat)) async def salamregex(_, message): await message.reply_text(text=f"Wa'alaikumsalam {message.from_user.mention} 😇") @@ -186,7 +188,8 @@ async def callbackreq(c, q): [ [ InlineKeyboardButton( - text="✅ Request Completed", callback_data="reqcompl" + text="✅ Request Completed", + callback_data="reqcompl", ) ] ] @@ -199,7 +202,8 @@ async def callbackreq(c, q): [ [ InlineKeyboardButton( - text="✅ Request Completed", callback_data="reqcompl" + text="✅ Request Completed", + callback_data="reqcompl", ) ] ] @@ -300,7 +304,8 @@ async def callbackreject(c, q): [ [ InlineKeyboardButton( - text="🚫 Request Rejected", callback_data="reqreject" + text="🚫 Request Rejected", + callback_data="reqreject", ) ] ] @@ -313,7 +318,8 @@ async def callbackreject(c, q): [ [ InlineKeyboardButton( - text="🚫 Request Rejected", callback_data="reqreject" + text="🚫 Request Rejected", + callback_data="reqreject", ) ] ] @@ -428,7 +434,8 @@ async def callbackaft_unav(_, q): @app.on_callback_query(filters.regex(r"^reqavailable$")) async def callbackaft_dahada(_, q): await q.answer( - "Request ini sudah ada, silahkan cari 🔍 di channelnya yaa 😉..", show_alert=True + "Request ini sudah ada, silahkan cari 🔍 di channelnya yaa 😉..", + show_alert=True, ) diff --git a/misskaty/plugins/filters.py b/misskaty/plugins/filters.py index 4c74d66d..d2616d91 100644 --- a/misskaty/plugins/filters.py +++ b/misskaty/plugins/filters.py @@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ + import re from pyrogram import filters @@ -55,7 +56,9 @@ You can use markdown or html to save text too. """ -@app.on_message(filters.command(["addfilter", "filter"], COMMAND_HANDLER) & ~filters.private) +@app.on_message( + filters.command(["addfilter", "filter"], COMMAND_HANDLER) & ~filters.private +) @adminsOnly("can_change_info") async def save_filters(_, message): try: @@ -80,7 +83,11 @@ async def save_filters(_, message): elif not replied_message.text and not replied_message.caption: data = None else: - data = replied_message.text.markdown if replied_message.text else replied_message.caption.markdown + data = ( + replied_message.text.markdown + if replied_message.text + else replied_message.caption.markdown + ) if replied_message.text: _type = "text" file_id = None @@ -110,7 +117,9 @@ async def save_filters(_, message): file_id = replied_message.voice.file_id if replied_message.reply_markup and "~" not in data: if urls := extract_urls(replied_message.reply_markup): - response = "\n".join([f"{name}=[{text}, {url}]" for name, text, url in urls]) + response = "\n".join( + [f"{name}=[{text}, {url}]" for name, text, url in urls] + ) data = data + response name = name.replace("_", " ") _filter = { @@ -121,7 +130,9 @@ async def save_filters(_, message): await save_filter(chat_id, name, _filter) return await message.reply_text(f"__**Saved filter {name}.**__") except UnboundLocalError: - return await message.reply_text("**Replied message is inaccessible.\n`Forward the message and try again`**") + return await message.reply_text( + "**Replied message is inaccessible.\n`Forward the message and try again`**" + ) @app.on_message(filters.command("filters", COMMAND_HANDLER) & ~filters.private) @@ -137,7 +148,9 @@ async def get_filterss(_, m): await m.reply_msg(msg) -@app.on_message(filters.command(["stop", "stopfilter"], COMMAND_HANDLER) & ~filters.private) +@app.on_message( + filters.command(["stop", "stopfilter"], COMMAND_HANDLER) & ~filters.private +) @adminsOnly("can_change_info") async def del_filter(_, m): if len(m.command) < 2: @@ -159,7 +172,9 @@ async def del_filter(_, m): ) async def filters_re(_, message): text = message.text.lower().strip() - if not text or (message.command and message.command[0].lower() in ["filter", "addfilter"]): + if not text or ( + message.command and message.command[0].lower() in ["filter", "addfilter"] + ): return chat_id = message.chat.id list_of_filters = await get_filters_names(chat_id) @@ -242,12 +257,16 @@ async def stop_all(_, message): else: keyboard = InlineKeyboardMarkup( [ - [InlineKeyboardButton("YES, DO IT", callback_data="stop_yes"), - InlineKeyboardButton("Cancel", callback_data="stop_no") + [ + InlineKeyboardButton("YES, DO IT", callback_data="stop_yes"), + InlineKeyboardButton("Cancel", callback_data="stop_no"), ] ] ) - await message.reply_text("**Are you sure you want to delete all the filters in this chat forever ?.**", reply_markup=keyboard) + await message.reply_text( + "**Are you sure you want to delete all the filters in this chat forever ?.**", + reply_markup=keyboard, + ) @app.on_callback_query(filters.regex("stop_(.*)")) @@ -257,12 +276,17 @@ async def stop_all_cb(_, cb): permissions = await member_permissions(chat_id, from_user.id) permission = "can_change_info" if permission not in permissions: - return await cb.answer(f"You don't have the required permission.\n Permission: {permission}", show_alert=True) + return await cb.answer( + f"You don't have the required permission.\n Permission: {permission}", + show_alert=True, + ) input = cb.data.split("_", 1)[1] if input == "yes": stoped_all = await deleteall_filters(chat_id) if stoped_all: - return await cb.message.edit("**Successfully deleted all filters on this chat.**") + return await cb.message.edit( + "**Successfully deleted all filters on this chat.**" + ) if input == "no": await cb.message.reply_to_message.delete() await cb.message.delete() diff --git a/misskaty/plugins/fun.py b/misskaty/plugins/fun.py index a7f1b7c4..bf1554a7 100644 --- a/misskaty/plugins/fun.py +++ b/misskaty/plugins/fun.py @@ -1,8 +1,8 @@ import textwrap -import regex from asyncio import gather from os import remove as hapus +import regex from PIL import Image, ImageDraw, ImageFont from pyrogram import filters from pyrogram.errors import MessageIdInvalid, PeerIdInvalid, ReactionInvalid @@ -201,16 +201,20 @@ async def beriharapan(c, m): @user.on_message(filters.command("react", ".")) async def givereact(c, m): if len(m.command) == 1: - return await m.reply("Please add reaction after command, you can give multiple reaction too.") + return await m.reply( + "Please add reaction after command, you can give multiple reaction too." + ) if not m.reply_to_message: return await m.reply("Please reply to the message you want to react to.") - emot = list(regex.findall(r'\p{Emoji}', m.text)) + emot = list(regex.findall(r"\p{Emoji}", m.text)) try: await m.reply_to_message.react(emoji=emot) except ReactionInvalid: await m.reply("Please give valid reaction.") except MessageIdInvalid: - await m.reply("Sorry, i couldn't react to other bots or without being as administrator.") + await m.reply( + "Sorry, i couldn't react to other bots or without being as administrator." + ) except PeerIdInvalid: await m.reply("Sorry, i can't react chat without join that groups.") except Exception as err: diff --git a/misskaty/plugins/genss.py b/misskaty/plugins/genss.py index 0674aab9..e58d5d68 100644 --- a/misskaty/plugins/genss.py +++ b/misskaty/plugins/genss.py @@ -1,9 +1,10 @@ """ - * @author yasir - * @date 2022-12-01 09:12:27 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved +* @author yasir +* @date 2022-12-01 09:12:27 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved """ + import math import os import time @@ -46,7 +47,9 @@ async def genss(self: Client, ctx: Message, strings): file_name = os.path.basename(url) download_file_path = os.path.join("downloads/", file_name) try: - downloader = SmartDL(url, download_file_path, progress_bar=False, timeout=10, verify=False) + downloader = SmartDL( + url, download_file_path, progress_bar=False, timeout=10, verify=False + ) downloader.start(blocking=False) except Exception as err: return await pesan.edit(str(err)) @@ -111,7 +114,9 @@ async def genss(self: Client, ctx: Message, strings): ) await ctx.reply_msg( strings("up_msg").format( - namma=ctx.from_user.mention if ctx.from_user else ctx.sender_chat.title, + namma=ctx.from_user.mention + if ctx.from_user + else ctx.sender_chat.title, id=ctx.from_user.id if ctx.from_user else ctx.sender_chat.title, bot_uname=self.me.username, ), @@ -178,7 +183,9 @@ async def genss(self: Client, ctx: Message, strings): ) await ctx.reply_msg( strings("up_msg").format( - namma=ctx.from_user.mention if ctx.from_user else ctx.sender_chat.title, + namma=ctx.from_user.mention + if ctx.from_user + else ctx.sender_chat.title, id=ctx.from_user.id if ctx.from_user else ctx.sender_chat.id, bot_uname=self.me.username, ), diff --git a/misskaty/plugins/grup_tools.py b/misskaty/plugins/grup_tools.py index f272536d..2bedb300 100644 --- a/misskaty/plugins/grup_tools.py +++ b/misskaty/plugins/grup_tools.py @@ -16,8 +16,8 @@ from pyrogram.errors import ( ) from pyrogram.types import ChatMemberUpdated, InlineKeyboardButton, InlineKeyboardMarkup -from database.users_chats_db import db from database.greetings_db import is_welcome, toggle_welcome +from database.users_chats_db import db from misskaty import BOT_USERNAME, app from misskaty.core.decorator import asyncify, capture_err from misskaty.helper import fetch, use_chat_lang @@ -169,7 +169,9 @@ async def member_has_joined(c: app, member: ChatMemberUpdated, strings): @app.adminsOnly("can_change_info") async def welcome_toggle_handler(client, message): is_enabled = await toggle_welcome(message.chat.id) - await message.reply_msg(f"Welcome messages are now {'enabled' if is_enabled else 'disabled'}.") + await message.reply_msg( + f"Welcome messages are now {'enabled' if is_enabled else 'disabled'}." + ) # ToDo with ChatMemberUpdated diff --git a/misskaty/plugins/imdb_search.py b/misskaty/plugins/imdb_search.py index 6d9c4158..d62ef97b 100644 --- a/misskaty/plugins/imdb_search.py +++ b/misskaty/plugins/imdb_search.py @@ -3,13 +3,13 @@ # * @projectName MissKatyPyro # * Copyright ©YasirPedia All rights reserved import contextlib -import httpx import json import logging import re import sys from urllib.parse import quote_plus +import httpx from bs4 import BeautifulSoup from deep_translator import GoogleTranslator from pykeyboard import InlineButton, InlineKeyboard @@ -145,7 +145,9 @@ async def imdb_search_id(kueri, message): return await k.edit_caption( f"⛔️ Tidak ditemukan hasil untuk kueri: {kueri}" ) - msg += f"🎬 Ditemukan ({len(res)}) hasil untuk kueri: {kueri}\n\n" + msg += ( + f"🎬 Ditemukan ({len(res)}) hasil untuk kueri: {kueri}\n\n" + ) for num, movie in enumerate(res, start=1): title = movie.get("l") if year := movie.get("yr"): @@ -207,7 +209,9 @@ async def imdb_search_en(kueri, message): return await k.edit_caption( f"⛔️ Result not found for keywords: {kueri}" ) - msg += f"🎬 Found ({len(res)}) result for keywords: {kueri}\n\n" + msg += ( + f"🎬 Found ({len(res)}) result for keywords: {kueri}\n\n" + ) for num, movie in enumerate(res, start=1): title = movie.get("l") if year := movie.get("yr"): @@ -300,13 +304,17 @@ async def imdbcari(_, query: CallbackQuery): InlineKeyboardButton( text="🚩 Language", callback_data=f"imdbset#{uid}" ), - InlineKeyboardButton(text="❌ Close", callback_data=f"close#{uid}"), + InlineKeyboardButton( + text="❌ Close", callback_data=f"close#{uid}" + ), ) ) buttons.add(*BTN) await query.message.edit_caption(msg, reply_markup=buttons) except httpx.HTTPError as exc: - await query.message.edit_caption(f"HTTP Exception for IMDB Search - {exc}") + await query.message.edit_caption( + f"HTTP Exception for IMDB Search - {exc}" + ) except (MessageIdInvalid, MessageNotModified): pass except Exception as err: @@ -357,13 +365,17 @@ async def imdbcari(_, query: CallbackQuery): InlineKeyboardButton( text="🚩 Language", callback_data=f"imdbset#{uid}" ), - InlineKeyboardButton(text="❌ Close", callback_data=f"close#{uid}"), + InlineKeyboardButton( + text="❌ Close", callback_data=f"close#{uid}" + ), ) ) buttons.add(*BTN) await query.message.edit_caption(msg, reply_markup=buttons) except httpx.HTTPError as exc: - await query.message.edit_caption(f"HTTP Exception for IMDB Search - {exc}") + await query.message.edit_caption( + f"HTTP Exception for IMDB Search - {exc}" + ) except (MessageIdInvalid, MessageNotModified): pass except Exception as err: @@ -387,7 +399,9 @@ async def imdb_id_callback(self: Client, query: CallbackQuery): r_json = json.loads( sop.find("script", attrs={"type": "application/ld+json"}).contents[0] ) - ott = await search_jw(r_json.get("alternateName") or r_json.get("name"), "ID") + ott = await search_jw( + r_json.get("alternateName") or r_json.get("name"), "ID" + ) typee = r_json.get("@type", "") res_str = "" tahun = ( @@ -402,7 +416,9 @@ async def imdb_id_callback(self: Client, query: CallbackQuery): res_str += "\n" if durasi := sop.select('li[data-testid="title-techspec_runtime"]'): durasi = ( - durasi[0].find(class_="ipc-metadata-list-item__content-container").text + durasi[0] + .find(class_="ipc-metadata-list-item__content-container") + .text ) res_str += f"Durasi: {GoogleTranslator('auto', 'id').translate(durasi)}\n" if kategori := r_json.get("contentRating"): @@ -420,9 +436,7 @@ async def imdb_id_callback(self: Client, query: CallbackQuery): rilis_url = release[0].find( class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link" )["href"] - res_str += ( - f"Rilis: {rilis}\n" - ) + res_str += f"Rilis: {rilis}\n" if genre := r_json.get("genre"): genre = "".join( f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, " @@ -461,19 +475,26 @@ async def imdb_id_callback(self: Client, query: CallbackQuery): ) res_str += f"Penulis: {creator[:-2]}\n" if actors := r_json.get("actor"): - actor = "".join(f"{i['name']}, " for i in actors) + actor = "".join( + f"{i['name']}, " for i in actors + ) res_str += f"Pemeran: {actor[:-2]}\n\n" if deskripsi := r_json.get("description"): summary = GoogleTranslator("auto", "id").translate(deskripsi) res_str += f"📜 Plot:\n
{summary}
\n\n" if keywd := r_json.get("keywords"): key_ = "".join( - f"#{i.replace(' ', '_').replace('-', '_')}, " for i in keywd.split(",") + f"#{i.replace(' ', '_').replace('-', '_')}, " + for i in keywd.split(",") + ) + res_str += ( + f"🔥 Kata Kunci:\n
{key_[:-2]}
\n" ) - res_str += f"🔥 Kata Kunci:\n
{key_[:-2]}
\n" if award := sop.select('li[data-testid="award_information"]'): awards = ( - award[0].find(class_="ipc-metadata-list-item__list-content-item").text + award[0] + .find(class_="ipc-metadata-list-item__list-content-item") + .text ) res_str += f"🏆 Penghargaan:\n
{GoogleTranslator('auto', 'id').translate(awards)}
\n" else: @@ -521,15 +542,21 @@ async def imdb_id_callback(self: Client, query: CallbackQuery): res_str, parse_mode=enums.ParseMode.HTML, reply_markup=markup ) except Exception as err: - LOGGER.error(f"Terjadi error saat menampilkan data IMDB. ERROR: {err}") + LOGGER.error( + f"Terjadi error saat menampilkan data IMDB. ERROR: {err}" + ) else: await query.message.edit_caption( res_str, parse_mode=enums.ParseMode.HTML, reply_markup=markup ) except httpx.HTTPError as exc: - await query.message.edit_caption(f"HTTP Exception for IMDB Search - {exc}") + await query.message.edit_caption( + f"HTTP Exception for IMDB Search - {exc}" + ) except AttributeError: - await query.message.edit_caption("Maaf, gagal mendapatkan info data dari IMDB.") + await query.message.edit_caption( + "Maaf, gagal mendapatkan info data dari IMDB." + ) except (MessageNotModified, MessageIdInvalid): pass @@ -549,7 +576,9 @@ async def imdb_en_callback(self: Client, query: CallbackQuery): r_json = json.loads( sop.find("script", attrs={"type": "application/ld+json"}).contents[0] ) - ott = await search_jw(r_json.get("alternateName") or r_json.get("name"), "US") + ott = await search_jw( + r_json.get("alternateName") or r_json.get("name"), "US" + ) typee = r_json.get("@type", "") res_str = "" tahun = ( @@ -564,7 +593,9 @@ async def imdb_en_callback(self: Client, query: CallbackQuery): res_str += "\n" if durasi := sop.select('li[data-testid="title-techspec_runtime"]'): durasi = ( - durasi[0].find(class_="ipc-metadata-list-item__content-container").text + durasi[0] + .find(class_="ipc-metadata-list-item__content-container") + .text ) res_str += f"Duration: {durasi}\n" if kategori := r_json.get("contentRating"): @@ -582,9 +613,7 @@ async def imdb_en_callback(self: Client, query: CallbackQuery): rilis_url = release[0].find( class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link" )["href"] - res_str += ( - f"Rilis: {rilis}\n" - ) + res_str += f"Rilis: {rilis}\n" if genre := r_json.get("genre"): genre = "".join( f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, " @@ -612,7 +641,8 @@ async def imdb_en_callback(self: Client, query: CallbackQuery): res_str += "\n🙎 Cast Info:\n" if r_json.get("director"): director = "".join( - f"{i['name']}, " for i in r_json["director"] + f"{i['name']}, " + for i in r_json["director"] ) res_str += f"Director: {director[:-2]}\n" if r_json.get("creator"): @@ -634,10 +664,14 @@ async def imdb_en_callback(self: Client, query: CallbackQuery): f"#{i.replace(' ', '_').replace('-', '_')}, " for i in r_json["keywords"].split(",") ) - res_str += f"🔥 Keywords:\n
{key_[:-2]}
\n" + res_str += ( + f"🔥 Keywords:\n
{key_[:-2]}
\n" + ) if award := sop.select('li[data-testid="award_information"]'): awards = ( - award[0].find(class_="ipc-metadata-list-item__list-content-item").text + award[0] + .find(class_="ipc-metadata-list-item__list-content-item") + .text ) res_str += f"🏆 Awards:\n
{awards}
\n" else: @@ -691,7 +725,9 @@ async def imdb_en_callback(self: Client, query: CallbackQuery): res_str, parse_mode=enums.ParseMode.HTML, reply_markup=markup ) except httpx.HTTPError as exc: - await query.message.edit_caption(f"HTTP Exception for IMDB Search - {exc}") + await query.message.edit_caption( + f"HTTP Exception for IMDB Search - {exc}" + ) except AttributeError: await query.message.edit_caption("Sorry, failed getting data from IMDB.") except (MessageNotModified, MessageIdInvalid): diff --git a/misskaty/plugins/inline_search.py b/misskaty/plugins/inline_search.py index b30f4dba..2f08b3e8 100644 --- a/misskaty/plugins/inline_search.py +++ b/misskaty/plugins/inline_search.py @@ -117,9 +117,9 @@ async def inline_menu(self, inline_query: InlineQuery): description="New Calculator", input_message_content=InputTextMessageContent( message_text=f"Made by @{self.me.username}", - disable_web_page_preview=True + disable_web_page_preview=True, ), - reply_markup=calc_btn(inline_query.from_user.id) + reply_markup=calc_btn(inline_query.from_user.id), ) ] else: @@ -130,9 +130,8 @@ async def inline_menu(self, inline_query: InlineQuery): title="Answer", description=f"Result: {result}", input_message_content=InputTextMessageContent( - message_text=f"{data} = {result}", - disable_web_page_preview=True - ) + message_text=f"{data} = {result}", disable_web_page_preview=True + ), ) ] await inline_query.answer( @@ -731,7 +730,9 @@ async def imdb_inl(_, query): f"#{i.replace(' ', '_').replace('-', '_')}, " for i in r_json["keywords"].split(",") ) - res_str += f"🔥 Kata Kunci:\n
{key_[:-2]}
\n" + res_str += ( + f"🔥 Kata Kunci:\n
{key_[:-2]}
\n" + ) if award := sop.select('li[data-testid="award_information"]'): awards = ( award[0] diff --git a/misskaty/plugins/json.py b/misskaty/plugins/json.py index eff4e57f..6095e23a 100644 --- a/misskaty/plugins/json.py +++ b/misskaty/plugins/json.py @@ -1,8 +1,8 @@ """ - * @author yasir - * @date 2022-12-01 09:12:27 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved +* @author yasir +* @date 2022-12-01 09:12:27 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved """ import os diff --git a/misskaty/plugins/locks.py b/misskaty/plugins/locks.py index e4356778..7ca7c818 100644 --- a/misskaty/plugins/locks.py +++ b/misskaty/plugins/locks.py @@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ + import asyncio from logging import getLogger @@ -178,7 +179,7 @@ async def locks_func(_, message): chat_id, ChatPermissions( all_perms=True, - ) + ), ) await message.reply(f"Unlocked Everything in {message.chat.title}") except ChatAdminRequired: diff --git a/misskaty/plugins/media_extractor.py b/misskaty/plugins/media_extractor.py index 75bf824d..18ef67cd 100644 --- a/misskaty/plugins/media_extractor.py +++ b/misskaty/plugins/media_extractor.py @@ -1,9 +1,10 @@ """ - * @author yasir - * @created 2022-12-01 09:12:27 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved +* @author yasir +* @created 2022-12-01 09:12:27 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved """ + import json import os import traceback diff --git a/misskaty/plugins/mediainfo.py b/misskaty/plugins/mediainfo.py index 06b5b4e0..34cc0208 100644 --- a/misskaty/plugins/mediainfo.py +++ b/misskaty/plugins/mediainfo.py @@ -1,9 +1,10 @@ """ - * @author yasir - * @date 2022-12-01 09:12:27 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved +* @author yasir +* @date 2022-12-01 09:12:27 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved """ + import io import subprocess import time @@ -66,7 +67,9 @@ DETAILS ) except: try: - link = await post_to_telegraph(False, "MissKaty MediaInfo", f"{body_text}") + link = await post_to_telegraph( + False, "MissKaty MediaInfo", f"{body_text}" + ) markup = InlineKeyboardMarkup( [[InlineKeyboardButton(text=strings("viweb"), url=link)]] ) @@ -76,7 +79,11 @@ DETAILS out_file.name = "MissKaty_Mediainfo.txt" await ctx.reply_document( out_file, - caption=strings("capt_media").format(ment=ctx.from_user.mention if ctx.from_user else ctx.sender_chat.title), + caption=strings("capt_media").format( + ment=ctx.from_user.mention + if ctx.from_user + else ctx.sender_chat.title + ), thumb="assets/thumb.jpg", reply_markup=markup, ) @@ -119,7 +126,11 @@ DETAILS out_file.name = "MissKaty_Mediainfo.txt" await ctx.reply_document( out_file, - caption=strings("capt_media").format(ment=ctx.from_user.mention if ctx.from_user else ctx.sender_chat.title), + caption=strings("capt_media").format( + ment=ctx.from_user.mention + if ctx.from_user + else ctx.sender_chat.title + ), thumb="assets/thumb.jpg", reply_markup=markup, ) diff --git a/misskaty/plugins/misc_tools.py b/misskaty/plugins/misc_tools.py index 951283c3..1fc2d1a5 100644 --- a/misskaty/plugins/misc_tools.py +++ b/misskaty/plugins/misc_tools.py @@ -5,6 +5,7 @@ * Copyright @YasirPedia All rights reserved """ +import ast import asyncio import contextlib import html @@ -73,11 +74,11 @@ def remove_html_tags(text): def calcExpression(text): try: - return float(eval(text)) + return float(ast.literal_eval(text)) except (SyntaxError, ZeroDivisionError): return "" except TypeError: - return float(eval(text.replace("(", "*("))) + return float(ast.literal_eval(text.replace("(", "*("))) except Exception as e: LOGGER.error(e, exc_info=True) return "" diff --git a/misskaty/plugins/nightmodev2.py b/misskaty/plugins/nightmodev2.py index e5192ab0..0577c6ac 100644 --- a/misskaty/plugins/nightmodev2.py +++ b/misskaty/plugins/nightmodev2.py @@ -5,7 +5,6 @@ import platform import re from datetime import datetime, timedelta -from attr import Attribute import pytz from apscheduler.jobstores.base import ConflictingIdError @@ -17,7 +16,7 @@ from pyrogram.errors import ( ChatNotModified, ChatRestricted, PeerIdInvalid, - QueryIdInvalid + QueryIdInvalid, ) from pyrogram.types import ChatPermissions, InlineKeyboardButton, InlineKeyboardMarkup @@ -241,7 +240,7 @@ async def nightmode_handler(self, msg, strings): can_send_roundvideos=msg.chat.permissions.can_send_roundvideos, can_send_stickers=msg.chat.permissions.can_send_stickers, can_send_videos=msg.chat.permissions.can_send_videos, - can_send_voices=msg.chat.permissions.can_send_voices + can_send_voices=msg.chat.permissions.can_send_voices, ) try: # schedule to enable nightmode diff --git a/misskaty/plugins/notes.py b/misskaty/plugins/notes.py index a6ee3d88..8a6fb52d 100644 --- a/misskaty/plugins/notes.py +++ b/misskaty/plugins/notes.py @@ -21,19 +21,25 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ + from re import findall from pyrogram import filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup -from database.notes_db import delete_note, get_note, get_note_names, save_note, deleteall_notes +from database.notes_db import ( + delete_note, + deleteall_notes, + get_note, + get_note_names, + save_note, +) from misskaty import app -from misskaty.vars import COMMAND_HANDLER from misskaty.core.decorator.errors import capture_err from misskaty.core.decorator.permissions import adminsOnly, member_permissions from misskaty.core.keyboard import ikb from misskaty.helper.functions import extract_text_and_keyb, extract_urls - +from misskaty.vars import COMMAND_HANDLER __MODULE__ = "Notes" __HELP__ = """/notes To Get All The Notes In The Chat. @@ -51,12 +57,16 @@ To change caption of any files use.\n/save [NOTE_NAME] or /addnote [NOTE_NAME] [ """ -@app.on_message(filters.command(["addnote", "save"], COMMAND_HANDLER) & ~filters.private) +@app.on_message( + filters.command(["addnote", "save"], COMMAND_HANDLER) & ~filters.private +) @adminsOnly("can_change_info") async def save_notee(_, message): try: if len(message.command) < 2 or not message.reply_to_message: - await message.reply_msg("**Usage:**\nReply to a message with /save [NOTE_NAME] to save a new note.") + await message.reply_msg( + "**Usage:**\nReply to a message with /save [NOTE_NAME] to save a new note." + ) else: text = message.text.markdown name = text.split(None, 1)[1].strip() @@ -74,7 +84,11 @@ async def save_notee(_, message): elif not replied_message.text and not replied_message.caption: data = None else: - data = replied_message.text.markdown if replied_message.text else replied_message.caption.markdown + data = ( + replied_message.text.markdown + if replied_message.text + else replied_message.caption.markdown + ) if replied_message.text: _type = "text" file_id = None @@ -104,7 +118,9 @@ async def save_notee(_, message): file_id = replied_message.voice.file_id if replied_message.reply_markup and "~" not in data: if urls := extract_urls(replied_message.reply_markup): - response = "\n".join([f"{name}=[{text}, {url}]" for name, text, url in urls]) + response = "\n".join( + [f"{name}=[{text}, {url}]" for name, text, url in urls] + ) data = data + response note = { "type": _type, @@ -116,7 +132,9 @@ async def save_notee(_, message): await save_note(chat_id, name, note) await message.reply_msg(f"__**Saved note {name}.**__") except UnboundLocalError: - return await message.reply_text("**Replied message is inaccessible.\n`Forward the message and try again`**") + return await message.reply_text( + "**Replied message is inaccessible.\n`Forward the message and try again`**" + ) @app.on_message(filters.command("notes", COMMAND_HANDLER) & ~filters.private) @@ -147,7 +165,7 @@ async def get_one_note(self, message): data = _note.get("data") file_id = _note.get("file_id") keyb = None - if data: + if data: if findall(r"\[.+\,.+\]", data): if keyboard := extract_text_and_keyb(ikb, data): data, keyb = keyboard @@ -206,7 +224,9 @@ async def get_one_note(self, message): ) -@app.on_message(filters.command(["delnote", "clear"], COMMAND_HANDLER) & ~filters.private) +@app.on_message( + filters.command(["delnote", "clear"], COMMAND_HANDLER) & ~filters.private +) @adminsOnly("can_change_info") async def del_note(_, message): if len(message.command) < 2: @@ -233,12 +253,16 @@ async def delete_all(_, message): return await message.reply_text("**No notes in this chat.**") keyboard = InlineKeyboardMarkup( [ - [InlineKeyboardButton("YES, DO IT", callback_data="delete_yes"), - InlineKeyboardButton("Cancel", callback_data="delete_no") + [ + InlineKeyboardButton("YES, DO IT", callback_data="delete_yes"), + InlineKeyboardButton("Cancel", callback_data="delete_no"), ] ] ) - await message.reply_text("**Are you sure you want to delete all the notes in this chat forever ?.**", reply_markup=keyboard) + await message.reply_text( + "**Are you sure you want to delete all the notes in this chat forever ?.**", + reply_markup=keyboard, + ) @app.on_callback_query(filters.regex("delete_(.*)")) @@ -248,9 +272,14 @@ async def delete_all_cb(_, cb): permissions = await member_permissions(chat_id, from_user.id) permission = "can_change_info" if permission not in permissions: - return await cb.answer(f"You don't have the required permission.\n Permission: {permission}", show_alert=True) + return await cb.answer( + f"You don't have the required permission.\n Permission: {permission}", + show_alert=True, + ) input = cb.data.split("_", 1)[1] if input == "yes": stoped_all = await deleteall_notes(chat_id) if stoped_all: - return await cb.message.edit("**Successfully deleted all notes on this chat.**") + return await cb.message.edit( + "**Successfully deleted all notes on this chat.**" + ) diff --git a/misskaty/plugins/ocr.py b/misskaty/plugins/ocr.py index c57d069a..06d8b23d 100644 --- a/misskaty/plugins/ocr.py +++ b/misskaty/plugins/ocr.py @@ -1,11 +1,10 @@ """ - * @author yasir - * @date 2022-12-01 09:12:27 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved +* @author yasir +* @date 2022-12-01 09:12:27 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved """ - import os from pyrogram import filters diff --git a/misskaty/plugins/paste.py b/misskaty/plugins/paste.py index af19a4da..d32a97f7 100644 --- a/misskaty/plugins/paste.py +++ b/misskaty/plugins/paste.py @@ -1,9 +1,10 @@ """ - * @author Yasir Aris M - * @created 2022-12-01 09:12:27 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved +* @author Yasir Aris M +* @created 2022-12-01 09:12:27 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved """ + from json import loads as json_loads from os import remove from re import compile as compiles @@ -214,7 +215,9 @@ async def wastepaste(_, message): "expire_at": 0, "expire_in": 0, } - response = await fetch.post("https://paste.yasir.eu.org/api/new", json=json_data) + response = await fetch.post( + "https://paste.yasir.eu.org/api/new", json=json_data + ) url = f"https://paste.yasir.eu.org/{response.json()['id']}" except Exception as e: return await msg.edit_msg(f"ERROR: {e}") @@ -282,7 +285,9 @@ async def nekopaste(_, message): try: x = ( - await fetch.post("https://nekobin.com/api/documents", json={"content": data}) + await fetch.post( + "https://nekobin.com/api/documents", json={"content": data} + ) ).json() url = f"https://nekobin.com/{x['result']['key']}" except Exception as e: diff --git a/misskaty/plugins/ping.py b/misskaty/plugins/ping.py index 9b517e51..907f2f18 100644 --- a/misskaty/plugins/ping.py +++ b/misskaty/plugins/ping.py @@ -1,9 +1,10 @@ """ - * @author yasir - * @date 2022-12-01 09:12:27 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved +* @author yasir +* @date 2022-12-01 09:12:27 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved """ + import platform import time from asyncio import Lock @@ -18,9 +19,9 @@ from misskaty import app, botStartTime, misskaty_version from misskaty.helper.human_read import get_readable_time from misskaty.vars import COMMAND_HANDLER - PING_LOCK = Lock() + @app.on_message(filters.command(["ping"], COMMAND_HANDLER)) async def ping(_, ctx: Message): currentTime = get_readable_time(time.time() - botStartTime) diff --git a/misskaty/plugins/pypi_search.py b/misskaty/plugins/pypi_search.py index 422a4167..9cf776f9 100644 --- a/misskaty/plugins/pypi_search.py +++ b/misskaty/plugins/pypi_search.py @@ -1,9 +1,10 @@ """ - * @author yasir - * @date 2023-01-23 19:41:27 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved +* @author yasir +* @date 2023-01-23 19:41:27 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved """ + from pykeyboard import InlineButton, InlineKeyboard from pyrogram import filters from pyrogram.errors import MessageTooLong, QueryIdInvalid diff --git a/misskaty/plugins/session_generator.py b/misskaty/plugins/session_generator.py index 22d72552..2f2bc614 100644 --- a/misskaty/plugins/session_generator.py +++ b/misskaty/plugins/session_generator.py @@ -33,7 +33,6 @@ __HELP__ = """ /genstring - Generate string session using this bot. Only support Pyrogram v2 and Telethon. """ - ask_ques = "**» Please choose the library for which you want generate string :**\n\nNote: I'm not collecting any personal info from this feature, you can deploy own bot if you want." buttons_ques = [ [ diff --git a/misskaty/plugins/start_help.py b/misskaty/plugins/start_help.py index 7e47a726..24ef74f4 100644 --- a/misskaty/plugins/start_help.py +++ b/misskaty/plugins/start_help.py @@ -1,9 +1,10 @@ """ - * @author yasir - * @date 2022-12-01 09:12:27 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved - """ +* @author yasir +* @date 2022-12-01 09:12:27 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved +""" + import re from pyrogram import Client, filters @@ -20,7 +21,6 @@ from misskaty.helper import bot_sys_stats, paginate_modules from misskaty.helper.localization import use_chat_lang from misskaty.vars import COMMAND_HANDLER - home_keyboard_pm = InlineKeyboardMarkup( [ [ @@ -104,13 +104,17 @@ async def start(self, ctx: Message, strings): strings("help_name").format(mod=HELPABLE[module].__MODULE__) + HELPABLE[module].__HELP__ ) - await ctx.reply_msg(text, disable_web_page_preview=True, message_effect_id=5104841245755180586) + await ctx.reply_msg( + text, + disable_web_page_preview=True, + message_effect_id=5104841245755180586, + ) if module == "federation": return await ctx.reply( text=text, reply_markup=FED_MARKUP, disable_web_page_preview=True, - message_effect_id=5104841245755180586 + message_effect_id=5104841245755180586, ) await ctx.reply( text, @@ -118,13 +122,12 @@ async def start(self, ctx: Message, strings): [[InlineKeyboardButton("back", callback_data="help_back")]] ), disable_web_page_preview=True, - message_effect_id=5104841245755180586) + message_effect_id=5104841245755180586, + ) elif name == "help": text, keyb = await help_parser(ctx.from_user.first_name) await ctx.reply_msg( - text, - reply_markup=keyb, - message_effect_id=5104841245755180586 + text, reply_markup=keyb, message_effect_id=5104841245755180586 ) else: await self.send_photo( @@ -133,7 +136,7 @@ async def start(self, ctx: Message, strings): caption=home_text_pm, reply_markup=home_keyboard_pm, reply_to_message_id=ctx.id, - message_effect_id=5104841245755180586 + message_effect_id=5104841245755180586, ) @@ -144,7 +147,7 @@ async def commands_callbacc(_, cb: CallbackQuery): cb.message.chat.id, text=text, reply_markup=keyb, - message_effect_id=5104841245755180586 + message_effect_id=5104841245755180586, ) await cb.message.delete_msg() @@ -187,19 +190,26 @@ async def help_command(_, ctx: Message, strings): strings("help_name").format(mod=HELPABLE[name].__MODULE__) + HELPABLE[name].__HELP__ ) - await ctx.reply_msg(text, disable_web_page_preview=True, message_effect_id=5104841245755180586) + await ctx.reply_msg( + text, + disable_web_page_preview=True, + message_effect_id=5104841245755180586, + ) else: text, help_keyboard = await help_parser(ctx.from_user.first_name) await ctx.reply_msg( text, reply_markup=help_keyboard, disable_web_page_preview=True, - message_effect_id=5104841245755180586 + message_effect_id=5104841245755180586, ) else: text, help_keyboard = await help_parser(ctx.from_user.first_name) await ctx.reply_msg( - text, reply_markup=help_keyboard, disable_web_page_preview=True, message_effect_id=5104841245755180586 + text, + reply_markup=help_keyboard, + disable_web_page_preview=True, + message_effect_id=5104841245755180586, ) diff --git a/misskaty/plugins/stickers.py b/misskaty/plugins/stickers.py index eeeb511c..846869cf 100644 --- a/misskaty/plugins/stickers.py +++ b/misskaty/plugins/stickers.py @@ -307,7 +307,7 @@ async def kang_sticker(self: Client, ctx: Message, strings): ), emoji=sticker_emoji, ) - ] + ], ) ) except PeerIdInvalid: diff --git a/misskaty/plugins/ubot_plugin.py b/misskaty/plugins/ubot_plugin.py index 6c169d86..d6b8df02 100644 --- a/misskaty/plugins/ubot_plugin.py +++ b/misskaty/plugins/ubot_plugin.py @@ -1,9 +1,10 @@ """ - * @author yasir - * @date 2022-12-01 09:12:27 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved +* @author yasir +* @date 2022-12-01 09:12:27 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved """ + # Code in this plugin to learn basic userbot in pyrogram import os from datetime import datetime diff --git a/misskaty/plugins/web_scraper.py b/misskaty/plugins/web_scraper.py index e4a4d195..923d2ba8 100644 --- a/misskaty/plugins/web_scraper.py +++ b/misskaty/plugins/web_scraper.py @@ -1,17 +1,18 @@ """ - * @author yasir - * @created 2022-12-01 09:12:27 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved +* @author yasir +* @created 2022-12-01 09:12:27 +* @projectName MissKatyPyro +* Copyright @YasirPedia All rights reserved """ + import contextlib -import httpx import logging import re import sys import traceback import cloudscraper +import httpx from bs4 import BeautifulSoup from cachetools import TTLCache from pykeyboard import InlineButton, InlineKeyboard @@ -20,7 +21,7 @@ from pyrogram.types import Message from database import dbname from misskaty import app -from misskaty.helper import Cache, Kusonime, fetch, use_chat_lang, post_to_telegraph +from misskaty.helper import Cache, Kusonime, fetch, post_to_telegraph, use_chat_lang __MODULE__ = "WebScraper" __HELP__ = """ @@ -76,28 +77,28 @@ async def getDataTerbit21(msg, kueri, CurrentPage, strings): with contextlib.redirect_stdout(sys.stderr): try: if kueri: - terbitjson = await fetch.get(f"{web['yasirapi']}/terbit21?q={kueri}") + terbitjson = await fetch.get( + f"{web['yasirapi']}/terbit21?q={kueri}" + ) else: terbitjson = await fetch.get(f"{web['yasirapi']}/terbit21") terbitjson.raise_for_status() except httpx.HTTPError as exc: - await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - {exc}") + await msg.edit_msg( + f"ERROR: Failed to fetch data from {exc.request.url} - {exc}" + ) return None, None res = terbitjson.json() if not res.get("result"): await msg.edit_msg(strings("no_result"), del_in=5) return None, None - SCRAP_DICT.add( - msg.id, [split_arr(res["result"], 6), kueri], timeout=1800 - ) + SCRAP_DICT.add(msg.id, [split_arr(res["result"], 6), kueri], timeout=1800) index = int(CurrentPage - 1) PageLen = len(SCRAP_DICT[msg.id][0]) if kueri: TerbitRes = strings("header_with_query").format(web="Terbit21", kueri=kueri) else: - TerbitRes = strings("header_no_query").format( - web="Terbit21", cmd="terbit21" - ) + TerbitRes = strings("header_no_query").format(web="Terbit21", cmd="terbit21") for c, i in enumerate(SCRAP_DICT[msg.id][0][index], start=1): TerbitRes += f"{index*6+c}. {i['judul']}\n{strings('cat_text')}: {i['kategori']}\n" TerbitRes += ( @@ -119,7 +120,9 @@ async def getDatalk21(msg, kueri, CurrentPage, strings): lk21json = await fetch.get(f"{web['yasirapi']}/lk21") lk21json.raise_for_status() except httpx.HTTPError as exc: - await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - {exc}") + await msg.edit_msg( + f"ERROR: Failed to fetch data from {exc.request.url} - {exc}" + ) return None, None res = lk21json.json() if not res.get("result"): @@ -129,9 +132,7 @@ async def getDatalk21(msg, kueri, CurrentPage, strings): index = int(CurrentPage - 1) PageLen = len(SCRAP_DICT[msg.id][0]) if kueri: - lkResult = strings("header_with_query").format( - web="Layarkaca21", kueri=kueri - ) + lkResult = strings("header_with_query").format(web="Layarkaca21", kueri=kueri) else: lkResult = strings("header_no_query").format(web="Layarkaca21", cmd="lk21") for c, i in enumerate(SCRAP_DICT[msg.id][0][index], start=1): @@ -150,12 +151,18 @@ async def getDataPahe(msg, kueri, CurrentPage, strings): with contextlib.redirect_stdout(sys.stderr): try: if kueri: - pahejson = await fetch.get(f"{web['yasirapi']}/pahe?q={kueri}&domain={web['pahe']}") + pahejson = await fetch.get( + f"{web['yasirapi']}/pahe?q={kueri}&domain={web['pahe']}" + ) else: - pahejson = await fetch.get(f"{web['yasirapi']}/pahe?domain={web['pahe']}") + pahejson = await fetch.get( + f"{web['yasirapi']}/pahe?domain={web['pahe']}" + ) pahejson.raise_for_status() except httpx.HTTPError as exc: - await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - {exc}") + await msg.edit_msg( + f"ERROR: Failed to fetch data from {exc.request.url} - {exc}" + ) return None, None res = pahejson.json() if not res.get("result"): @@ -170,9 +177,7 @@ async def getDataPahe(msg, kueri, CurrentPage, strings): else strings("header_no_query").format(web="Pahe", cmd="pahe") ) for c, i in enumerate(SCRAP_DICT[msg.id][0][index], start=1): - paheResult += ( - f"{index*6+c}. {i['judul']}\n\n" - ) + paheResult += f"{index*6+c}. {i['judul']}\n\n" return paheResult, PageLen @@ -187,7 +192,10 @@ async def getDataKuso(msg, kueri, CurrentPage, user, strings): ) data.raise_for_status() except httpx.HTTPError as exc: - await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - {exc}", disable_web_page_preview=True) + await msg.edit_msg( + f"ERROR: Failed to fetch data from {exc.request.url} - {exc}", + disable_web_page_preview=True, + ) return None, 0, None, None res = BeautifulSoup(data, "lxml").find_all("h2", {"class": "episodeye"}) for i in res: @@ -237,7 +245,9 @@ async def getDataMovieku(msg, kueri, CurrentPage, strings): ) data.raise_for_status() except httpx.HTTPError as exc: - await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - {exc}") + await msg.edit_msg( + f"ERROR: Failed to fetch data from {exc.request.url} - {exc}" + ) return None, None r = BeautifulSoup(data, "lxml") res = r.find_all(class_="bx") @@ -271,11 +281,15 @@ async def getDataNodrakor(msg, kueri, CurrentPage, user, strings): with contextlib.redirect_stdout(sys.stderr): try: data = await fetch.get( - f"{web['nodrakor']}/?s={kueri}", follow_redirects=True, + f"{web['nodrakor']}/?s={kueri}", + follow_redirects=True, ) data.raise_for_status() except httpx.HTTPError as exc: - await msg.edit_msg(f"HTTP Exception for {exc.request.url} - {exc}", disable_web_page_preview=True) + await msg.edit_msg( + f"HTTP Exception for {exc.request.url} - {exc}", + disable_web_page_preview=True, + ) return None, 0, None text = BeautifulSoup(data, "lxml") entry = text.find_all(class_="entry-header") @@ -319,11 +333,15 @@ async def getDataSavefilm21(msg, kueri, CurrentPage, user, strings): with contextlib.redirect_stdout(sys.stderr): try: data = await fetch.get( - f"{web['savefilm21']}/?s={kueri}", follow_redirects=True, + f"{web['savefilm21']}/?s={kueri}", + follow_redirects=True, ) data.raise_for_status() except httpx.HTTPError as exc: - await msg.edit_msg(f"HTTP Exception for {exc.request.url} - {exc}", disable_web_page_preview=True) + await msg.edit_msg( + f"HTTP Exception for {exc.request.url} - {exc}", + disable_web_page_preview=True, + ) return None, 0, None text = BeautifulSoup(data, "lxml") entry = text.find_all(class_="entry-header") @@ -367,13 +385,17 @@ async def getDataLendrive(msg, kueri, CurrentPage, user, strings): try: if kueri: data = await fetch.get( - f"{web['lendrive']}/?s={kueri}", follow_redirects=True, + f"{web['lendrive']}/?s={kueri}", + follow_redirects=True, ) else: data = await fetch.get(web["lendrive"], follow_redirects=True) data.raise_for_status() except httpx.HTTPError as exc: - await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - {exc}", disable_web_page_preview=True) + await msg.edit_msg( + f"ERROR: Failed to fetch data from {exc.request.url} - {exc}", + disable_web_page_preview=True, + ) return None, 0, None res = BeautifulSoup(data, "lxml") lenddata = [] @@ -391,7 +413,12 @@ async def getDataLendrive(msg, kueri, CurrentPage, user, strings): else o.find(class_="typez BD") ) lenddata.append( - {"judul": title, "link": link, "quality": kualitas or "N/A", "status": status} + { + "judul": title, + "link": link, + "quality": kualitas or "N/A", + "status": status, + } ) if not lenddata: await msg.edit_msg(strings("no_result"), del_in=5) @@ -422,11 +449,15 @@ async def getDataMelong(msg, kueri, CurrentPage, user, strings): with contextlib.redirect_stdout(sys.stderr): try: data = await fetch.get( - f"{web['melongmovie']}/?s={kueri}", follow_redirects=True, + f"{web['melongmovie']}/?s={kueri}", + follow_redirects=True, ) data.raise_for_status() except httpx.HTTPError as exc: - await msg.edit_msg(f"HTTP Exception for {exc.request.url} - {exc}", disable_web_page_preview=True) + await msg.edit_msg( + f"HTTP Exception for {exc.request.url} - {exc}", + disable_web_page_preview=True, + ) return None, 0, None bs4 = BeautifulSoup(data, "lxml") melongdata = [] @@ -472,7 +503,10 @@ async def getDataGomov(msg, kueri, CurrentPage, user, strings): ) gomovv.raise_for_status() except httpx.HTTPError as exc: - await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - {exc}", disable_web_page_preview=True) + await msg.edit_msg( + f"ERROR: Failed to fetch data from {exc.request.url} - {exc}", + disable_web_page_preview=True, + ) return None, 0, None text = BeautifulSoup(gomovv, "lxml") entry = text.find_all(class_="entry-header") @@ -543,8 +577,8 @@ async def getSame(msg, query, current_page, strings): PageLen = len(savedict[msg.id][0]) sameresult = "".join( f"{index * 6 + c}. {i['title']}\nStatus: {i['sta']}\nRating: {i['rate']}\n\n" - for c, i in enumerate(savedict[msg.id][0][index], start=1) - ) + for c, i in enumerate(savedict[msg.id][0][index], start=1) + ) return sameresult, PageLen @@ -634,7 +668,7 @@ async def pahe_s(_, message, strings): # Gomov CMD -@app.on_cmd(["gomov","klikxxi"], no_channel=True) +@app.on_cmd(["gomov", "klikxxi"], no_channel=True) @use_chat_lang() async def gomov_s(self, message, strings): kueri = " ".join(message.command[1:]) @@ -1287,7 +1321,9 @@ async def kusonime_scrap(client, callback_query, strings): ) try: if init_url := data_kuso.get(link, False): - await callback_query.message.edit_msg(init_url.get("ph_url"), reply_markup=keyboard) + await callback_query.message.edit_msg( + init_url.get("ph_url"), reply_markup=keyboard + ) tgh = await kuso.telegraph(link, client.me.username) data_kuso[link] = {"ph_url": tgh} return await callback_query.message.edit_msg(tgh, reply_markup=keyboard) @@ -1332,9 +1368,14 @@ async def savefilm21_scrap(_, callback_query, strings): strings("res_scrape").format(link=link, kl=res), reply_markup=keyboard ) except httpx.HTTPError as exc: - await callback_query.message.edit_msg(f"HTTP Exception for {exc.request.url} - {exc}", reply_markup=keyboard) + await callback_query.message.edit_msg( + f"HTTP Exception for {exc.request.url} - {exc}", + reply_markup=keyboard, + ) except Exception as err: - await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard) + await callback_query.message.edit_msg( + f"ERROR: {err}", reply_markup=keyboard + ) # NoDrakor DDL @@ -1367,26 +1408,35 @@ async def nodrakorddl_scrap(_, callback_query, strings): html.raise_for_status() soup = BeautifulSoup(html.text, "lxml") if "/tv/" in link: - result = soup.find("div", {"entry-content entry-content-single"}).find_all("p") + result = soup.find( + "div", {"entry-content entry-content-single"} + ).find_all("p") msg = "".join(str(f"{i}\n") for i in result) link = await post_to_telegraph(False, "MissKaty NoDrakor", msg) return await callback_query.message.edit_msg( - strings("res_scrape").format(link=link, kl=link), reply_markup=keyboard + strings("res_scrape").format(link=link, kl=link), + reply_markup=keyboard, ) res = soup.find_all(class_="button button-shadow") res = "".join(f"{i.text}\n{i['href']}\n\n" for i in res) if len(res) > 3500: link = await post_to_telegraph(False, "MissKaty NoDrakor", res) return await callback_query.message.edit_msg( - strings("res_scrape").format(link=link, kl=link), reply_markup=keyboard + strings("res_scrape").format(link=link, kl=link), + reply_markup=keyboard, ) await callback_query.message.edit_msg( strings("res_scrape").format(link=link, kl=res), reply_markup=keyboard ) except httpx.HTTPError as exc: - await callback_query.message.edit_msg(f"HTTP Exception for {exc.request.url} - {exc}", reply_markup=keyboard) + await callback_query.message.edit_msg( + f"HTTP Exception for {exc.request.url} - {exc}", + reply_markup=keyboard, + ) except Exception as err: - await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard) + await callback_query.message.edit_msg( + f"ERROR: {err}", reply_markup=keyboard + ) # Scrape Link Download Movieku.CC @@ -1409,14 +1459,18 @@ async def muviku_scrap(_, message, strings): data.append({"link": link, "kualitas": kualitas}) if not data: return await message.reply(strings("no_result")) - res = "".join(f"Host: {i['kualitas']}\n{i['link']}\n\n" for i in data) + res = "".join( + f"Host: {i['kualitas']}\n{i['link']}\n\n" for i in data + ) await message.reply(res) except IndexError: return await message.reply( strings("invalid_cmd_scrape").format(cmd=message.command[0]) ) except httpx.HTTPError as exc: - await message.reply(f"HTTP Exception for {exc.request.url} - {exc}") + await message.reply( + f"HTTP Exception for {exc.request.url} - {exc}" + ) except Exception as e: await message.reply(f"ERROR: {str(e)}") @@ -1459,9 +1513,14 @@ async def melong_scrap(_, callback_query, strings): strings("res_scrape").format(link=link, kl=rep), reply_markup=keyboard ) except httpx.HTTPError as exc: - await callback_query.message.edit_msg(f"HTTP Exception for {exc.request.url} - {exc}", reply_markup=keyboard) + await callback_query.message.edit_msg( + f"HTTP Exception for {exc.request.url} - {exc}", + reply_markup=keyboard, + ) except Exception as err: - await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard) + await callback_query.message.edit_msg( + f"ERROR: {err}", reply_markup=keyboard + ) # Scrape DDL Link Gomov @@ -1503,9 +1562,14 @@ async def gomov_dl(_, callback_query, strings): strings("res_scrape").format(link=link, kl=hasil), reply_markup=keyboard ) except httpx.HTTPError as exc: - await callback_query.message.edit_msg(f"HTTP Exception for {exc.request.url} - {exc}", reply_markup=keyboard) + await callback_query.message.edit_msg( + f"HTTP Exception for {exc.request.url} - {exc}", + reply_markup=keyboard, + ) except Exception as err: - await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard) + await callback_query.message.edit_msg( + f"ERROR: {err}", reply_markup=keyboard + ) @app.on_cb("lendriveextract#") @@ -1541,12 +1605,18 @@ async def lendrive_dl(_, callback_query, strings): continue kl += f"{i.find('strong')}:\n" kl += "".join( - f"[ {a.text} ]\n" for a in i.findAll("a") + f"[ {a.text} ]\n" + for a in i.findAll("a") ) await callback_query.message.edit_msg( strings("res_scrape").format(link=link, kl=kl), reply_markup=keyboard ) except httpx.HTTPError as exc: - await callback_query.message.edit_msg(f"HTTP Exception for {exc.request.url} - {exc}", reply_markup=keyboard) + await callback_query.message.edit_msg( + f"HTTP Exception for {exc.request.url} - {exc}", + reply_markup=keyboard, + ) except Exception as err: - await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard) + await callback_query.message.edit_msg( + f"ERROR: {err}", reply_markup=keyboard + ) diff --git a/misskaty/plugins/webss.py b/misskaty/plugins/webss.py index 9b08f684..b42d6803 100644 --- a/misskaty/plugins/webss.py +++ b/misskaty/plugins/webss.py @@ -33,7 +33,9 @@ async def take_ss(_, ctx: Message, strings): msg = await ctx.reply_msg(strings("wait_str")) try: url = f"https://webss.yasirweb.eu.org/api/screenshot?resX=1280&resY=900&outFormat=jpg&waitTime=1000&isFullPage=false&dismissModals=false&url={url}" - downloader = SmartDL(url, download_file_path, progress_bar=False, timeout=15, verify=False) + downloader = SmartDL( + url, download_file_path, progress_bar=False, timeout=15, verify=False + ) downloader.start(blocking=True) await gather( *[ diff --git a/misskaty/plugins/ytdl_plugins.py b/misskaty/plugins/ytdl_plugins.py index bfba1aa7..8a1add49 100644 --- a/misskaty/plugins/ytdl_plugins.py +++ b/misskaty/plugins/ytdl_plugins.py @@ -27,7 +27,7 @@ from pyrogram.types import ( from misskaty import app from misskaty.core import pyro_cooldown from misskaty.core.decorator import capture_err, new_task -from misskaty.helper import fetch, use_chat_lang, isValidURL +from misskaty.helper import fetch, isValidURL, use_chat_lang from misskaty.vars import COMMAND_HANDLER, LOG_CHANNEL, SUDO LOGGER = getLogger("MissKaty") @@ -94,7 +94,11 @@ async def ytsearch(_, ctx: Message, strings): async def ytdownv2(self, ctx: Message, strings): if not ctx.from_user: return await ctx.reply_msg(strings("no_channel")) - url = ctx.command[1] if ctx.command and len(ctx.command) > 1 else ctx.text or ctx.caption + url = ( + ctx.command[1] + if ctx.command and len(ctx.command) > 1 + else ctx.text or ctx.caption + ) if not isValidURL(url): return await ctx.reply_msg(strings("invalid_link")) async with iYTDL(log_group_id=0, cache_path="cache", silent=True) as ytdl: diff --git a/update.py b/update.py index 0145e797..96178ff8 100644 --- a/update.py +++ b/update.py @@ -15,7 +15,9 @@ basicConfig( format="[%(levelname)s] - [%(asctime)s - %(name)s - %(message)s] -> [%(module)s:%(lineno)d]", datefmt="%d-%b-%y %H:%M:%S", handlers=[ - handlers.RotatingFileHandler("MissKatyLogs.txt", mode="w+", maxBytes=5242880, backupCount=1), + handlers.RotatingFileHandler( + "MissKatyLogs.txt", mode="w+", maxBytes=5242880, backupCount=1 + ), StreamHandler(), ], ) diff --git a/utils.py b/utils.py index 6efc20e6..09aeb0b6 100644 --- a/utils.py +++ b/utils.py @@ -128,7 +128,11 @@ def extract_user(message: Message) -> Union[int, str]: user_first_name = message.reply_to_message.from_user.first_name elif len(message.command) > 1: - if message.entities and len(message.entities) > 1 and message.entities[1].type.value == "text_mention": + if ( + message.entities + and len(message.entities) > 1 + and message.entities[1].type.value == "text_mention" + ): required_entity = message.entities[1] user_id = required_entity.user.id user_first_name = required_entity.user.first_name