From 82728f2cea796b5b3ef922f64c072e202c022429 Mon Sep 17 00:00:00 2001 From: yasir Date: Fri, 2 Dec 2022 21:31:25 +0700 Subject: [PATCH] Logging --- README.md | 2 +- logging.conf | 32 --- misskaty/__init__.py | 16 +- misskaty/__main__.py | 23 +- misskaty/plugins/__init__.py | 25 +- misskaty/plugins/admin.py | 3 +- misskaty/plugins/auto_approve.py | 36 ++- misskaty/plugins/auto_forwarder.py | 9 +- misskaty/plugins/banned.py | 13 +- misskaty/plugins/bypass.py | 7 + misskaty/plugins/copy_forward.py | 38 ++- misskaty/plugins/download_upload.py | 5 +- misskaty/plugins/filter_request.py | 285 +++++++++++++++++--- misskaty/plugins/genss.py | 17 +- misskaty/plugins/grup_tools.py | 6 +- misskaty/plugins/json.py | 8 + misskaty/plugins/mediainfo.py | 45 +++- misskaty/plugins/misc_tools.py | 400 +++++++++++++++++++++++----- misskaty/plugins/ocr.py | 9 +- misskaty/plugins/paste.py | 7 + misskaty/plugins/scrapwebsite.py | 8 + misskaty/plugins/sub_extractor.py | 7 + misskaty/plugins/ubot_plugin.py | 1 + misskaty/plugins/ytdl_download.py | 16 +- misskaty/vars.py | 4 +- utils.py | 29 +- 26 files changed, 806 insertions(+), 245 deletions(-) delete mode 100644 logging.conf diff --git a/README.md b/README.md index 772512d0..d438064e 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ This repo has many bugs and i dont have time to fix it. If you can help me, plea You can check demo this repo in this bot [MissKatyPyro](https://t.me/MissKatyRoBot) ## Features -I'm forget about it, try asking doraemon maybe know.. :) +Check by yourself.. :) ## Variables diff --git a/logging.conf b/logging.conf deleted file mode 100644 index c523b779..00000000 --- a/logging.conf +++ /dev/null @@ -1,32 +0,0 @@ -[loggers] -keys=root - -[handlers] -keys=consoleHandler,fileHandler - -[formatters] -keys=consoleFormatter,fileFormatter - -[logger_root] -level=DEBUG -handlers=consoleHandler,fileHandler - -[handler_consoleHandler] -class=StreamHandler -level=INFO -formatter=consoleFormatter -args=(sys.stdout,) - -[handler_fileHandler] -class=FileHandler -level=ERROR -formatter=fileFormatter -args=('MissKatyLogs.txt','w',) - -[formatter_consoleFormatter] -format=%(asctime)s - %(lineno)d - %(name)s - %(module)s - %(levelname)s - %(message)s -datefmt=%I:%M:%S %p - -[formatter_fileFormatter] -format=[%(asctime)s:%(name)s:%(lineno)d:%(levelname)s] %(message)s -datefmt=%m/%d/%Y %I:%M:%S %p diff --git a/misskaty/__init__.py b/misskaty/__init__.py index 4d51adbc..027aebbf 100644 --- a/misskaty/__init__.py +++ b/misskaty/__init__.py @@ -1,18 +1,18 @@ -import logging +from logging import basicConfig, FileHandler, StreamHandler, getLogger import time -import logging.config - -# Get logging -logging.config.fileConfig("logging.conf") -logging.getLogger().setLevel(logging.INFO) -logging.getLogger("pyrogram").setLevel(logging.ERROR) from pyrogram import Client from misskaty.vars import API_ID, API_HASH, BOT_TOKEN, USER_SESSION +basicConfig( + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", + handlers=[FileHandler("MissKatyLogs.txt"), StreamHandler()], + level=INFO, +) + MOD_LOAD = [] MOD_NOLOAD = [] HELPABLE = {} - +LOGGER = getLogger(__name__) botStartTime = time.time() # Pyrogram Bot Client diff --git a/misskaty/__main__.py b/misskaty/__main__.py index 32b59c1b..2e1e1e73 100644 --- a/misskaty/__main__.py +++ b/misskaty/__main__.py @@ -5,15 +5,14 @@ * @projectName MissKatyPyro * Copyright @YasirPedia All rights reserved """ -import asyncio, importlib, re, logging -from misskaty import app, user, HELPABLE +import asyncio, importlib, re +from misskaty import app, user, HELPABLE, LOGGER from misskaty.plugins import ALL_MODULES from misskaty.helper import paginate_modules from misskaty.helper.tools import bot_sys_stats from database.users_chats_db import db from misskaty.vars import LOG_CHANNEL from utils import temp -from logging import info as log_info from pyrogram.raw.all import layer from pyrogram import idle, __version__, filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup @@ -44,15 +43,15 @@ async def start_bot(): await user.start() me = await app.get_me() ubot = await user.get_me() - log_info("+===============================================================+") - log_info("| MissKatyPyro |") - log_info("+===============+===============+===============+===============+") - log_info(bot_modules) - log_info("+===============+===============+===============+===============+") - log_info(f"[INFO]: BOT STARTED AS @{me.username}!") + LOGGER.info("+===============================================================+") + LOGGER.info("| MissKatyPyro |") + LOGGER.info("+===============+===============+===============+===============+") + LOGGER.info(bot_modules) + LOGGER.info("+===============+===============+===============+===============+") + LOGGER.info(f"[INFO]: BOT STARTED AS @{me.username}!") try: - log_info("[INFO]: SENDING ONLINE STATUS") + LOGGER.info("[INFO]: SENDING ONLINE STATUS") await app.send_message( 617426792, f"USERBOT AND BOT STARTED with Pyrogram v{__version__}..\nUserBot: {ubot.first_name}\nBot: {me.first_name}\n\nwith Pyrogram v{__version__} (Layer {layer}) started on @{me.username}.", @@ -63,7 +62,7 @@ async def start_bot(): await idle() await app.stop() await user.stop() - print("[INFO]: Bye!") + LOGGER.info("[INFO]: Bye!") home_keyboard_pm = InlineKeyboardMarkup( @@ -339,4 +338,4 @@ if __name__ == "__main__": try: loop.run_until_complete(start_bot()) except KeyboardInterrupt: - logging.info("----------------------- Service Stopped -----------------------") + LOGGER.info("----------------------- Service Stopped -----------------------") diff --git a/misskaty/plugins/__init__.py b/misskaty/plugins/__init__.py index 25fde160..ba586858 100644 --- a/misskaty/plugins/__init__.py +++ b/misskaty/plugins/__init__.py @@ -8,9 +8,8 @@ import glob import importlib import sys -from logging import info as log_info from os.path import basename, dirname, isfile -from misskaty import MOD_LOAD, MOD_NOLOAD +from misskaty import MOD_LOAD, MOD_NOLOAD, LOGGER def __list_all_modules(): @@ -18,28 +17,36 @@ def __list_all_modules(): # folder for the * in __main__ to work. mod_paths = glob.glob(f"{dirname(__file__)}/*.py") all_modules = [ - basename(f)[:-3] for f in mod_paths if isfile(f) and f.endswith(".py") - and not f.endswith("__init__.py") and not f.endswith("__main__.py") + basename(f)[:-3] + for f in mod_paths + if isfile(f) + and f.endswith(".py") + and not f.endswith("__init__.py") + and not f.endswith("__main__.py") ] if MOD_LOAD or MOD_NOLOAD: to_load = MOD_LOAD if to_load: if not all( - any(mod == module_name for module_name in all_modules) - for mod in to_load): + any(mod == module_name for module_name in all_modules) + for mod in to_load + ): sys.exit() else: to_load = all_modules - return [item for item in to_load - if item not in MOD_NOLOAD] if MOD_NOLOAD else to_load + return ( + [item for item in to_load if item not in MOD_NOLOAD] + if MOD_NOLOAD + else to_load + ) return all_modules -log_info("[INFO]: IMPORTING PLUGINS") +LOGGER.info("[INFO]: IMPORTING PLUGINS") importlib.import_module("misskaty.plugins.__main__") ALL_MODULES = sorted(__list_all_modules()) __all__ = ALL_MODULES + ["ALL_MODULES"] diff --git a/misskaty/plugins/admin.py b/misskaty/plugins/admin.py index bbfa3c56..4bda289e 100644 --- a/misskaty/plugins/admin.py +++ b/misskaty/plugins/admin.py @@ -1,4 +1,3 @@ -import logging import asyncio, re from misskaty import app from misskaty.helper.functions import ( @@ -64,7 +63,7 @@ async def admin_cache_func(_, cmu): ) ], } - logging.info(f"Updated admin cache for {cmu.chat.id} [{cmu.chat.title}]") + LOGGER.info(f"Updated admin cache for {cmu.chat.id} [{cmu.chat.title}]") # Purge CMD diff --git a/misskaty/plugins/auto_approve.py b/misskaty/plugins/auto_approve.py index c476afd1..39aab085 100644 --- a/misskaty/plugins/auto_approve.py +++ b/misskaty/plugins/auto_approve.py @@ -1,3 +1,10 @@ +""" + * @author yasir + * @date 2022-12-01 09:12:27 + * @lastModified 2022-12-01 09:32:31 + * @projectName MissKatyPyro + * Copyright @YasirPedia All rights reserved +""" from misskaty import app from pyrogram import filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup @@ -9,7 +16,18 @@ from misskaty.core.decorator.errors import capture_err @app.on_chat_join_request(filters.chat(-1001686184174)) async def approve_join_chat(c, m): try: - markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="Sudah", callback_data=f"approve_{m.chat.id}"), InlineKeyboardButton(text="Belum", callback_data=f"declined_{m.chat.id}")]]) + markup = InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="Sudah", callback_data=f"approve_{m.chat.id}" + ), + InlineKeyboardButton( + text="Belum", callback_data=f"declined_{m.chat.id}" + ), + ] + ] + ) await c.send_message( m.from_user.id, "PERMINTAAN JOIN CHANNEL YMOVIEZ REBORN\n\nSebelum masuk ke channel ada tes kejujuran, apakah anda sudah membaca catatan di @YMovieZ_New? Jika sudah silahkan klik Sudah, jika kamu berbohong resiko kamu tanggung sendiri πŸ˜Άβ€πŸŒ«οΈ.\n\nBot by @YasirPediaChannel", @@ -24,10 +42,14 @@ async def approve_join_chat(c, m): async def approve_chat(c, q): i, chat = q.data.split("_") try: - await q.message.edit("Yeayy, selamat kamu bisa bergabung di Channel YMovieZ Reborn...") + await q.message.edit( + "Yeayy, selamat kamu bisa bergabung di Channel YMovieZ Reborn..." + ) await c.approve_chat_join_request(chat, q.from_user.id) except UserAlreadyParticipant: - await q.message.edit("Kamu sudah di acc join grup, jadi ga perlu menekan button.") + await q.message.edit( + "Kamu sudah di acc join grup, jadi ga perlu menekan button." + ) except Exception as err: await q.message.edit(err) @@ -36,9 +58,13 @@ async def approve_chat(c, q): async def decline_chat(c, q): i, chat = q.data.split("_") try: - await q.message.edit("Yahh, kamu ditolak join channel. Biasakan rajin membaca yahhh..") + await q.message.edit( + "Yahh, kamu ditolak join channel. Biasakan rajin membaca yahhh.." + ) await c.decline_chat_join_request(chat, q.from_user.id) except UserAlreadyParticipant: - await q.message.edit("Kamu sudah di acc join grup, jadi ga perlu menekan button.") + await q.message.edit( + "Kamu sudah di acc join grup, jadi ga perlu menekan button." + ) except Exception as err: await q.message.edit(err) diff --git a/misskaty/plugins/auto_forwarder.py b/misskaty/plugins/auto_forwarder.py index c8b0c09d..86197975 100644 --- a/misskaty/plugins/auto_forwarder.py +++ b/misskaty/plugins/auto_forwarder.py @@ -1,6 +1,5 @@ # Code copy from https://github.com/AbirHasan2005/Forward-Client -import logging -from misskaty import user +from misskaty import user, LOGGER from pyrogram import filters from asyncio import sleep from pyrogram.types import Message @@ -76,14 +75,14 @@ async def ForwardMessage(client: user, msg: Message): await msg.copy(FORWARD_TO_CHAT_ID[i]) except FloodWait as e: await sleep(e.value) - logging.warning(f"#FloodWait: Stopped Forwarder for {e.x}s!") + LOGGER.warning(f"#FloodWait: Stopped Forwarder for {e.x}s!") await ForwardMessage(client, msg) except Exception as err: - logging.warning( + LOGGER.warning( f"#ERROR: {err}\n\nUnable to Forward Message to {str(FORWARD_TO_CHAT_ID[i])}, reason: {err}" ) except Exception as err: - logging.warning(f"#ERROR: {err}") + LOGGER.warning(f"#ERROR: {err}") @user.on_message((filters.text | filters.media) & filters.chat(FORWARD_FROM_CHAT_ID)) diff --git a/misskaty/plugins/banned.py b/misskaty/plugins/banned.py index 6c22eb8f..0b368afb 100644 --- a/misskaty/plugins/banned.py +++ b/misskaty/plugins/banned.py @@ -8,7 +8,9 @@ from misskaty import app async def banned_users(_, client, message: Message): - return (message.from_user is not None or not message.sender_chat) and message.from_user.id in temp.BANNED_USERS + return ( + message.from_user is not None or not message.sender_chat + ) and message.from_user.id in temp.BANNED_USERS banned_user = filters.create(banned_users) @@ -24,7 +26,9 @@ disabled_group = filters.create(disabled_chat) @app.on_message(filters.private & banned_user & filters.incoming) async def ban_reply(bot, message): ban = await db.get_ban_status(message.from_user.id) - await message.reply(f'Sorry Dude, You are Banned to use Me. \nBan Reason: {ban["ban_reason"]}') + await message.reply( + f'Sorry Dude, You are Banned to use Me. \nBan Reason: {ban["ban_reason"]}' + ) @app.on_message(filters.group & disabled_group & filters.incoming) @@ -32,7 +36,10 @@ async def grp_bd(bot, message): buttons = [[InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]] reply_markup = InlineKeyboardMarkup(buttons) vazha = await db.get_chat(message.chat.id) - k = await message.reply(text=f"CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..\nReason : {vazha['reason']}.", reply_markup=reply_markup) + k = await message.reply( + text=f"CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..\nReason : {vazha['reason']}.", + reply_markup=reply_markup, + ) try: await k.pin() except: diff --git a/misskaty/plugins/bypass.py b/misskaty/plugins/bypass.py index a8a08db2..809b0597 100644 --- a/misskaty/plugins/bypass.py +++ b/misskaty/plugins/bypass.py @@ -1,3 +1,10 @@ +""" + * @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 from misskaty.helper.http import http from misskaty import app diff --git a/misskaty/plugins/copy_forward.py b/misskaty/plugins/copy_forward.py index 2eeba8b8..6140b94c 100644 --- a/misskaty/plugins/copy_forward.py +++ b/misskaty/plugins/copy_forward.py @@ -12,10 +12,25 @@ async def copy(client, message): if not message.reply_to_message: return await message.reply("Silahkan balas pesan yang mau dicopy.") try: - await message.reply_to_message.copy(message.from_user.id, caption_entities=message.reply_to_message.entities, reply_markup=message.reply_to_message.reply_markup) + await message.reply_to_message.copy( + message.from_user.id, + caption_entities=message.reply_to_message.entities, + reply_markup=message.reply_to_message.reply_markup, + ) return await message.reply_text("Pesan berhasil dikirim..") except UserIsBlocked: - return await message.reply("Silahkan PM Saya untuk mengcopy pesan ke chat pribadi..", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="πŸ’¬ Chat Aku Yahh", url="https://t.me/MissKatyRoBot")]])) + return await message.reply( + "Silahkan PM Saya untuk mengcopy pesan ke chat pribadi..", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="πŸ’¬ Chat Aku Yahh", url="https://t.me/MissKatyRoBot" + ) + ] + ] + ), + ) except Exception as e: return await message.reply(f"ERROR: {str(e)}") elif message.reply_to_message: @@ -31,7 +46,11 @@ async def copy(client, message): and message.from_user.id != 2024984460 ): return await message.reply_text("πŸ¦‰πŸ¦‰πŸ¦‰") - await message.reply_to_message.copy(idtujuan, caption_entities=message.reply_to_message.entities, reply_markup=message.reply_to_message.reply_markup) + await message.reply_to_message.copy( + idtujuan, + caption_entities=message.reply_to_message.entities, + reply_markup=message.reply_to_message.reply_markup, + ) return await message.reply_text("Pesan berhasil dikirim..") except UserNotParticipant: return await message.reply("Command ini hanya untuk admin YMoviezNew") @@ -51,7 +70,18 @@ async def forward(client, message): await message.reply_to_message.forward(message.from_user.id) return await message.reply_text("Pesan berhasil dikirim..") except UserIsBlocked: - return await message.reply("Silahkan PM Saya untuk memforward pesan ke chat pribadi..", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="πŸ’¬ Chat Aku Yahh", url="https://t.me/MissKatyRoBot")]])) + return await message.reply( + "Silahkan PM Saya untuk memforward pesan ke chat pribadi..", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="πŸ’¬ Chat Aku Yahh", url="https://t.me/MissKatyRoBot" + ) + ] + ] + ), + ) except Exception as e: return await message.reply(f"ERROR: {str(e)}") elif message.reply_to_message: diff --git a/misskaty/plugins/download_upload.py b/misskaty/plugins/download_upload.py index bb7f3186..34edc8aa 100644 --- a/misskaty/plugins/download_upload.py +++ b/misskaty/plugins/download_upload.py @@ -2,12 +2,11 @@ import time import asyncio import math import os -import logging import aiohttp import json from misskaty.helper.http import http from bs4 import BeautifulSoup -from misskaty import app +from misskaty import app, LOGGER from pySmartDL import SmartDL from datetime import datetime from misskaty.core.decorator.errors import capture_err @@ -130,7 +129,7 @@ async def download(client, message): display_message = current_message await asyncio.sleep(10) except Exception as e: - logging.info(str(e)) + LOGGER.info(str(e)) if os.path.exists(download_file_path): end_t = datetime.now() ms = (end_t - start_t).seconds diff --git a/misskaty/plugins/filter_request.py b/misskaty/plugins/filter_request.py index 656ac802..57d65311 100644 --- a/misskaty/plugins/filter_request.py +++ b/misskaty/plugins/filter_request.py @@ -17,20 +17,50 @@ async def start(_, message): await message.reply_text(text=f"Wa'alaikumsalam {message.from_user.mention} πŸ˜‡") -@app.on_message(filters.regex(r"#request|#req", re.I) & (filters.text | filters.photo) & filters.chat(-1001255283935) & ~filters.channel) +@app.on_message( + filters.regex(r"#request|#req", re.I) + & (filters.text | filters.photo) + & filters.chat(-1001255283935) + & ~filters.channel +) @capture_err async def request_user(client, message): if message.sender_chat: - return await message.reply(f"{message.from_user.mention} mohon gunakan akun asli saat request.") + return await message.reply( + f"{message.from_user.mention} mohon gunakan akun asli saat request." + ) is_in_gap, sleep_time = await check_time_gap(message.from_user.id) if is_in_gap: return await message.reply("Sabar dikit napa.. πŸ™„") markup = InlineKeyboardMarkup( [ - [InlineKeyboardButton(text="πŸ’¬ Lihat Pesan", url=f"https://t.me/c/1255283935/{message.id}")], - [InlineKeyboardButton(text="🚫 Tolak", callback_data=f"rejectreq_{message.id}_{message.chat.id}"), InlineKeyboardButton(text="βœ… Done", callback_data=f"donereq_{message.id}_{message.chat.id}")], - [InlineKeyboardButton(text="⚠️ Tidak Tersedia", callback_data=f"unavailablereq_{message.id}_{message.chat.id}")], - [InlineKeyboardButton(text="πŸ” Sudah Ada", callback_data=f"dahada_{message.id}_{message.chat.id}")], + [ + InlineKeyboardButton( + text="πŸ’¬ Lihat Pesan", url=f"https://t.me/c/1255283935/{message.id}" + ) + ], + [ + InlineKeyboardButton( + text="🚫 Tolak", + callback_data=f"rejectreq_{message.id}_{message.chat.id}", + ), + InlineKeyboardButton( + text="βœ… Done", + callback_data=f"donereq_{message.id}_{message.chat.id}", + ), + ], + [ + InlineKeyboardButton( + text="⚠️ Tidak Tersedia", + callback_data=f"unavailablereq_{message.id}_{message.chat.id}", + ) + ], + [ + InlineKeyboardButton( + text="πŸ” Sudah Ada", + callback_data=f"dahada_{message.id}_{message.chat.id}", + ) + ], ] ) try: @@ -40,16 +70,47 @@ async def request_user(client, message): else: REQUEST_DB[user_id] = 1 if REQUEST_DB[user_id] > 3: - return await message.reply(f"Mohon maaf {message.from_user.mention}, maksimal request hanya 3x perhari. Kalo mau tambah 5k per request 😝😝.") + return await message.reply( + f"Mohon maaf {message.from_user.mention}, maksimal request hanya 3x perhari. Kalo mau tambah 5k per request 😝😝." + ) if message.text: - forward = await client.send_message(-1001575525902, f"Request by {message.from_user.first_name} (#id{message.from_user.id})\n\n{message.text}", reply_markup=markup) - markup2 = InlineKeyboardMarkup([[InlineKeyboardButton(text="⏳ Cek Status Request", url=f"https://t.me/c/1575525902/{forward.id}")]]) + forward = await client.send_message( + -1001575525902, + f"Request by {message.from_user.first_name} (#id{message.from_user.id})\n\n{message.text}", + reply_markup=markup, + ) + markup2 = InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="⏳ Cek Status Request", + url=f"https://t.me/c/1575525902/{forward.id}", + ) + ] + ] + ) if message.photo: forward = await client.send_photo( - -1001575525902, message.photo.file_id, caption=f"Request by {message.from_user.first_name} (#id{message.from_user.id})\n\n{message.caption}", reply_markup=markup + -1001575525902, + message.photo.file_id, + caption=f"Request by {message.from_user.first_name} (#id{message.from_user.id})\n\n{message.caption}", + reply_markup=markup, ) - markup2 = InlineKeyboardMarkup([[InlineKeyboardButton(text="⏳ Cek Status Request", url=f"https://t.me/c/1575525902/{forward.id}")]]) - await message.reply_text(text=f"Hai {message.from_user.mention}, request kamu sudah dikirim yaa. Harap bersabar mungkin admin juga punya kesibukan lain.\n\nSisa Request: {3 - REQUEST_DB[user_id]}x", quote=True, reply_markup=markup2) + markup2 = InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="⏳ Cek Status Request", + url=f"https://t.me/c/1575525902/{forward.id}", + ) + ] + ] + ) + await message.reply_text( + text=f"Hai {message.from_user.mention}, request kamu sudah dikirim yaa. Harap bersabar mungkin admin juga punya kesibukan lain.\n\nSisa Request: {3 - REQUEST_DB[user_id]}x", + quote=True, + reply_markup=markup2, + ) except: pass @@ -78,7 +139,10 @@ async def start(_, message): async def _callbackreq(c, q): try: user = await c.get_chat_member(-1001201566570, q.from_user.id) - if user.status in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]: + if user.status in [ + enums.ChatMemberStatus.ADMINISTRATOR, + enums.ChatMemberStatus.OWNER, + ]: i, msg_id, chat_id = q.data.split("_") await c.send_message( chat_id=chat_id, @@ -87,23 +151,54 @@ async def _callbackreq(c, q): ) if q.message.caption: - await q.message.edit_text(f"COMPLETED\n\n{q.message.caption}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="βœ… Request Completed", callback_data="reqcompl")]])) + await q.message.edit_text( + f"COMPLETED\n\n{q.message.caption}", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="βœ… Request Completed", callback_data="reqcompl" + ) + ] + ] + ), + ) else: - await q.message.edit_text(f"COMPLETED\n\n{q.message.text}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="βœ… Request Completed", callback_data="reqcompl")]])) + await q.message.edit_text( + f"COMPLETED\n\n{q.message.text}", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="βœ… Request Completed", callback_data="reqcompl" + ) + ] + ] + ), + ) await q.answer("Request berhasil diselesaikan βœ…") else: await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True) except UserNotParticipant: - return await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10) + return await q.answer( + "Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10 + ) except PeerIdInvalid: - return await q.answer("Silahkan kirim pesan digrup supaya bot bisa merespon.", show_alert=True, cache_time=10) + return await q.answer( + "Silahkan kirim pesan digrup supaya bot bisa merespon.", + show_alert=True, + cache_time=10, + ) @app.on_callback_query(filters.regex(r"^dahada")) async def _callbackreqada(c, q): try: user = await c.get_chat_member(-1001201566570, q.from_user.id) - if user.status in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]: + if user.status in [ + enums.ChatMemberStatus.ADMINISTRATOR, + enums.ChatMemberStatus.OWNER, + ]: i, msg_id, chat_id = q.data.split("_") await c.send_message( chat_id=chat_id, @@ -112,23 +207,56 @@ async def _callbackreqada(c, q): ) if q.message.caption: - await q.message.edit_text(f"#AlreadyAvailable\n\n{q.message.caption}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="πŸ” Request Sudah Ada", callback_data="reqavailable")]])) + await q.message.edit_text( + f"#AlreadyAvailable\n\n{q.message.caption}", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="πŸ” Request Sudah Ada", + callback_data="reqavailable", + ) + ] + ] + ), + ) else: - await q.message.edit_text(f"Already Available\n\n{q.message.text}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="πŸ” Request Sudah Ada", callback_data="reqavailable")]])) + await q.message.edit_text( + f"Already Available\n\n{q.message.text}", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="πŸ” Request Sudah Ada", + callback_data="reqavailable", + ) + ] + ] + ), + ) await q.answer("Done βœ”οΈ") else: await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True) except UserNotParticipant: - return await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10) + return await q.answer( + "Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10 + ) except PeerIdInvalid: - return await q.answer("Silahkan kirim pesan digrup supaya bot bisa merespon.", show_alert=True, cache_time=10) + return await q.answer( + "Silahkan kirim pesan digrup supaya bot bisa merespon.", + show_alert=True, + cache_time=10, + ) @app.on_callback_query(filters.regex(r"^rejectreq")) async def _callbackreject(c, q): try: user = await c.get_chat_member(-1001201566570, q.from_user.id) - if user.status in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]: + if user.status in [ + enums.ChatMemberStatus.ADMINISTRATOR, + enums.ChatMemberStatus.OWNER, + ]: i, msg_id, chat_id = q.data.split("_") await c.send_message( chat_id=chat_id, @@ -137,23 +265,54 @@ async def _callbackreject(c, q): ) if q.message.caption: - await q.message.edit_text(f"REJECTED\n\n{q.message.caption}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="🚫 Request Rejected", callback_data="reqreject")]])) + await q.message.edit_text( + f"REJECTED\n\n{q.message.caption}", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="🚫 Request Rejected", callback_data="reqreject" + ) + ] + ] + ), + ) else: - await q.message.edit_text(f"REJECTED\n\n{q.message.text}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="🚫 Request Rejected", callback_data="reqreject")]])) + await q.message.edit_text( + f"REJECTED\n\n{q.message.text}", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="🚫 Request Rejected", callback_data="reqreject" + ) + ] + ] + ), + ) await q.answer("Request berhasil ditolak 🚫") else: await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True) except UserNotParticipant: - await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10) + await q.answer( + "Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10 + ) except PeerIdInvalid: - return await q.answer("Silahkan kirim pesan digrup supaya bot bisa merespon.", show_alert=True, cache_time=10) + return await q.answer( + "Silahkan kirim pesan digrup supaya bot bisa merespon.", + show_alert=True, + cache_time=10, + ) @app.on_callback_query(filters.regex(r"^unavailablereq")) async def _callbackunav(c, q): try: user = await c.get_chat_member(-1001201566570, q.from_user.id) - if user.status in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]: + if user.status in [ + enums.ChatMemberStatus.ADMINISTRATOR, + enums.ChatMemberStatus.OWNER, + ]: i, msg_id, chat_id = q.data.split("_") await c.send_message( chat_id=chat_id, @@ -162,36 +321,86 @@ async def _callbackunav(c, q): ) if q.message.caption: - await q.message.edit_text(f"UNAVAILABLE\n\n{q.message.caption}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="⚠️ Request Unavailable", callback_data="requnav")]])) + await q.message.edit_text( + f"UNAVAILABLE\n\n{q.message.caption}", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="⚠️ Request Unavailable", + callback_data="requnav", + ) + ] + ] + ), + ) else: - await q.message.edit_text(f"UNAVAILABLE\n\n{q.message.text}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="⚠️ Request Unavailable", callback_data="requnav")]])) - await q.answer("Request tidak tersedia, mungkin belum rilis atau memang tidak tersedia versi digital.") + await q.message.edit_text( + f"UNAVAILABLE\n\n{q.message.text}", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="⚠️ Request Unavailable", + callback_data="requnav", + ) + ] + ] + ), + ) + await q.answer( + "Request tidak tersedia, mungkin belum rilis atau memang tidak tersedia versi digital." + ) else: - await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=1000) + await q.answer( + "Apa motivasi kamu menekan tombol ini?", + show_alert=True, + cache_time=1000, + ) except UserNotParticipant: - await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10) + await q.answer( + "Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10 + ) except PeerIdInvalid: - return await q.answer("Silahkan kirim pesan digrup supaya bot bisa merespon.", show_alert=True, cache_time=10) + return await q.answer( + "Silahkan kirim pesan digrup supaya bot bisa merespon.", + show_alert=True, + cache_time=10, + ) @app.on_callback_query(filters.regex(r"^reqcompl$")) async def _callbackaft_done(c, q): - await q.answer("Request ini sudah terselesaikan πŸ₯³, silahkan cek di channel atau grup yaa..", show_alert=True, cache_time=1000) + await q.answer( + "Request ini sudah terselesaikan πŸ₯³, silahkan cek di channel atau grup yaa..", + show_alert=True, + cache_time=1000, + ) @app.on_callback_query(filters.regex(r"^reqreject$")) async def _callbackaft_rej(c, q): - await q.answer("Request ini ditolak πŸ’”, silahkan cek rules grup yaa.", show_alert=True, cache_time=1000) + await q.answer( + "Request ini ditolak πŸ’”, silahkan cek rules grup yaa.", + show_alert=True, + cache_time=1000, + ) @app.on_callback_query(filters.regex(r"^requnav$")) async def _callbackaft_unav(c, q): - await q.answer("Request ini tidak tersedia ☹️, mungkin filmnya belum rilis atau memang tidak tersedia versi digital.", show_alert=True, cache_time=1000) + await q.answer( + "Request ini tidak tersedia ☹️, mungkin filmnya belum rilis atau memang tidak tersedia versi digital.", + show_alert=True, + cache_time=1000, + ) @app.on_callback_query(filters.regex(r"^reqavailable$")) async def _callbackaft_dahada(c, q): - await q.answer("Request ini sudah ada, silahkan cari πŸ” di channelnya yaa πŸ˜‰..", show_alert=True) + await q.answer( + "Request ini sudah ada, silahkan cari πŸ” di channelnya yaa πŸ˜‰..", show_alert=True + ) scheduler = AsyncIOScheduler(timezone="Asia/Jakarta") diff --git a/misskaty/plugins/genss.py b/misskaty/plugins/genss.py index 5fed89f0..bd37a814 100644 --- a/misskaty/plugins/genss.py +++ b/misskaty/plugins/genss.py @@ -1,17 +1,16 @@ -# the logging things -import logging - -logging.basicConfig( - level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" -) -logger = logging.getLogger(__name__) - +""" + * @author yasir + * @date 2022-12-01 09:12:27 + * @lastModified 2022-12-01 09:32:31 + * @projectName MissKatyPyro + * Copyright @YasirPedia All rights reserved +""" import os, time, traceback from asyncio import sleep, gather from shutil import rmtree from pyrogram import filters, enums from pyrogram.errors import FloodWait -from misskaty import app +from misskaty import app, LOGGER from misskaty.helper.ffmpeg_helper import take_ss, genss_link from misskaty.vars import COMMAND_HANDLER from misskaty.helper.pyro_progress import progress_for_pyrogram diff --git a/misskaty/plugins/grup_tools.py b/misskaty/plugins/grup_tools.py index b0a9c028..ff8337ec 100644 --- a/misskaty/plugins/grup_tools.py +++ b/misskaty/plugins/grup_tools.py @@ -1,12 +1,11 @@ from datetime import datetime, timedelta import time import os -import logging from misskaty.helper.http import http from pyrogram import enums, filters from pyrogram.types import ChatMemberUpdated, InlineKeyboardButton, InlineKeyboardMarkup from pyrogram.errors import ChatSendMediaForbidden, MessageTooLong, RPCError, SlowmodeWait -from misskaty import app +from misskaty import app, LOGGER from misskaty.core.decorator.errors import capture_err, asyncify from PIL import Image, ImageChops, ImageDraw, ImageFont import textwrap @@ -15,9 +14,6 @@ from utils import temp from pyrogram.errors import ChatAdminRequired from misskaty.vars import SUDO, LOG_CHANNEL, SUPPORT_CHAT, COMMAND_HANDLER -logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s") -LOGGER = logging.getLogger(__name__) - def circle(pfp, size=(215, 215)): pfp = pfp.resize(size, Image.ANTIALIAS).convert("RGBA") diff --git a/misskaty/plugins/json.py b/misskaty/plugins/json.py index 43d791fa..9cff43d7 100644 --- a/misskaty/plugins/json.py +++ b/misskaty/plugins/json.py @@ -1,3 +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 +""" + import os from pyrogram import filters from misskaty import app diff --git a/misskaty/plugins/mediainfo.py b/misskaty/plugins/mediainfo.py index 7c172b8d..fd772c6b 100644 --- a/misskaty/plugins/mediainfo.py +++ b/misskaty/plugins/mediainfo.py @@ -1,3 +1,10 @@ +""" + * @author yasir + * @date 2022-12-01 09:12:27 + * @lastModified 2022-12-01 09:32:31 + * @projectName MissKatyPyro + * Copyright @YasirPedia All rights reserved +""" import io from os import remove as osremove import time @@ -14,11 +21,15 @@ from misskaty.helper.pyro_progress import ( ) -@app.on_message(filters.command(["mediainfo", "mediainfo@MissKatyRoBot"], COMMAND_HANDLER)) +@app.on_message( + filters.command(["mediainfo", "mediainfo@MissKatyRoBot"], COMMAND_HANDLER) +) @capture_err async def mediainfo(client, message): if message.reply_to_message and message.reply_to_message.media: - process = await message.reply_text("`Sedang memproses, lama waktu tergantung ukuran file kamu...`", quote=True) + process = await message.reply_text( + "`Sedang memproses, lama waktu tergantung ukuran file kamu...`", quote=True + ) file_info = get_file_id(message.reply_to_message) if file_info is None: await process.edit_text("Balas ke format media yang valid") @@ -54,14 +65,22 @@ async def mediainfo(client, message): try: link = message.text.split(" ", maxsplit=1)[1] if link.startswith("https://file.yasirweb.my.id"): - link = link.replace("https://file.yasirweb.my.id", "https://file.yasiraris.workers.dev") + link = link.replace( + "https://file.yasirweb.my.id", "https://file.yasiraris.workers.dev" + ) if link.startswith("https://link.yasirweb.my.id"): - link = link.replace("https://link.yasirweb.my.id", "https://yasirrobot.herokuapp.com") + link = link.replace( + "https://link.yasirweb.my.id", "https://yasirrobot.herokuapp.com" + ) process = await message.reply_text("`Mohon tunggu sejenak...`") try: - output = subprocess.check_output(["mediainfo", f"{link}"]).decode("utf-8") + output = subprocess.check_output(["mediainfo", f"{link}"]).decode( + "utf-8" + ) except Exception: - return await process.edit("Sepertinya link yang kamu kirim tidak valid, pastikan direct link dan bisa di download.") + return await process.edit( + "Sepertinya link yang kamu kirim tidak valid, pastikan direct link dan bisa di download." + ) title = "MissKaty Bot Mediainfo" body_text = f""" @@ -72,10 +91,18 @@ async def mediainfo(client, message): # response = await http.post(siteurl, data={"content": output, "extension": 'txt'} ) # response = response.json() # spacebin = "https://spaceb.in/"+response['payload']['id'] - markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="πŸ’¬ Telegraph", url=tgraph)]]) + markup = InlineKeyboardMarkup( + [[InlineKeyboardButton(text="πŸ’¬ Telegraph", url=tgraph)]] + ) with io.BytesIO(str.encode(output)) as out_file: out_file.name = "MissKaty_Mediainfo.txt" - await message.reply_document(out_file, caption=f"Hasil mediainfo anda..\n\nRequest by: {message.from_user.mention}", reply_markup=markup) + await message.reply_document( + out_file, + caption=f"Hasil mediainfo anda..\n\nRequest by: {message.from_user.mention}", + reply_markup=markup, + ) await process.delete() except IndexError: - return await message.reply_text("Gunakan command /mediainfo [link], atau reply telegram media dengan /mediainfo.") + return await message.reply_text( + "Gunakan command /mediainfo [link], atau reply telegram media dengan /mediainfo." + ) diff --git a/misskaty/plugins/misc_tools.py b/misskaty/plugins/misc_tools.py index fe80d9cc..342ac68c 100644 --- a/misskaty/plugins/misc_tools.py +++ b/misskaty/plugins/misc_tools.py @@ -6,7 +6,14 @@ import traceback from pyrogram import Client, filters from deep_translator import GoogleTranslator from gtts import gTTS -from pyrogram.errors import MediaEmpty, MessageNotModified, PhotoInvalidDimensions, UserNotParticipant, WebpageMediaEmpty, MessageTooLong +from pyrogram.errors import ( + MediaEmpty, + MessageNotModified, + PhotoInvalidDimensions, + UserNotParticipant, + WebpageMediaEmpty, + MessageTooLong, +) from misskaty.vars import COMMAND_HANDLER from utils import extract_user, get_file_id, demoji import time @@ -16,11 +23,7 @@ from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQ from misskaty.core.decorator.errors import capture_err from misskaty.helper.tools import rentry, GENRES_EMOJI from misskaty.helper.http import http -from misskaty import app -import logging - -logger = logging.getLogger(__name__) -logger.setLevel(logging.ERROR) +from misskaty import app, LOGGER __MODULE__ = "Misc" __HELP__ = """ @@ -46,12 +49,20 @@ def remove_html_tags(text): async def stackoverflow(client, message): if len(message.command) == 1: return await message.reply("Give a query to search in StackOverflow!") - r = (await http.get(f"https://api.stackexchange.com/2.3/search/excerpts?order=asc&sort=relevance&q={message.command[1]}&accepted=True&migrated=FalseΒ¬ice=False&wiki=False&site=stackoverflow")).json() + r = ( + await http.get( + f"https://api.stackexchange.com/2.3/search/excerpts?order=asc&sort=relevance&q={message.command[1]}&accepted=True&migrated=FalseΒ¬ice=False&wiki=False&site=stackoverflow" + ) + ).json() hasil = "" for count, data in enumerate(r["items"], start=1): question = data["question_id"] title = data["title"] - snippet = remove_html_tags(data["excerpt"])[:80].replace("\n", "").replace(" ", "") if len(remove_html_tags(data["excerpt"])) > 80 else remove_html_tags(data["excerpt"]).replace("\n", "").replace(" ", "") + snippet = ( + remove_html_tags(data["excerpt"])[:80].replace("\n", "").replace(" ", "") + if len(remove_html_tags(data["excerpt"])) > 80 + else remove_html_tags(data["excerpt"]).replace("\n", "").replace(" ", "") + ) hasil += f"{count}. {title}\n{snippet}\n" try: await message.reply(hasil) @@ -70,8 +81,14 @@ async def gsearch(client, message): query = message.text.split(" ", maxsplit=1)[1] msg = await message.reply_text(f"**Googling** for `{query}` ...") try: - headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/61.0.3163.100 Safari/537.36"} - html = await http.get(f"https://www.google.com/search?q={query}&gl=id&hl=id&num=17", headers=headers) + headers = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/61.0.3163.100 Safari/537.36" + } + html = await http.get( + f"https://www.google.com/search?q={query}&gl=id&hl=id&num=17", + headers=headers, + ) soup = BeautifulSoup(html.text, "lxml") # collect data @@ -96,17 +113,24 @@ async def gsearch(client, message): arr = json.dumps(data, indent=2, ensure_ascii=False) parse = json.loads(arr) total = len(parse) - res = "".join(f"{i['title']}\n{i['snippet']}\n\n" for i in parse) + res = "".join( + f"{i['title']}\n{i['snippet']}\n\n" for i in parse + ) except Exception: exc = traceback.format_exc() return await msg.edit(exc) - await msg.edit(text=f"Ada {total} Hasil Pencarian dari {query}:\n{res}Scraped by @MissKatyRoBot", disable_web_page_preview=True) + await msg.edit( + text=f"Ada {total} Hasil Pencarian dari {query}:\n{res}Scraped by @MissKatyRoBot", + disable_web_page_preview=True, + ) @app.on_message(filters.command(["tr", "trans", "translate"], COMMAND_HANDLER)) @capture_err async def translate(client, message): - if message.reply_to_message and (message.reply_to_message.text or message.reply_to_message.caption): + if message.reply_to_message and ( + message.reply_to_message.text or message.reply_to_message.caption + ): target_lang = "id" if len(message.command) == 1 else message.text.split()[1] text = message.reply_to_message.text or message.reply_to_message.caption else: @@ -118,20 +142,28 @@ async def translate(client, message): text = message.text.split(None, 2)[2] msg = await message.reply("Menerjemahkan...") try: - tekstr = (await http.get(f"https://script.google.com/macros/s/AKfycbyhNk6uVgrtJLEFRUT6y5B2pxETQugCZ9pKvu01-bE1gKkDRsw/exec?q={text}&target={target_lang}")).json()["text"] + tekstr = ( + await http.get( + f"https://script.google.com/macros/s/AKfycbyhNk6uVgrtJLEFRUT6y5B2pxETQugCZ9pKvu01-bE1gKkDRsw/exec?q={text}&target={target_lang}" + ) + ).json()["text"] except Exception as err: return await msg.edit(f"Error: {str(err)}") try: await msg.edit(f"{tekstr}") except MessageTooLong: url = await rentry(tekstr.text) - await msg.edit(f"Your translated text pasted to rentry because has long text:\n{url}") + await msg.edit( + f"Your translated text pasted to rentry because has long text:\n{url}" + ) @app.on_message(filters.command(["tts"], COMMAND_HANDLER)) @capture_err async def tts(_, message): - if message.reply_to_message and (message.reply_to_message.text or message.reply_to_message.caption): + if message.reply_to_message and ( + message.reply_to_message.text or message.reply_to_message.caption + ): if len(message.text.split()) == 1: target_lang = "id" else: @@ -160,13 +192,18 @@ async def tts(_, message): pass -@app.on_message(filters.command(["tosticker", "tosticker@MissKatyRoBot"], COMMAND_HANDLER)) +@app.on_message( + filters.command(["tosticker", "tosticker@MissKatyRoBot"], COMMAND_HANDLER) +) @capture_err async def tostick(client, message): try: if not message.reply_to_message or not message.reply_to_message.photo: return await message.reply_text("Reply ke foto untuk mengubah ke sticker") - sticker = await client.download_media(message.reply_to_message.photo.file_id, f"tostick_{message.from_user.id}.webp") + sticker = await client.download_media( + message.reply_to_message.photo.file_id, + f"tostick_{message.from_user.id}.webp", + ) await message.reply_sticker(sticker) os.remove(sticker) except Exception as e: @@ -180,9 +217,16 @@ async def topho(client, message): if not message.reply_to_message or not message.reply_to_message.sticker: return await message.reply_text("Reply ke sticker untuk mengubah ke foto") if message.reply_to_message.sticker.is_animated: - return await message.reply_text("Ini sticker animasi, command ini hanya untuk sticker biasa.") - photo = await client.download_media(message.reply_to_message.sticker.file_id, f"tostick_{message.from_user.id}.jpg") - await message.reply_photo(photo=photo, caption="Sticker -> Image\n@MissKatyRoBot") + return await message.reply_text( + "Ini sticker animasi, command ini hanya untuk sticker biasa." + ) + photo = await client.download_media( + message.reply_to_message.sticker.file_id, + f"tostick_{message.from_user.id}.jpg", + ) + await message.reply_photo( + photo=photo, caption="Sticker -> Image\n@MissKatyRoBot" + ) os.remove(photo) except Exception as e: @@ -198,7 +242,10 @@ async def showid(client, message): last = message.from_user.last_name or "" username = message.from_user.username dc_id = message.from_user.dc_id or "" - await message.reply_text(f"➲ First Name: {first}\n➲ Last Name: {last}\n➲ Username: {username}\n➲ Telegram ID: {user_id}\n➲ Data Centre: {dc_id}", quote=True) + await message.reply_text( + f"➲ First Name: {first}\n➲ Last Name: {last}\n➲ Username: {username}\n➲ Telegram ID: {user_id}\n➲ Data Centre: {dc_id}", + quote=True, + ) elif chat_type in ["group", "supergroup"]: _id = "" @@ -212,10 +259,16 @@ async def showid(client, message): ) file_info = get_file_id(message.reply_to_message) else: - _id += "➲ User ID: " f"{message.from_user.id if message.from_user else 'Anonymous'}\n" + _id += ( + "➲ User ID: " + f"{message.from_user.id if message.from_user else 'Anonymous'}\n" + ) file_info = get_file_id(message) if file_info: - _id += f"{file_info.message_type}: " f"{file_info.file_id}\n" + _id += ( + f"{file_info.message_type}: " + f"{file_info.file_id}\n" + ) await message.reply_text(_id, quote=True) @@ -246,24 +299,41 @@ async def who_is(client, message): if message.chat.type in (("supergroup", "channel")): try: chat_member_p = await message.chat.get_member(from_user.id) - joined_date = datetime.fromtimestamp(chat_member_p.joined_date or time.time()).strftime("%Y.%m.%d %H:%M:%S") - message_out_str += "➲Joined this Chat on: " f"{joined_date}" "\n" + joined_date = datetime.fromtimestamp( + chat_member_p.joined_date or time.time() + ).strftime("%Y.%m.%d %H:%M:%S") + message_out_str += ( + "➲Joined this Chat on: " f"{joined_date}" "\n" + ) except UserNotParticipant: pass if chat_photo := from_user.photo: local_user_photo = await client.download_media(message=chat_photo.big_file_id) buttons = [[InlineKeyboardButton("πŸ” Close", callback_data="close_data")]] reply_markup = InlineKeyboardMarkup(buttons) - await message.reply_photo(photo=local_user_photo, quote=True, reply_markup=reply_markup, caption=message_out_str, disable_notification=True) + await message.reply_photo( + photo=local_user_photo, + quote=True, + reply_markup=reply_markup, + caption=message_out_str, + disable_notification=True, + ) os.remove(local_user_photo) else: buttons = [[InlineKeyboardButton("πŸ” Close", callback_data="close_data")]] reply_markup = InlineKeyboardMarkup(buttons) - await message.reply_text(text=message_out_str, reply_markup=reply_markup, quote=True, disable_notification=True) + await message.reply_text( + text=message_out_str, + reply_markup=reply_markup, + quote=True, + disable_notification=True, + ) await status_message.delete() -headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.1.17 (KHTML, like Gecko) Version/7.1 Safari/537.85.10"} +headers = { + "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.1.17 (KHTML, like Gecko) Version/7.1 Safari/537.85.10" +} async def get_content(url): @@ -298,7 +368,10 @@ async def mdlsearch(client, message): ] for movie in res ] - await k.edit(f"Ditemukan {len(movies)} query dari {title}", reply_markup=InlineKeyboardMarkup(btn)) + await k.edit( + f"Ditemukan {len(movies)} query dari {title}", + reply_markup=InlineKeyboardMarkup(btn), + ) else: await message.reply("Berikan aku nama drama yang ingin dicari. πŸ€·πŸ»β€β™‚οΈ") @@ -313,16 +386,22 @@ async def mdl_callback(bot: Client, query: CallbackQuery): try: res = (await http.get(f"https://kuryana.vercel.app/id/{slug}")).json() result += f"Title: {res['data']['title']}\n" - result += f"AKA: {res['data']['others']['also_known_as']}\n\n" + result += ( + f"AKA: {res['data']['others']['also_known_as']}\n\n" + ) result += f"Rating: {res['data']['details']['score']}\n" result += f"Content Rating: {res['data']['details']['content_rating']}\n" result += f"Type: {res['data']['details']['type']}\n" - result += f"Country: {res['data']['details']['country']}\n" + result += ( + f"Country: {res['data']['details']['country']}\n" + ) if res["data"]["details"]["type"] == "Movie": result += f"Release Date: {res['data']['details']['release_date']}\n" elif res["data"]["details"]["type"] == "Drama": result += f"Episode: {res['data']['details']['episodes']}\n" - result += f"Aired: {res['data']['details']['aired']}\n" + result += ( + f"Aired: {res['data']['details']['aired']}\n" + ) try: result += f"Aired on: {res['data']['details']['aired_on']}\n" except: @@ -331,11 +410,17 @@ async def mdl_callback(bot: Client, query: CallbackQuery): result += f"Original Network: {res['data']['details']['original_network']}\n" except: pass - result += f"Duration: {res['data']['details']['duration']}\n" - result += f"Genre: {res['data']['others']['genres']}\n\n" + result += ( + f"Duration: {res['data']['details']['duration']}\n" + ) + result += ( + f"Genre: {res['data']['others']['genres']}\n\n" + ) result += f"Synopsis: {res['data']['synopsis']}\n" result += f"Tags: {res['data']['others']['tags']}\n" - btn = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Open MyDramaList", url=res["data"]["link"])]]) + btn = InlineKeyboardMarkup( + [[InlineKeyboardButton("🎬 Open MyDramaList", url=res["data"]["link"])]] + ) await query.message.edit_text(result, reply_markup=btn) except Exception as e: await query.message.edit_text(f"ERROR:\n{e}") @@ -349,9 +434,13 @@ async def mdl_callback(bot: Client, query: CallbackQuery): async def imdb1_search(client, message): BTN = [] if message.sender_chat: - return await message.reply("Mohon maaf fitur tidak tersedia untuk akun channel, harap ganti ke akun biasa..") + return await message.reply( + "Mohon maaf fitur tidak tersedia untuk akun channel, harap ganti ke akun biasa.." + ) if len(message.command) == 1: - return await message.reply("Berikan aku nama series atau movie yang ingin dicari. πŸ€·πŸ»β€β™‚οΈ", quote=True) + return await message.reply( + "Berikan aku nama series atau movie yang ingin dicari. πŸ€·πŸ»β€β™‚οΈ", quote=True + ) r, judul = message.text.split(None, 1) k = await message.reply("πŸ”Ž Sedang mencari di Database IMDB..", quote=True) msg = "" @@ -368,7 +457,11 @@ async def imdb1_search(client, message): type = movie.get("q").replace("feature", "movie").capitalize() movieID = re.findall(r"tt(\d+)", movie.get("id"))[0] msg += f"{count}. {title} {year} ~ {type}\n" - BTN.append(InlineKeyboardButton(text=count, callback_data=f"imdbid#{message.from_user.id}#{movieID}")) + BTN.append( + InlineKeyboardButton( + text=count, callback_data=f"imdbid#{message.from_user.id}#{movieID}" + ) + ) buttons.add(*BTN) await k.edit(msg, reply_markup=buttons) except Exception as err: @@ -386,12 +479,18 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery): url = f"https://www.imdb.com/title/tt{movie}/" resp = await get_content(url) sop = BeautifulSoup(resp, "lxml") - r_json = json.loads(sop.find("script", attrs={"type": "application/ld+json"}).contents[0]) + r_json = json.loads( + sop.find("script", attrs={"type": "application/ld+json"}).contents[0] + ) res_str = "" type = f"{r_json['@type']}" if r_json.get("@type") else "" if r_json.get("name"): try: - tahun = sop.select('ul[data-testid="hero-title-block__metadata"]')[0].find(class_="sc-8c396aa2-2 itZqyK").text + tahun = ( + sop.select('ul[data-testid="hero-title-block__metadata"]')[0] + .find(class_="sc-8c396aa2-2 itZqyK") + .text + ) except: tahun = "-" res_str += f"πŸ“Ή Judul: {r_json['name']} [{tahun}] ({type})\n" @@ -400,31 +499,63 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery): else: res_str += "\n" if sop.select('li[data-testid="title-techspec_runtime"]'): - durasi = sop.select('li[data-testid="title-techspec_runtime"]')[0].find(class_="ipc-metadata-list-item__content-container").text + durasi = ( + sop.select('li[data-testid="title-techspec_runtime"]')[0] + .find(class_="ipc-metadata-list-item__content-container") + .text + ) res_str += f"Durasi: {GoogleTranslator('auto', 'id').translate(durasi)}\n" if r_json.get("contentRating"): res_str += f"Kategori: {r_json['contentRating']} \n" if r_json.get("aggregateRating"): res_str += f"Peringkat: {r_json['aggregateRating']['ratingValue']}⭐️ dari {r_json['aggregateRating']['ratingCount']} pengguna \n" if sop.select('li[data-testid="title-details-releasedate"]'): - rilis = sop.select('li[data-testid="title-details-releasedate"]')[0].find(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link").text - rilis_url = sop.select('li[data-testid="title-details-releasedate"]')[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" + rilis = ( + sop.select('li[data-testid="title-details-releasedate"]')[0] + .find( + class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link" + ) + .text + ) + rilis_url = sop.select('li[data-testid="title-details-releasedate"]')[ + 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" + ) if r_json.get("genre"): - genre = "".join(f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, " if i in GENRES_EMOJI else f"#{i.replace('-', '_').replace(' ', '_')}, " for i in r_json["genre"]) + genre = "".join( + f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, " + if i in GENRES_EMOJI + else f"#{i.replace('-', '_').replace(' ', '_')}, " + for i in r_json["genre"] + ) genre = genre[:-2] res_str += f"Genre: {genre}\n" if sop.select('li[data-testid="title-details-origin"]'): country = "".join( f"{demoji(country.text)} #{country.text.replace(' ', '_').replace('-', '_')}, " - for country in sop.select('li[data-testid="title-details-origin"]')[0].findAll(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link") + for country in sop.select('li[data-testid="title-details-origin"]')[ + 0 + ].findAll( + class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link" + ) ) country = country[:-2] res_str += f"Negara: {country}\n" if sop.select('li[data-testid="title-details-languages"]'): language = "".join( - f"#{lang.text.replace(' ', '_').replace('-', '_')}, " for lang in sop.select('li[data-testid="title-details-languages"]')[0].findAll(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link") + f"#{lang.text.replace(' ', '_').replace('-', '_')}, " + for lang in sop.select('li[data-testid="title-details-languages"]')[ + 0 + ].findAll( + class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link" + ) ) language = language[:-2] res_str += f"Bahasa: {language}\n" @@ -455,7 +586,9 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery): actors = actors[:-2] res_str += f"Pemeran: {actors}\n\n" if r_json.get("description"): - summary = GoogleTranslator("auto", "id").translate(r_json.get("description")) + summary = GoogleTranslator("auto", "id").translate( + r_json.get("description") + ) res_str += f"πŸ“œ Plot: {summary}\n\n" if r_json.get("keywords"): keywords = r_json["keywords"].split(",") @@ -466,27 +599,66 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery): key_ = key_[:-2] res_str += f"πŸ”₯ Kata Kunci: {key_} \n" if sop.select('li[data-testid="award_information"]'): - awards = sop.select('li[data-testid="award_information"]')[0].find(class_="ipc-metadata-list-item__list-content-item").text + awards = ( + sop.select('li[data-testid="award_information"]')[0] + .find(class_="ipc-metadata-list-item__list-content-item") + .text + ) res_str += f"πŸ† Penghargaan: {GoogleTranslator('auto', 'id').translate(awards)}\n\n" else: res_str += "\n" res_str += "©️ IMDb by @MissKatyRoBot" if r_json.get("trailer"): trailer_url = r_json["trailer"]["url"] - markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}"), InlineKeyboardButton("▢️ Trailer", url=trailer_url)]]) + markup = InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + "🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}" + ), + InlineKeyboardButton("▢️ Trailer", url=trailer_url), + ] + ] + ) else: - markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}")]]) + markup = InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + "🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}" + ) + ] + ] + ) if thumb := r_json.get("image"): try: - await query.message.reply_photo(photo=thumb, quote=True, caption=res_str, reply_to_message_id=usr.id, reply_markup=markup) + await query.message.reply_photo( + photo=thumb, + quote=True, + caption=res_str, + reply_to_message_id=usr.id, + reply_markup=markup, + ) except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty): poster = thumb.replace(".jpg", "._V1_UX360.jpg") - await query.message.reply_photo(photo=poster, caption=res_str, reply_to_message_id=usr.id, reply_markup=markup) + await query.message.reply_photo( + photo=poster, + caption=res_str, + reply_to_message_id=usr.id, + reply_markup=markup, + ) except Exception: - await query.message.reply(res_str, reply_markup=markup, disable_web_page_preview=False, reply_to_message_id=usr.id) + await query.message.reply( + res_str, + reply_markup=markup, + disable_web_page_preview=False, + reply_to_message_id=usr.id, + ) await query.message.delete() else: - await query.message.edit(res_str, reply_markup=markup, disable_web_page_preview=False) + await query.message.edit( + res_str, reply_markup=markup, disable_web_page_preview=False + ) await query.answer() except MessageNotModified: pass @@ -503,7 +675,10 @@ async def imdb_en_search(client, message): if message.sender_chat: return await message.reply("This feature not available for channel.") if len(message.command) == 1: - return await message.reply("Give movie name or series. Ex: /imdb_en soul. πŸ€·πŸ»β€β™‚οΈ", quote=True) + return await message.reply( + "Give movie name or series. Ex: /imdb_en soul. πŸ€·πŸ»β€β™‚οΈ", + quote=True, + ) r, title = message.text.split(None, 1) k = await message.reply("Searching Movie/Series in IMDB Database.. 😴", quote=True) msg = "" @@ -520,7 +695,11 @@ async def imdb_en_search(client, message): type = movie.get("qid").replace("feature", "movie").capitalize() movieID = re.findall(r"tt(\d+)", movie.get("id"))[0] msg += f"{count}. {titles} {year} ~ {type}\n" - BTN.append(InlineKeyboardButton(text=count, callback_data=f"imdben#{message.from_user.id}#{movieID}")) + BTN.append( + InlineKeyboardButton( + text=count, callback_data=f"imdben#{message.from_user.id}#{movieID}" + ) + ) buttons.add(*BTN) await k.edit(msg, reply_markup=buttons) except Exception as err: @@ -539,12 +718,18 @@ async def imdb_en_callback(bot: Client, query: CallbackQuery): url = f"https://www.imdb.com/title/tt{movie}/" resp = await get_content(url) sop = BeautifulSoup(resp, "lxml") - r_json = json.loads(sop.find("script", attrs={"type": "application/ld+json"}).contents[0]) + r_json = json.loads( + sop.find("script", attrs={"type": "application/ld+json"}).contents[0] + ) res_str = "" type = f"{r_json['@type']}" if r_json.get("@type") else "" if r_json.get("name"): try: - tahun = sop.select('ul[data-testid="hero-title-block__metadata"]')[0].find(class_="sc-8c396aa2-2 itZqyK").text + tahun = ( + sop.select('ul[data-testid="hero-title-block__metadata"]')[0] + .find(class_="sc-8c396aa2-2 itZqyK") + .text + ) except: tahun = "-" res_str += f"πŸ“Ή Title: {r_json['name']} [{tahun}] ({type})\n" @@ -553,31 +738,61 @@ async def imdb_en_callback(bot: Client, query: CallbackQuery): else: res_str += "\n" if sop.select('li[data-testid="title-techspec_runtime"]'): - durasi = sop.select('li[data-testid="title-techspec_runtime"]')[0].find(class_="ipc-metadata-list-item__content-container").text + durasi = ( + sop.select('li[data-testid="title-techspec_runtime"]')[0] + .find(class_="ipc-metadata-list-item__content-container") + .text + ) res_str += f"Duration: {durasi}\n" if r_json.get("contentRating"): res_str += f"Category: {r_json['contentRating']} \n" if r_json.get("aggregateRating"): res_str += f"Rating: {r_json['aggregateRating']['ratingValue']}⭐️ from {r_json['aggregateRating']['ratingCount']} user \n" if sop.select('li[data-testid="title-details-releasedate"]'): - rilis = sop.select('li[data-testid="title-details-releasedate"]')[0].find(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link").text - rilis_url = sop.select('li[data-testid="title-details-releasedate"]')[0].find(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link")["href"] + rilis = ( + sop.select('li[data-testid="title-details-releasedate"]')[0] + .find( + class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link" + ) + .text + ) + rilis_url = sop.select('li[data-testid="title-details-releasedate"]')[ + 0 + ].find( + class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link" + )[ + "href" + ] res_str += f"Release Data: {rilis}\n" if r_json.get("genre"): - genre = "".join(f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, " if i in GENRES_EMOJI else f"#{i.replace('-', '_').replace(' ', '_')}, " for i in r_json["genre"]) + genre = "".join( + f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, " + if i in GENRES_EMOJI + else f"#{i.replace('-', '_').replace(' ', '_')}, " + for i in r_json["genre"] + ) genre = genre[:-2] res_str += f"Genre: {genre}\n" if sop.select('li[data-testid="title-details-origin"]'): country = "".join( f"{demoji(country.text)} #{country.text.replace(' ', '_').replace('-', '_')}, " - for country in sop.select('li[data-testid="title-details-origin"]')[0].findAll(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link") + for country in sop.select('li[data-testid="title-details-origin"]')[ + 0 + ].findAll( + class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link" + ) ) country = country[:-2] res_str += f"Country: {country}\n" if sop.select('li[data-testid="title-details-languages"]'): language = "".join( - f"#{lang.text.replace(' ', '_').replace('-', '_')}, " for lang in sop.select('li[data-testid="title-details-languages"]')[0].findAll(class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link") + f"#{lang.text.replace(' ', '_').replace('-', '_')}, " + for lang in sop.select('li[data-testid="title-details-languages"]')[ + 0 + ].findAll( + class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link" + ) ) language = language[:-2] res_str += f"Language: {language}\n" @@ -618,27 +833,66 @@ async def imdb_en_callback(bot: Client, query: CallbackQuery): key_ = key_[:-2] res_str += f"πŸ”₯ Keywords: {key_} \n" if sop.select('li[data-testid="award_information"]'): - awards = sop.select('li[data-testid="award_information"]')[0].find(class_="ipc-metadata-list-item__list-content-item").text + awards = ( + sop.select('li[data-testid="award_information"]')[0] + .find(class_="ipc-metadata-list-item__list-content-item") + .text + ) res_str += f"πŸ† Awards: {awards}\n\n" else: res_str += "\n" res_str += "©️ IMDb by @MissKatyRoBot" if r_json.get("trailer"): trailer_url = r_json["trailer"]["url"] - markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}"), InlineKeyboardButton("▢️ Trailer", url=trailer_url)]]) + markup = InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + "🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}" + ), + InlineKeyboardButton("▢️ Trailer", url=trailer_url), + ] + ] + ) else: - markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}")]]) + markup = InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + "🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}" + ) + ] + ] + ) if thumb := r_json.get("image"): try: - await query.message.reply_photo(photo=thumb, quote=True, caption=res_str, reply_to_message_id=usr.id, reply_markup=markup) + await query.message.reply_photo( + photo=thumb, + quote=True, + caption=res_str, + reply_to_message_id=usr.id, + reply_markup=markup, + ) except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty): poster = thumb.replace(".jpg", "._V1_UX360.jpg") - await query.message.reply_photo(photo=poster, caption=res_str, reply_to_message_id=usr.id, reply_markup=markup) + await query.message.reply_photo( + photo=poster, + caption=res_str, + reply_to_message_id=usr.id, + reply_markup=markup, + ) except Exception: - await query.message.reply(res_str, reply_markup=markup, disable_web_page_preview=False, reply_to_message_id=usr.id) + await query.message.reply( + res_str, + reply_markup=markup, + disable_web_page_preview=False, + reply_to_message_id=usr.id, + ) await query.message.delete() else: - await query.message.edit(res_str, reply_markup=markup, disable_web_page_preview=False) + await query.message.edit( + res_str, reply_markup=markup, disable_web_page_preview=False + ) await query.answer() except Exception: exc = traceback.format_exc() diff --git a/misskaty/plugins/ocr.py b/misskaty/plugins/ocr.py index 893d3389..56300c68 100644 --- a/misskaty/plugins/ocr.py +++ b/misskaty/plugins/ocr.py @@ -1,3 +1,10 @@ +""" + * @author yasir + * @date 2022-12-01 09:12:27 + * @lastModified 2022-12-01 09:32:31 + * @projectName MissKatyPyro + * Copyright @YasirPedia All rights reserved +""" import os from pyrogram import filters from telegraph import upload_file @@ -28,7 +35,7 @@ async def ocr(_, message): req = ( await http.get( f"https://script.google.com/macros/s/AKfycbwURISN0wjazeJTMHTPAtxkrZTWTpsWIef5kxqVGoXqnrzdLdIQIfLO7jsR5OQ5GO16/exec?url={url}", - follow_redirects=True + follow_redirects=True, ) ).json() await msg.edit(f"Hasil OCR:\n{req['text']}") diff --git a/misskaty/plugins/paste.py b/misskaty/plugins/paste.py index 4385115a..104dfa13 100644 --- a/misskaty/plugins/paste.py +++ b/misskaty/plugins/paste.py @@ -1,3 +1,10 @@ +""" + * @author yasir + * @date 2022-12-01 09:12:27 + * @lastModified 2022-12-01 09:32:31 + * @projectName MissKatyPyro + * Copyright @YasirPedia All rights reserved +""" from os import remove from re import compile as compiles from misskaty.helper.http import http diff --git a/misskaty/plugins/scrapwebsite.py b/misskaty/plugins/scrapwebsite.py index 13bfff04..9b72bc53 100644 --- a/misskaty/plugins/scrapwebsite.py +++ b/misskaty/plugins/scrapwebsite.py @@ -1,3 +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 +""" + # This plugin to scrape from melongmovie, and lk21 from bs4 import BeautifulSoup import aiohttp diff --git a/misskaty/plugins/sub_extractor.py b/misskaty/plugins/sub_extractor.py index fed0e65b..37881df1 100644 --- a/misskaty/plugins/sub_extractor.py +++ b/misskaty/plugins/sub_extractor.py @@ -1,3 +1,10 @@ +""" + * @author yasir + * @date 2022-12-01 09:12:27 + * @lastModified 2022-12-01 09:32:31 + * @projectName MissKatyPyro + * Copyright @YasirPedia All rights reserved +""" from misskaty import app from pyrogram import filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup diff --git a/misskaty/plugins/ubot_plugin.py b/misskaty/plugins/ubot_plugin.py index 4a037a52..7f8debe0 100644 --- a/misskaty/plugins/ubot_plugin.py +++ b/misskaty/plugins/ubot_plugin.py @@ -1,3 +1,4 @@ +# Code in this plugin to learn basic userbot in pyrogram import os from pyrogram import enums, filters from pyrogram.types import ( diff --git a/misskaty/plugins/ytdl_download.py b/misskaty/plugins/ytdl_download.py index 04774454..2bf3c6e6 100644 --- a/misskaty/plugins/ytdl_download.py +++ b/misskaty/plugins/ytdl_download.py @@ -1,12 +1,5 @@ -""" - * @author yasir - * @date 2022-12-01 09:12:27 - * @lastModified 2022-12-01 09:32:31 - * @projectName MissKatyPyro - * Copyright @YasirPedia All rights reserved - """ -import os, logging, json, shutil, asyncio, time -from misskaty import app +import os, json, shutil, asyncio, time +from misskaty import app, LOGGER from PIL import Image from pyrogram import filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup @@ -20,11 +13,6 @@ from misskaty.plugins.dev import shell_exec from misskaty.core.decorator.errors import capture_err from misskaty.helper.pyro_progress import progress_for_pyrogram -logging.basicConfig( - level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" -) -LOGGER = logging.getLogger(__name__) - user_time = {} diff --git a/misskaty/vars.py b/misskaty/vars.py index 319f7cd8..ed099c8d 100644 --- a/misskaty/vars.py +++ b/misskaty/vars.py @@ -1,11 +1,9 @@ -import logging +from bot import LOGGER from os import environ from dotenv import load_dotenv load_dotenv("config.env", override=True) -LOGGER = logging.getLogger(__name__) - def getConfig(name: str): try: diff --git a/utils.py b/utils.py index 62e85627..17badac2 100644 --- a/utils.py +++ b/utils.py @@ -1,15 +1,17 @@ -import logging -from pyrogram.errors import FloodWait, InputUserDeactivated, PeerIdInvalid, UserIsBlocked +from pyrogram.errors import ( + FloodWait, + InputUserDeactivated, + PeerIdInvalid, + UserIsBlocked, +) import asyncio +from misskaty import LOGGER from pyrogram.types import Message from typing import Union import os import emoji from database.users_chats_db import db -logger = logging.getLogger(__name__) -logger.setLevel(logging.INFO) - BANNED = {} @@ -38,14 +40,14 @@ async def broadcast_messages(user_id, message): return await broadcast_messages(user_id, message) except InputUserDeactivated: await db.delete_user(int(user_id)) - logging.info(f"{user_id}-Removed from Database, since deleted account.") + LOGGER.info(f"{user_id}-Removed from Database, since deleted account.") return False, "Deleted" except UserIsBlocked: - logging.info(f"{user_id} -Blocked the bot.") + LOGGER.info(f"{user_id} -Blocked the bot.") return False, "Blocked" except PeerIdInvalid: await db.delete_user(int(user_id)) - logging.info(f"{user_id} - PeerIdInvalid") + LOGGER.info(f"{user_id} - PeerIdInvalid") return False, "Error" except Exception: return False, "Error" @@ -65,7 +67,16 @@ def get_size(size): def get_file_id(msg: Message): if msg.media: - for message_type in ("photo", "animation", "audio", "document", "video", "video_note", "voice", "sticker"): + for message_type in ( + "photo", + "animation", + "audio", + "document", + "video", + "video_note", + "voice", + "sticker", + ): if obj := getattr(msg, message_type): setattr(obj, "message_type", message_type) return obj