diff --git a/database/afk_db.py b/database/afk_db.py
index c44cc9f7..5a6062e5 100644
--- a/database/afk_db.py
+++ b/database/afk_db.py
@@ -47,9 +47,7 @@ async def is_afk(user_id: int) -> bool:
async def add_afk(user_id: int, mode):
- await usersdb.update_one(
- {"user_id": user_id}, {"$set": {"reason": mode}}, upsert=True
- )
+ await usersdb.update_one({"user_id": user_id}, {"$set": {"reason": mode}}, upsert=True)
async def remove_afk(user_id: int):
@@ -60,9 +58,4 @@ async def remove_afk(user_id: int):
async def get_afk_users() -> list:
users = usersdb.find({"user_id": {"$gt": 0}})
- if not users:
- return []
- users_list = []
- for user in await users.to_list(length=1000000000):
- users_list.append(user)
- return users_list
+ return list(await users.to_list(length=1000000000)) if users else []
diff --git a/database/filters_db.py b/database/filters_db.py
index d9d185bd..fba5983b 100644
--- a/database/filters_db.py
+++ b/database/filters_db.py
@@ -31,10 +31,7 @@ async def get_filter(chat_id: int, name: str) -> Union[bool, dict]:
async def get_filters_names(chat_id: int) -> List[str]:
- _filters = []
- for _filter in await _get_filters(chat_id):
- _filters.append(_filter)
- return _filters
+ return list(await _get_filters(chat_id))
async def save_filter(chat_id: int, name: str, _filter: dict):
diff --git a/database/imdb_db.py b/database/imdb_db.py
index 86dded73..90b840c6 100644
--- a/database/imdb_db.py
+++ b/database/imdb_db.py
@@ -9,9 +9,7 @@ async def is_imdbset(user_id: int) -> bool:
async def add_imdbset(user_id: int, lang):
- await imbd_db.update_one(
- {"user_id": user_id}, {"$set": {"lang": lang}}, upsert=True
- )
+ await imbd_db.update_one({"user_id": user_id}, {"$set": {"lang": lang}}, upsert=True)
async def remove_imdbset(user_id: int):
diff --git a/database/karma_db.py b/database/karma_db.py
index 6e4b0d6a..0ef04570 100644
--- a/database/karma_db.py
+++ b/database/karma_db.py
@@ -43,9 +43,7 @@ async def update_karma(chat_id: int, name: str, karma: dict):
name = name.lower().strip()
karmas = await get_karmas(chat_id)
karmas[name] = karma
- await karmadb.update_one(
- {"chat_id": chat_id}, {"$set": {"karma": karmas}}, upsert=True
- )
+ await karmadb.update_one({"chat_id": chat_id}, {"$set": {"karma": karmas}}, upsert=True)
async def is_karma_on(chat_id: int) -> bool:
diff --git a/database/notes_db.py b/database/notes_db.py
index 0e55ca7d..89761702 100644
--- a/database/notes_db.py
+++ b/database/notes_db.py
@@ -31,10 +31,7 @@ async def get_note(chat_id: int, name: str) -> Union[bool, dict]:
async def get_note_names(chat_id: int) -> List[str]:
- _notes = []
- for note in await _get_notes(chat_id):
- _notes.append(note)
- return _notes
+ return list(await _get_notes(chat_id))
async def save_note(chat_id: int, name: str, note: dict):
@@ -42,6 +39,4 @@ async def save_note(chat_id: int, name: str, note: dict):
_notes = await _get_notes(chat_id)
_notes[name] = note
- await notesdb.update_one(
- {"chat_id": chat_id}, {"$set": {"notes": _notes}}, upsert=True
- )
+ await notesdb.update_one({"chat_id": chat_id}, {"$set": {"notes": _notes}}, upsert=True)
diff --git a/database/users_chats_db.py b/database/users_chats_db.py
index b25aafac..8f686841 100644
--- a/database/users_chats_db.py
+++ b/database/users_chats_db.py
@@ -80,18 +80,14 @@ class Database:
is_disabled=False,
reason="",
)
- await self.grp.update_one(
- {"id": int(id)}, {"$set": {"chat_status": chat_status}}
- )
+ await self.grp.update_one({"id": int(id)}, {"$set": {"chat_status": chat_status}})
async def disable_chat(self, chat, reason="No Reason"):
chat_status = dict(
is_disabled=True,
reason=reason,
)
- await self.grp.update_one(
- {"id": int(chat)}, {"$set": {"chat_status": chat_status}}
- )
+ await self.grp.update_one({"id": int(chat)}, {"$set": {"chat_status": chat_status}})
async def total_chat_count(self):
return await self.grp.count_documents({})
diff --git a/database/warn_db.py b/database/warn_db.py
index 5d3daf5d..122cacf7 100644
--- a/database/warn_db.py
+++ b/database/warn_db.py
@@ -32,9 +32,7 @@ async def add_warn(chat_id: int, name: str, warn: dict):
warns = await get_warns(chat_id)
warns[name] = warn
- await warnsdb.update_one(
- {"chat_id": chat_id}, {"$set": {"warns": warns}}, upsert=True
- )
+ await warnsdb.update_one({"chat_id": chat_id}, {"$set": {"warns": warns}}, upsert=True)
async def remove_warns(chat_id: int, name: str) -> bool:
diff --git a/misskaty/core/decorator/permissions.py b/misskaty/core/decorator/permissions.py
index db00b78c..25c34c33 100644
--- a/misskaty/core/decorator/permissions.py
+++ b/misskaty/core/decorator/permissions.py
@@ -51,12 +51,7 @@ async def list_admins(chat_id: int):
admins_in_chat[chat_id] = {
"last_updated_at": time(),
- "data": [
- member.user.id
- async for member in app.get_chat_members(
- chat_id, filter=enums.ChatMembersFilter.ADMINISTRATORS
- )
- ],
+ "data": [member.user.id async for member in app.get_chat_members(chat_id, filter=enums.ChatMembersFilter.ADMINISTRATORS)],
}
return admins_in_chat[chat_id]["data"]
diff --git a/misskaty/core/keyboard.py b/misskaty/core/keyboard.py
index e80a1cc6..1736ff66 100644
--- a/misskaty/core/keyboard.py
+++ b/misskaty/core/keyboard.py
@@ -12,12 +12,7 @@ def keyboard(buttons_list, row_width: int = 2):
if theres, a url, it will make url button, else callback button
"""
buttons = InlineKeyboard(row_width=row_width)
- data = [
- Ikb(text=str(i[0]), url=str(i[1]))
- if is_url(i[1])
- else Ikb(text=str(i[0]), callback_data=str(i[1]))
- for i in buttons_list
- ]
+ data = [Ikb(text=str(i[0]), url=str(i[1])) if is_url(i[1]) else Ikb(text=str(i[0]), callback_data=str(i[1])) for i in buttons_list]
buttons.add(*data)
return buttons
diff --git a/misskaty/helper/ffmpeg_helper.py b/misskaty/helper/ffmpeg_helper.py
index 0695e2d8..76bd2dd0 100644
--- a/misskaty/helper/ffmpeg_helper.py
+++ b/misskaty/helper/ffmpeg_helper.py
@@ -33,9 +33,7 @@ async def ssgen_link(video, output_directory, ttl):
"image2",
out_put_file_name,
]
- process = await asyncio.create_subprocess_exec(
- *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
- )
+ process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
stdout, stderr = await process.communicate()
stderr.decode().strip()
@@ -44,11 +42,7 @@ async def ssgen_link(video, output_directory, ttl):
async def genss_link(msg, video_link, output_directory, min_duration, no_of_photos):
- metadata = (
- await shell_exec(
- f"ffprobe -i {video_link} -show_entries format=duration -v quiet -of csv='p=0'"
- )
- )[0]
+ metadata = (await shell_exec(f"ffprobe -i {video_link} -show_entries format=duration -v quiet -of csv='p=0'"))[0]
duration = round(float(metadata))
if duration > min_duration:
images = []
@@ -56,20 +50,12 @@ async def genss_link(msg, video_link, output_directory, min_duration, no_of_phot
current_ttl = ttl_step
for looper in range(no_of_photos):
ss_img = await ssgen_link(video_link, output_directory, current_ttl)
- images.append(
- InputMediaPhoto(
- media=ss_img, caption=f"Screenshot at {hhmmss(current_ttl)}"
- )
- )
+ images.append(InputMediaPhoto(media=ss_img, caption=f"Screenshot at {hhmmss(current_ttl)}"))
try:
- await msg.edit(
- f"๐ธ Take Screenshoot:\n{looper+1} of {no_of_photos} screenshot generated.."
- )
+ await msg.edit(f"๐ธ Take Screenshoot:\n{looper+1} of {no_of_photos} screenshot generated..")
except FloodWait as e:
await asyncio.sleep(e.value)
- await msg.edit(
- f"๐ธ Take Screenshoot:\n{looper+1} of {no_of_photos} screenshot generated.."
- )
+ await msg.edit(f"๐ธ Take Screenshoot:\n{looper+1} of {no_of_photos} screenshot generated..")
current_ttl = current_ttl + ttl_step
await asyncio.sleep(2)
return images
diff --git a/misskaty/helper/files.py b/misskaty/helper/files.py
index d8f8079f..c5a91845 100644
--- a/misskaty/helper/files.py
+++ b/misskaty/helper/files.py
@@ -53,20 +53,14 @@ async def resize_file_to_sticker_size(file_path: str) -> str:
im.save(file_path)
-async def upload_document(
- client: Client, file_path: str, chat_id: int
-) -> raw.base.InputDocument:
+async def upload_document(client: Client, file_path: str, chat_id: int) -> raw.base.InputDocument:
media = await client.send(
raw.functions.messages.UploadMedia(
peer=await client.resolve_peer(chat_id),
media=raw.types.InputMediaUploadedDocument(
mime_type=client.guess_mime_type(file_path) or "application/zip",
file=await client.save_file(file_path),
- attributes=[
- raw.types.DocumentAttributeFilename(
- file_name=os.path.basename(file_path)
- )
- ],
+ attributes=[raw.types.DocumentAttributeFilename(file_name=os.path.basename(file_path))],
),
)
)
diff --git a/misskaty/helper/media_helper.py b/misskaty/helper/media_helper.py
index d15cd2fb..ca1cd4f6 100644
--- a/misskaty/helper/media_helper.py
+++ b/misskaty/helper/media_helper.py
@@ -21,9 +21,7 @@ def post_to_telegraph(a_title: str, content: str) -> str:
async def run_subprocess(cmd):
- process = await asyncio.create_subprocess_exec(
- *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
- )
+ process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
return await process.communicate()
@@ -50,9 +48,7 @@ async def get_media_info(file_link):
async def runcmd(cmd: str) -> Tuple[str, str, int, int]:
"""run command in terminal"""
args = shlex.split(cmd)
- process = await asyncio.create_subprocess_exec(
- *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
- )
+ process = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
stdout, stderr = await process.communicate()
return (
stdout.decode("utf-8", "replace").strip(),
diff --git a/misskaty/helper/misc.py b/misskaty/helper/misc.py
index e45bf0e6..8c9b2cc0 100644
--- a/misskaty/helper/misc.py
+++ b/misskaty/helper/misc.py
@@ -63,15 +63,9 @@ def paginate_modules(page_n, module_dict, prefix, chat=None):
if len(pairs) > COLUMN_SIZE:
pairs = pairs[modulo_page * COLUMN_SIZE : COLUMN_SIZE * (modulo_page + 1)] + [
(
- EqInlineKeyboardButton(
- "โฎ", callback_data=f"{prefix}_prev({modulo_page})"
- ),
- EqInlineKeyboardButton(
- "Back", callback_data=f"{prefix}_home({modulo_page})"
- ),
- EqInlineKeyboardButton(
- "โฏ", callback_data=f"{prefix}_next({modulo_page})"
- ),
+ EqInlineKeyboardButton("โฎ", callback_data=f"{prefix}_prev({modulo_page})"),
+ EqInlineKeyboardButton("Back", callback_data=f"{prefix}_home({modulo_page})"),
+ EqInlineKeyboardButton("โฏ", callback_data=f"{prefix}_next({modulo_page})"),
)
]
diff --git a/misskaty/helper/stickerset.py b/misskaty/helper/stickerset.py
index 7b42f3d3..a1e8bca7 100644
--- a/misskaty/helper/stickerset.py
+++ b/misskaty/helper/stickerset.py
@@ -22,9 +22,7 @@ from typing import List
from pyrogram import Client, errors, raw
-async def get_sticker_set_by_name(
- client: Client, name: str
-) -> raw.base.messages.StickerSet:
+async def get_sticker_set_by_name(client: Client, name: str) -> raw.base.messages.StickerSet:
try:
return await client.invoke(
raw.functions.messages.GetStickerSet(
@@ -65,15 +63,11 @@ async def add_sticker_to_set(
) -> raw.base.messages.StickerSet:
return await client.invoke(
raw.functions.stickers.AddStickerToSet(
- stickerset=raw.types.InputStickerSetShortName(
- short_name=stickerset.set.short_name
- ),
+ stickerset=raw.types.InputStickerSetShortName(short_name=stickerset.set.short_name),
sticker=sticker,
)
)
-async def create_sticker(
- sticker: raw.base.InputDocument, emoji: str
-) -> raw.base.InputStickerSetItem:
+async def create_sticker(sticker: raw.base.InputDocument, emoji: str) -> raw.base.InputStickerSetItem:
return raw.types.InputStickerSetItem(document=sticker, emoji=emoji)
diff --git a/misskaty/helper/tools.py b/misskaty/helper/tools.py
index 45e25b4e..4d6ae857 100644
--- a/misskaty/helper/tools.py
+++ b/misskaty/helper/tools.py
@@ -57,10 +57,7 @@ TOTAL PLUGINS: {len(ALL_MODULES)}
def get_random_string(length: int = 5):
- text_str = "".join(
- random.SystemRandom().choice(string.ascii_letters + string.digits)
- for _ in range(length)
- )
+ text_str = "".join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length))
return text_str.upper()
diff --git a/misskaty/plugins/__init__.py b/misskaty/plugins/__init__.py
index a7f96b07..385a555b 100644
--- a/misskaty/plugins/__init__.py
+++ b/misskaty/plugins/__init__.py
@@ -20,32 +20,18 @@ def __list_all_modules():
# This generates a list of modules in this
# 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")
- ]
+ 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")]
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
- ):
+ if not all(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
diff --git a/misskaty/plugins/admin.py b/misskaty/plugins/admin.py
index a72cb3ca..afe88f66 100644
--- a/misskaty/plugins/admin.py
+++ b/misskaty/plugins/admin.py
@@ -63,12 +63,7 @@ async def admin_cache_func(_, cmu):
try:
admins_in_chat[cmu.chat.id] = {
"last_updated_at": time(),
- "data": [
- member.user.id
- async for member in app.get_chat_members(
- cmu.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS
- )
- ],
+ "data": [member.user.id async for member in app.get_chat_members(cmu.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS)],
}
LOGGER.info(f"Updated admin cache for {cmu.chat.id} [{cmu.chat.title}]")
except:
@@ -158,9 +153,7 @@ async def kickFunc(client, message):
# Ban/DBan/TBan User
-@app.on_message(
- filters.command(["ban", "dban", "tban"], COMMAND_HANDLER) & ~filters.private
-)
+@app.on_message(filters.command(["ban", "dban", "tban"], COMMAND_HANDLER) & ~filters.private)
@adminsOnly("can_restrict_members")
async def banFunc(client, message):
user_id, reason = await extract_user_and_reason(message, sender_chat=True)
@@ -172,23 +165,14 @@ async def banFunc(client, message):
if user_id in SUDO:
return await message.reply_text("You Wanna Ban The Elevated One?, RECONSIDER!")
if user_id in (await list_admins(message.chat.id)):
- return await message.reply_text(
- "I can't ban an admin, You know the rules, so do i."
- )
+ return await message.reply_text("I can't ban an admin, You know the rules, so do i.")
try:
mention = (await app.get_users(user_id)).mention
except IndexError:
- mention = (
- message.reply_to_message.sender_chat.title
- if message.reply_to_message
- else "Anon"
- )
+ mention = message.reply_to_message.sender_chat.title if message.reply_to_message else "Anon"
- msg = (
- f"**Banned User:** {mention}\n"
- f"**Banned By:** {message.from_user.mention if message.from_user else 'Anon'}\n"
- )
+ msg = f"**Banned User:** {mention}\n" f"**Banned By:** {message.from_user.mention if message.from_user else 'Anon'}\n"
if message.command[0][0] == "d":
await message.reply_to_message.delete()
if message.command[0] == "tban":
@@ -236,33 +220,25 @@ async def unban_func(_, message):
elif len(message.command) == 1 and reply:
user = message.reply_to_message.from_user.id
else:
- return await message.reply_text(
- "Provide a username or reply to a user's message to unban."
- )
+ return await message.reply_text("Provide a username or reply to a user's message to unban.")
await message.chat.unban_member(user)
umention = (await app.get_users(user)).mention
await message.reply_text(f"Unbanned! {umention}")
# Ban users listed in a message
-@app.on_message(
- filters.user(SUDO) & filters.command("listban", COMMAND_HANDLER) & ~filters.private
-)
+@app.on_message(filters.user(SUDO) & filters.command("listban", COMMAND_HANDLER) & ~filters.private)
async def list_ban_(c, message):
userid, msglink_reason = await extract_user_and_reason(message)
if not userid or not msglink_reason:
- return await message.reply_text(
- "Provide a userid/username along with message link and reason to list-ban"
- )
+ return await message.reply_text("Provide a userid/username along with message link and reason to list-ban")
if len(msglink_reason.split(" ")) == 1: # message link included with the reason
return await message.reply_text("You must provide a reason to list-ban")
# seperate messge link from reason
lreason = msglink_reason.split()
messagelink, reason = lreason[0], " ".join(lreason[1:])
- if not re.search(
- r"(https?://)?t(elegram)?\.me/\w+/\d+", messagelink
- ): # validate link
+ if not re.search(r"(https?://)?t(elegram)?\.me/\w+/\d+", messagelink): # validate link
return await message.reply_text("Invalid message link provided")
if userid == c.me.id:
@@ -271,9 +247,7 @@ async def list_ban_(c, message):
return await message.reply_text("You Wanna Ban The Elevated One?, RECONSIDER!")
splitted = messagelink.split("/")
uname, mid = splitted[-2], int(splitted[-1])
- m = await message.reply_text(
- "`Banning User from multiple groups. This may take some time`"
- )
+ m = await message.reply_text("`Banning User from multiple groups. This may take some time`")
try:
msgtext = (await app.get_messages(uname, mid)).text
gusernames = re.findall(r"@\w+", msgtext)
@@ -302,17 +276,11 @@ async def list_ban_(c, message):
# Unban users listed in a message
-@app.on_message(
- filters.user(SUDO)
- & filters.command("listunban", COMMAND_HANDLER)
- & ~filters.private
-)
+@app.on_message(filters.user(SUDO) & filters.command("listunban", COMMAND_HANDLER) & ~filters.private)
async def list_unban_(c, message):
userid, msglink = await extract_user_and_reason(message)
if not userid or not msglink:
- return await message.reply_text(
- "Provide a userid/username along with message link to list-unban"
- )
+ return await message.reply_text("Provide a userid/username along with message link to list-unban")
if not re.search(r"(https?://)?t(elegram)?\.me/\w+/\d+", msglink): # validate link
return await message.reply_text("Invalid message link provided")
@@ -362,9 +330,7 @@ async def deleteFunc(_, message):
# Promote Members
-@app.on_message(
- filters.command(["promote", "fullpromote"], COMMAND_HANDLER) & ~filters.private
-)
+@app.on_message(filters.command(["promote", "fullpromote"], COMMAND_HANDLER) & ~filters.private)
@adminsOnly("can_promote_members")
async def promoteFunc(client, message):
try:
@@ -474,15 +440,10 @@ async def mute(client, message):
if user_id in SUDO:
return await message.reply_text("You wanna mute the elevated one?, RECONSIDER!")
if user_id in (await list_admins(message.chat.id)):
- return await message.reply_text(
- "I can't mute an admin, You know the rules, so do i."
- )
+ return await message.reply_text("I can't mute an admin, You know the rules, so do i.")
mention = (await app.get_users(user_id)).mention
keyboard = ikb({"๐จ Unmute ๐จ": f"unmute_{user_id}"})
- msg = (
- f"**Muted User:** {mention}\n"
- f"**Muted By:** {message.from_user.mention if message.from_user else 'Anon'}\n"
- )
+ msg = f"**Muted User:** {mention}\n" f"**Muted By:** {message.from_user.mention if message.from_user else 'Anon'}\n"
if message.command[0] == "tmute":
split = reason.split(None, 1)
time_value = split[0]
@@ -558,9 +519,7 @@ async def warn_user(client, message):
if user_id in SUDO:
return await message.reply_text("You Wanna Warn The Elevated One?, RECONSIDER!")
if user_id in (await list_admins(chat_id)):
- return await message.reply_text(
- "I can't warn an admin, You know the rules, so do i."
- )
+ return await message.reply_text("I can't warn an admin, You know the rules, so do i.")
user, warns = await asyncio.gather(
app.get_users(user_id),
get_warn(chat_id, await int_to_alpha(user_id)),
@@ -593,8 +552,7 @@ async def remove_warning(_, cq):
permission = "can_restrict_members"
if permission not in permissions:
return await cq.answer(
- "You don't have enough permissions to perform this action.\n"
- + f"Permission needed: {permission}",
+ "You don't have enough permissions to perform this action.\n" + f"Permission needed: {permission}",
show_alert=True,
)
user_id = cq.data.split("_")[1]
@@ -619,8 +577,7 @@ async def unmute_user(_, cq):
permission = "can_restrict_members"
if permission not in permissions:
return await cq.answer(
- "You don't have enough permissions to perform this action.\n"
- + f"Permission needed: {permission}",
+ "You don't have enough permissions to perform this action.\n" + f"Permission needed: {permission}",
show_alert=True,
)
user_id = cq.data.split("_")[1]
@@ -639,8 +596,7 @@ async def unban_user(_, cq):
permission = "can_restrict_members"
if permission not in permissions:
return await cq.answer(
- "You don't have enough permissions to perform this action.\n"
- + f"Permission needed: {permission}",
+ "You don't have enough permissions to perform this action.\n" + f"Permission needed: {permission}",
show_alert=True,
)
user_id = cq.data.split("_")[1]
@@ -657,9 +613,7 @@ async def unban_user(_, cq):
@adminsOnly("can_restrict_members")
async def remove_warnings(_, message):
if not message.reply_to_message:
- return await message.reply_text(
- "Reply to a message to remove a user's warnings."
- )
+ return await message.reply_text("Reply to a message to remove a user's warnings.")
user_id = message.reply_to_message.from_user.id
mention = message.reply_to_message.from_user.mention
chat_id = message.chat.id
@@ -690,13 +644,7 @@ async def check_warns(_, message):
# Report User in Group
-@app.on_message(
- (
- filters.command("report", COMMAND_HANDLER)
- | filters.command(["admins", "admin"], prefixes="@")
- )
- & ~filters.private
-)
+@app.on_message((filters.command("report", COMMAND_HANDLER) | filters.command(["admins", "admin"], prefixes="@")) & ~filters.private)
@capture_err
async def report_user(_, message):
if not message.reply_to_message:
@@ -711,28 +659,13 @@ async def report_user(_, message):
linked_chat = (await app.get_chat(message.chat.id)).linked_chat
if linked_chat is None:
if reply_id in list_of_admins or reply_id == message.chat.id:
- return await message.reply_text(
- "Do you know that the user you are replying is an admin ?"
- )
+ return await message.reply_text("Do you know that the user you are replying is an admin ?")
- elif (
- reply_id in list_of_admins
- or reply_id == message.chat.id
- or reply_id == linked_chat.id
- ):
- return await message.reply_text(
- "Do you know that the user you are replying is an admin ?"
- )
- user_mention = (
- reply.from_user.mention if reply.from_user else reply.sender_chat.title
- )
+ elif reply_id in list_of_admins or reply_id == message.chat.id or reply_id == linked_chat.id:
+ return await message.reply_text("Do you know that the user you are replying is an admin ?")
+ user_mention = reply.from_user.mention if reply.from_user else reply.sender_chat.title
text = f"Reported {user_mention} to admins!"
- admin_data = [
- m
- async for m in app.get_chat_members(
- message.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS
- )
- ]
+ admin_data = [m async for m in app.get_chat_members(message.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS)]
for admin in admin_data:
if admin.user.is_bot or admin.user.is_deleted:
# return bots or deleted admins
diff --git a/misskaty/plugins/afk.py b/misskaty/plugins/afk.py
index d0ec2469..e1734629 100644
--- a/misskaty/plugins/afk.py
+++ b/misskaty/plugins/afk.py
@@ -143,9 +143,7 @@ async def active_afk(_, message):
"reason": None,
}
else:
- await app.download_media(
- message.reply_to_message, file_name=f"{user_id}.jpg"
- )
+ await app.download_media(message.reply_to_message, file_name=f"{user_id}.jpg")
details = {
"type": "photo",
"time": time.time(),
@@ -162,9 +160,7 @@ async def active_afk(_, message):
"reason": _reason,
}
else:
- await app.download_media(
- message.reply_to_message, file_name=f"{user_id}.jpg"
- )
+ await app.download_media(message.reply_to_message, file_name=f"{user_id}.jpg")
details = {
"type": "photo",
"time": time.time(),
@@ -180,9 +176,7 @@ async def active_afk(_, message):
}
await add_afk(user_id, details)
- send = await message.reply_text(
- f"{message.from_user.mention} [{message.from_user.id}] is now AFK!."
- )
+ send = await message.reply_text(f"{message.from_user.mention} [{message.from_user.id}] is now AFK!.")
await put_cleanmode(message.chat.id, send.id)
diff --git a/misskaty/plugins/auto_approve.py b/misskaty/plugins/auto_approve.py
index df37b201..51a4e76e 100644
--- a/misskaty/plugins/auto_approve.py
+++ b/misskaty/plugins/auto_approve.py
@@ -20,12 +20,8 @@ async def approve_join_chat(c, m):
markup = InlineKeyboardMarkup(
[
[
- InlineKeyboardButton(
- text="Sudah", callback_data=f"approve_{m.chat.id}"
- ),
- InlineKeyboardButton(
- text="Belum", callback_data=f"declined_{m.chat.id}"
- ),
+ InlineKeyboardButton(text="Sudah", callback_data=f"approve_{m.chat.id}"),
+ InlineKeyboardButton(text="Belum", callback_data=f"declined_{m.chat.id}"),
]
]
)
@@ -43,14 +39,10 @@ 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)
@@ -59,13 +51,9 @@ 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 f01a4f09..a9b22216 100644
--- a/misskaty/plugins/auto_forwarder.py
+++ b/misskaty/plugins/auto_forwarder.py
@@ -20,9 +20,7 @@ LOGGER = getLogger(__name__)
async def FilterMessage(message: Message):
- if (message.forward_from or message.forward_from_chat) and (
- "forwarded" not in FORWARD_FILTERS
- ):
+ if (message.forward_from or message.forward_from_chat) and ("forwarded" not in FORWARD_FILTERS):
return 400
if (len(FORWARD_FILTERS) == 9) or (
(message.video and ("video" in FORWARD_FILTERS))
@@ -46,10 +44,7 @@ async def CheckBlockedExt(event: Message):
if (media is not None) and (media.file_name is not None):
_file = media.file_name.rsplit(".", 1)
if len(_file) == 2:
- return (
- _file[-1].lower() in BLOCKED_EXTENSIONS
- or _file[-1].upper() in BLOCKED_EXTENSIONS
- )
+ return _file[-1].lower() in BLOCKED_EXTENSIONS or _file[-1].upper() in BLOCKED_EXTENSIONS
else:
return False
@@ -83,9 +78,7 @@ async def ForwardMessage(client: user, msg: Message):
LOGGER.warning(f"#FloodWait: Stopped Forwarder for {e.x}s!")
await ForwardMessage(client, msg)
except Exception as err:
- LOGGER.warning(
- f"#ERROR: {err}\n\nUnable to Forward Message to {str(FORWARD_TO_CHAT_ID[i])}, reason: {err}"
- )
+ LOGGER.warning(f"#ERROR: {err}\n\nUnable to Forward Message to {str(FORWARD_TO_CHAT_ID[i])}, reason: {err}")
except Exception as err:
LOGGER.warning(f"#ERROR: {err}")
diff --git a/misskaty/plugins/banned.py b/misskaty/plugins/banned.py
index 17c7e001..ea2f9d9a 100644
--- a/misskaty/plugins/banned.py
+++ b/misskaty/plugins/banned.py
@@ -8,9 +8,7 @@ from utils import temp
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)
@@ -26,9 +24,7 @@ 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)
diff --git a/misskaty/plugins/broadcast.py b/misskaty/plugins/broadcast.py
index c14fdb01..880f84d1 100644
--- a/misskaty/plugins/broadcast.py
+++ b/misskaty/plugins/broadcast.py
@@ -37,10 +37,6 @@ async def broadcast(bot, message):
done += 1
await asyncio.sleep(2)
if not done % 20:
- await sts.edit(
- f"Broadcast in progress:\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}"
- )
+ await sts.edit(f"Broadcast in progress:\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}")
time_taken = datetime.timedelta(seconds=int(time.time() - start_time))
- await sts.edit(
- f"Broadcast Completed:\nCompleted in {time_taken} seconds.\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}"
- )
+ await sts.edit(f"Broadcast Completed:\nCompleted in {time_taken} seconds.\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}")
diff --git a/misskaty/plugins/bypass.py b/misskaty/plugins/bypass.py
index 1e25968c..23580628 100644
--- a/misskaty/plugins/bypass.py
+++ b/misskaty/plugins/bypass.py
@@ -45,10 +45,7 @@ async def pling_bypass(url):
res = await http.get(link)
json_dic_files = res.json().pop("files")
msg = f"\n**Source Link** :\n`{url}`\n**Direct Link :**\n"
- msg += "\n".join(
- f'**โ [{i["name"]}]({unquote(i["url"])}) ({get_readable_file_size(int(i["size"]))})**'
- for i in json_dic_files
- )
+ msg += "\n".join(f'**โ [{i["name"]}]({unquote(i["url"])}) ({get_readable_file_size(int(i["size"]))})**' for i in json_dic_files)
return msg
except Exception as e:
return e
@@ -81,9 +78,7 @@ def wetransfer_bypass(url: str) -> str:
r = s.get("https://wetransfer.com/")
m = re.search('name="csrf-token" content="([^"]+)"', r.text)
s.headers.update({"x-csrf-token": m[1], "x-requested-with": "XMLHttpRequest"})
- r = s.post(
- f"https://wetransfer.com/api/v4/transfers/{transfer_id}/download", json=j
- )
+ r = s.post(f"https://wetransfer.com/api/v4/transfers/{transfer_id}/download", json=j)
j = r.json()
dl_url = j["direct_link"]
@@ -94,9 +89,7 @@ def wetransfer_bypass(url: str) -> str:
@capture_err
async def bypass(_, message):
if len(message.command) == 1:
- return await message.reply(
- f"Gunakan perintah /{message.command[0]} untuk bypass url"
- )
+ return await message.reply(f"Gunakan perintah /{message.command[0]} untuk bypass url")
url = message.command[1]
urllib.parse.urlparse(url).netloc
msg = await message.reply("Bypassing URL..", quote=True)
@@ -120,8 +113,6 @@ async def bypass(_, message):
reply_markup=markup,
disable_web_page_preview=True,
)
- elif "wetransfer.com" or "we.tl" in message.command[1]:
+ else:
data = wetransfer_bypass(url)
await msg.edit(f"{data}\n\n{mention}")
- else:
- await msg.edit("Unsupported URL. Read help menu..")
diff --git a/misskaty/plugins/chatbot.py b/misskaty/plugins/chatbot.py
index 5e66ca66..00a410d2 100644
--- a/misskaty/plugins/chatbot.py
+++ b/misskaty/plugins/chatbot.py
@@ -9,9 +9,7 @@ from misskaty.vars import COMMAND_HANDLER, OPENAI_API
@app.on_message(filters.command("ask", COMMAND_HANDLER))
async def chatbot(c, m):
if len(m.command) == 1:
- return await m.reply(
- f"Gunakan perintah /{m.command[0]} [pertanyaan] untuk menanyakan pertanyaan menggunakan AI."
- )
+ return await m.reply(f"Gunakan perintah /{m.command[0]} [pertanyaan] untuk menanyakan pertanyaan menggunakan AI.")
pertanyaan = m.text.split(" ", maxsplit=1)[1]
headers = {
"Content-Type": "application/json",
@@ -26,11 +24,7 @@ async def chatbot(c, m):
}
msg = await m.reply("Wait a moment looking for your answer..")
try:
- response = (
- await http.post(
- "https://api.openai.com/v1/completions", headers=headers, json=json_data
- )
- ).json()
+ response = (await http.post("https://api.openai.com/v1/completions", headers=headers, json=json_data)).json()
await msg.edit(response["choices"][0]["text"])
except MessageNotModified:
pass
diff --git a/misskaty/plugins/code_tester.py b/misskaty/plugins/code_tester.py
index 109f0583..53a845c9 100644
--- a/misskaty/plugins/code_tester.py
+++ b/misskaty/plugins/code_tester.py
@@ -67,9 +67,7 @@ async def glot(lang, langcode, code):
"content-type": "application/json",
"Authorization": "Token b8a2b75a-a078-4089-869c-e53d448b1ebb",
}
- r = await session.post(
- f"https://glot.io/api/run/{lang}/latest", headers=headers, json=data
- )
+ r = await session.post(f"https://glot.io/api/run/{lang}/latest", headers=headers, json=data)
return await r.json()
@@ -77,9 +75,7 @@ async def glot(lang, langcode, code):
async def list_lang(client, message):
daftarlang = await listcode()
list_ = "".join(f"~> {i['name']}\n" for i in daftarlang)
- return await message.reply(
- f"List of Supported Programming Languages:\n{list_}"
- )
+ return await message.reply(f"List of Supported Programming Languages:\n{list_}")
@app.on_message(filters.command(["assembly"], "!"))
diff --git a/misskaty/plugins/detect_afk.py b/misskaty/plugins/detect_afk.py
index 4f4f38af..ce93a984 100644
--- a/misskaty/plugins/detect_afk.py
+++ b/misskaty/plugins/detect_afk.py
@@ -195,9 +195,7 @@ async def chat_watcher_func(_, message):
reasonafk = reasondb["reason"]
seenago = get_readable_time2((int(time.time() - timeafk)))
if afktype == "text":
- msg += (
- f"**{first_name[:25]}** is AFK since {seenago} ago.\n\n"
- )
+ msg += f"**{first_name[:25]}** is AFK since {seenago} ago.\n\n"
if afktype == "text_reason":
msg += f"**{first_name[:25]}** is AFK since {seenago} ago.\n\n**Reason:** {reasonafk}\n\n"
if afktype == "animation":
diff --git a/misskaty/plugins/dev.py b/misskaty/plugins/dev.py
index 7c029a3e..3dcc8896 100644
--- a/misskaty/plugins/dev.py
+++ b/misskaty/plugins/dev.py
@@ -52,9 +52,7 @@ async def donate(_, message):
)
-@app.on_message(
- filters.command(["balas"], COMMAND_HANDLER) & filters.user(SUDO) & filters.reply
-)
+@app.on_message(filters.command(["balas"], COMMAND_HANDLER) & filters.user(SUDO) & filters.reply)
async def balas(c, m):
pesan = m.text.split(" ", 1)
await m.delete()
@@ -68,9 +66,7 @@ async def neofetch(c, m):
@app.on_message(filters.command(["shell", "sh"], COMMAND_HANDLER) & filters.user(SUDO))
-@app.on_edited_message(
- filters.command(["shell", "sh"], COMMAND_HANDLER) & filters.user(SUDO)
-)
+@app.on_edited_message(filters.command(["shell", "sh"], COMMAND_HANDLER) & filters.user(SUDO))
async def shell(_, m):
cmd = m.text.split(" ", 1)
if len(cmd) == 1:
@@ -83,15 +79,7 @@ async def shell(_, m):
await m.reply_document(
document=doc,
file_name=doc.name,
- reply_markup=InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- text="โ Close", callback_data=f"close#{m.from_user.id}"
- )
- ]
- ]
- ),
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="โ Close", callback_data=f"close#{m.from_user.id}")]]),
)
try:
os.remove("shell_output.txt")
@@ -101,15 +89,7 @@ async def shell(_, m):
await m.reply(
shell,
parse_mode=enums.ParseMode.HTML,
- reply_markup=InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- text="โ Close", callback_data=f"close#{m.from_user.id}"
- )
- ]
- ]
- ),
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="โ Close", callback_data=f"close#{m.from_user.id}")]]),
)
else:
await m.reply("No Reply")
@@ -159,15 +139,7 @@ async def evaluation_cmd_t(_, m):
document="MissKatyEval.txt",
caption=f"{cmd[: 4096 // 4 - 1]}",
disable_notification=True,
- reply_markup=InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- text="โ Close", callback_data=f"close#{m.from_user.id}"
- )
- ]
- ]
- ),
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="โ Close", callback_data=f"close#{m.from_user.id}")]]),
)
os.remove("MissKatyEval.txt")
await status_message.delete()
@@ -175,32 +147,17 @@ async def evaluation_cmd_t(_, m):
await status_message.edit(
final_output,
parse_mode=enums.ParseMode.MARKDOWN,
- reply_markup=InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- text="โ Close", callback_data=f"close#{m.from_user.id}"
- )
- ]
- ]
- ),
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="โ Close", callback_data=f"close#{m.from_user.id}")]]),
)
async def aexec(code, c, m):
- exec(
- "async def __aexec(c, m): "
- + "\n p = print"
- + "\n replied = m.reply_to_message"
- + "".join(f"\n {l_}" for l_ in code.split("\n"))
- )
+ exec("async def __aexec(c, m): " + "\n p = print" + "\n replied = m.reply_to_message" + "".join(f"\n {l_}" for l_ in code.split("\n")))
return await locals()["__aexec"](c, m)
async def shell_exec(code, treat=True):
- process = await asyncio.create_subprocess_shell(
- code, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT
- )
+ process = await asyncio.create_subprocess_shell(code, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)
stdout = (await process.communicate())[0]
if treat:
diff --git a/misskaty/plugins/download_upload.py b/misskaty/plugins/download_upload.py
index c8373187..5ecc5909 100644
--- a/misskaty/plugins/download_upload.py
+++ b/misskaty/plugins/download_upload.py
@@ -50,15 +50,7 @@ async def upload(bot, message):
text = callapi.json()
output = f'File Uploaded to Anonfile\n\n๐ File Name: {text["data"]["file"]["metadata"]["name"]}\n\n๐ฆ File Size: {text["data"]["file"]["metadata"]["size"]["readable"]}\n\n๐ฅ Download Link: {text["data"]["file"]["url"]["full"]}'
- btn = InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- "๐ฅ Download ๐ฅ", url=f"{text['data']['file']['url']['full']}"
- )
- ]
- ]
- )
+ btn = InlineKeyboardMarkup([[InlineKeyboardButton("๐ฅ Download ๐ฅ", url=f"{text['data']['file']['url']['full']}")]])
await m.edit(output, reply_markup=btn)
except Exception as e:
await bot.send_message(message.chat.id, text=f"Something Went Wrong!\n\n{e}")
@@ -79,9 +71,7 @@ async def download(client, message):
)
end_t = datetime.now()
ms = (end_t - start_t).seconds
- await pesan.edit(
- f"Downloaded to {the_real_download_location} in {ms} seconds."
- )
+ await pesan.edit(f"Downloaded to {the_real_download_location} in {ms} seconds.")
elif len(message.command) > 1:
start_t = datetime.now()
the_url_parts = " ".join(message.command[1:])
@@ -117,14 +107,10 @@ async def download(client, message):
current_message += f"File Name: {custom_file_name}\n"
current_message += f"Speed: {speed}\n"
current_message += f"{progress_str}\n"
- current_message += (
- f"{humanbytes(downloaded)} of {humanbytes(total_length)}\n"
- )
+ current_message += f"{humanbytes(downloaded)} of {humanbytes(total_length)}\n"
current_message += f"ETA: {estimated_total_time}"
if round(diff % 10.00) == 0 and current_message != display_message:
- await pesan.edit(
- disable_web_page_preview=True, text=current_message
- )
+ await pesan.edit(disable_web_page_preview=True, text=current_message)
display_message = current_message
await asyncio.sleep(10)
except Exception as e:
@@ -132,22 +118,16 @@ async def download(client, message):
if os.path.exists(download_file_path):
end_t = datetime.now()
ms = (end_t - start_t).seconds
- await pesan.edit(
- f"Downloaded to {download_file_path} in {ms} seconds"
- )
+ await pesan.edit(f"Downloaded to {download_file_path} in {ms} seconds")
else:
- await pesan.edit(
- "Reply to a Telegram Media, to download it to my local server."
- )
+ await pesan.edit("Reply to a Telegram Media, to download it to my local server.")
@app.on_message(filters.command(["tiktokdl"], COMMAND_HANDLER))
@capture_err
async def tiktokdl(client, message):
if len(message.command) == 1:
- return await message.reply(
- f"Use command /{message.command[0]} [link] to download tiktok video."
- )
+ return await message.reply(f"Use command /{message.command[0]} [link] to download tiktok video.")
link = message.command[1]
msg = await message.reply("Trying download...")
try:
@@ -166,9 +146,7 @@ async def tiktokdl(client, message):
@capture_err
async def fbdl(client, message):
if len(message.command) == 1:
- return await message.reply(
- f"Use command /{message.command[0]} [link] to download Facebook video."
- )
+ return await message.reply(f"Use command /{message.command[0]} [link] to download Facebook video.")
link = message.command[1]
msg = await message.reply("Trying download...")
try:
@@ -190,7 +168,5 @@ async def fbdl(client, message):
except:
pass
except Exception as e:
- await message.reply(
- f"Failed to download Facebook video..\n\nReason: {e}"
- )
+ await message.reply(f"Failed to download Facebook video..\n\nReason: {e}")
await msg.delete()
diff --git a/misskaty/plugins/filter_request.py b/misskaty/plugins/filter_request.py
index 51e414ca..00e898f1 100644
--- a/misskaty/plugins/filter_request.py
+++ b/misskaty/plugins/filter_request.py
@@ -19,28 +19,17 @@ 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="๐ฌ Lihat Pesan", url=f"https://t.me/c/1255283935/{message.id}")],
[
InlineKeyboardButton(
text="๐ซ Tolak",
@@ -72,9 +61,7 @@ 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,
@@ -155,36 +142,18 @@ 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"
- )
- ]
- ]
- ),
+ 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"
- )
- ]
- ]
- ),
+ 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.",
@@ -240,9 +209,7 @@ async def _callbackreqada(c, q):
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.",
@@ -269,36 +236,18 @@ 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"
- )
- ]
- ]
- ),
+ 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"
- )
- ]
- ]
- ),
+ 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.",
@@ -350,9 +299,7 @@ async def _callbackunav(c, q):
]
),
)
- await q.answer(
- "Request tidak tersedia, mungkin belum rilis atau memang tidak tersedia versi digital."
- )
+ 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?",
@@ -360,9 +307,7 @@ async def _callbackunav(c, q):
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.",
@@ -400,9 +345,7 @@ async def _callbackaft_unav(c, q):
@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/filters.py b/misskaty/plugins/filters.py
index b03f6a42..381d4216 100644
--- a/misskaty/plugins/filters.py
+++ b/misskaty/plugins/filters.py
@@ -50,13 +50,9 @@ You can use markdown or html to save text too.
@adminsOnly("can_change_info")
async def save_filters(_, message):
if len(message.command) == 1 or not message.reply_to_message:
- return await message.reply_text(
- "**Usage:**\nReply to a text or sticker with /filter [FILTER_NAME] to save it."
- )
+ return await message.reply_text("**Usage:**\nReply to a text or sticker with /filter [FILTER_NAME] to save it.")
if not message.reply_to_message.text and not message.reply_to_message.sticker:
- return await message.reply_text(
- "__**You can only save text or stickers in filters for now.**__"
- )
+ return await message.reply_text("__**You can only save text or stickers in filters for now.**__")
name = message.text.split(None, 1)[1].strip()
if not name:
return await message.reply_text("**Usage:**\n__/filter [FILTER_NAME]__")
@@ -64,9 +60,7 @@ async def save_filters(_, message):
_type = "text" if message.reply_to_message.text else "sticker"
_filter = {
"type": _type,
- "data": message.reply_to_message.text.markdown
- if _type == "text"
- else message.reply_to_message.sticker.file_id,
+ "data": message.reply_to_message.text.markdown if _type == "text" else message.reply_to_message.sticker.file_id,
}
await save_filter(chat_id, name, _filter)
await message.reply(f"__**Saved filter {name}.**__")
diff --git a/misskaty/plugins/genss.py b/misskaty/plugins/genss.py
index ecfd97e6..02b48b89 100644
--- a/misskaty/plugins/genss.py
+++ b/misskaty/plugins/genss.py
@@ -36,17 +36,10 @@ __HELP__ = """"
async def genss(client, message):
replied = message.reply_to_message
if replied is not None:
- media = None
- if replied is not None:
- vid = [replied.video, replied.document]
- for v in vid:
- if v is not None:
- media = v
- break
+ vid = [replied.video, replied.document]
+ media = next((v for v in vid if v is not None), None)
if media is None:
- return await message.reply(
- "Reply to a Telegram Video or document as video to generate screenshoot!"
- )
+ return await message.reply("Reply to a Telegram Video or document as video to generate screenshoot!")
process = await message.reply_text("`Processing, please wait..`")
c_time = time.time()
the_real_download_location = await client.download_media(
@@ -68,16 +61,12 @@ async def genss(client, message):
chat_id=message.chat.id,
message_id=process.id,
)
- await client.send_chat_action(
- chat_id=message.chat.id, action=enums.ChatAction.UPLOAD_PHOTO
- )
+ await client.send_chat_action(chat_id=message.chat.id, action=enums.ChatAction.UPLOAD_PHOTO)
try:
await gather(
*[
- message.reply_document(
- images, reply_to_message_id=message.id
- ),
+ message.reply_document(images, reply_to_message_id=message.id),
message.reply_photo(images, reply_to_message_id=message.id),
]
)
@@ -85,9 +74,7 @@ async def genss(client, message):
await sleep(e.value)
await gather(
*[
- message.reply_document(
- images, reply_to_message_id=message.id
- ),
+ message.reply_document(images, reply_to_message_id=message.id),
message.reply_photo(images, reply_to_message_id=message.id),
]
)
@@ -119,13 +106,9 @@ async def genss_link(client, message):
try:
link = message.text.split(" ")[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("`Processing, please wait..`")
tmp_directory_for_each_user = f"./MissKaty_Genss/{str(message.from_user.id)}"
if not os.path.isdir(tmp_directory_for_each_user):
@@ -137,9 +120,7 @@ async def genss_link(client, message):
chat_id=message.chat.id,
message_id=process.id,
)
- await client.send_chat_action(
- chat_id=message.chat.id, action=enums.ChatAction.UPLOAD_PHOTO
- )
+ await client.send_chat_action(chat_id=message.chat.id, action=enums.ChatAction.UPLOAD_PHOTO)
try:
await message.reply_media_group(images, reply_to_message_id=message.id)
except FloodWait as e:
diff --git a/misskaty/plugins/grup_tools.py b/misskaty/plugins/grup_tools.py
index 1e52eecb..2430375c 100644
--- a/misskaty/plugins/grup_tools.py
+++ b/misskaty/plugins/grup_tools.py
@@ -47,9 +47,7 @@ def draw_multiple_line_text(image, text, font, text_start_height):
lines = textwrap.wrap(text, width=50)
for line in lines:
line_width, line_height = font.getsize(line)
- draw.text(
- ((image_width - line_width) / 2, y_text), line, font=font, fill="black"
- )
+ draw.text(((image_width - line_width) / 2, y_text), line, font=font, fill="black")
y_text += line_height
@@ -59,12 +57,8 @@ def welcomepic(pic, user, chat, count, id):
background = background.resize((1024, 500), Image.ANTIALIAS)
pfp = Image.open(pic).convert("RGBA")
pfp = circle(pfp)
- pfp = pfp.resize(
- (265, 265)
- ) # Resizes the Profilepicture so it fits perfectly in the circle
- font = ImageFont.truetype(
- "Calistoga-Regular.ttf", 37
- ) # <- Text Font of the Member Count. Change the text size for your preference
+ pfp = pfp.resize((265, 265)) # Resizes the Profilepicture so it fits perfectly in the circle
+ font = ImageFont.truetype("Calistoga-Regular.ttf", 37) # <- Text Font of the Member Count. Change the text size for your preference
member_text = f"User#{count}, Selamat Datang {user}" # <- Text under the Profilepicture with the Membercount
draw_multiple_line_text(background, member_text, font, 395)
draw_multiple_line_text(background, chat, font, 47)
@@ -75,23 +69,15 @@ def welcomepic(pic, user, chat, count, id):
size=20,
align="right",
)
- background.paste(
- pfp, (379, 123), pfp
- ) # Pastes the Profilepicture on the Background Image
- background.save(
- f"downloads/welcome#{id}.png"
- ) # Saves the finished Image in the folder with the filename
+ background.paste(pfp, (379, 123), pfp) # Pastes the Profilepicture on the Background Image
+ background.save(f"downloads/welcome#{id}.png") # Saves the finished Image in the folder with the filename
return f"downloads/welcome#{id}.png"
@app.on_chat_member_updated(filters.group & filters.chat(-1001128045651))
@capture_err
async def member_has_joined(c: app, member: ChatMemberUpdated):
- if (
- not member.new_chat_member
- or member.new_chat_member.status in {"banned", "left", "restricted"}
- or member.old_chat_member
- ):
+ if not member.new_chat_member or member.new_chat_member.status in {"banned", "left", "restricted"} or member.old_chat_member:
return
user = member.new_chat_member.user if member.new_chat_member else member.from_user
if user.id in SUDO:
@@ -110,21 +96,15 @@ async def member_has_joined(c: app, member: ChatMemberUpdated):
pass
mention = f"{user.first_name}"
joined_date = datetime.fromtimestamp(time.time()).strftime("%Y.%m.%d %H:%M:%S")
- first_name = (
- f"{user.first_name} {user.last_name}" if user.last_name else user.first_name
- )
+ first_name = f"{user.first_name} {user.last_name}" if user.last_name else user.first_name
id = user.id
dc = user.dc_id or "Member tanpa PP"
count = await app.get_chat_members_count(member.chat.id)
try:
- pic = await app.download_media(
- user.photo.big_file_id, file_name=f"pp{user.id}.png"
- )
+ pic = await app.download_media(user.photo.big_file_id, file_name=f"pp{user.id}.png")
except AttributeError:
pic = "img/profilepic.png"
- welcomeimg = await welcomepic(
- pic, user.first_name, member.chat.title, count, user.id
- )
+ welcomeimg = await welcomepic(pic, user.first_name, member.chat.title, count, user.id)
temp.MELCOW[f"welcome-{member.chat.id}"] = await c.send_photo(
member.chat.id,
photo=welcomeimg,
@@ -133,30 +113,18 @@ async def member_has_joined(c: app, member: ChatMemberUpdated):
userspammer = ""
# Spamwatch Detection
try:
- headers = {
- "Authorization": "Bearer XvfzE4AUNXkzCy0DnIVpFDlxZi79lt6EnwKgBj8Quuzms0OSdHvf1k6zSeyzZ_lz"
- }
- apispamwatch = (
- await http.get(
- f"https://api.spamwat.ch/banlist/{user.id}", headers=headers
- )
- ).json()
+ headers = {"Authorization": "Bearer XvfzE4AUNXkzCy0DnIVpFDlxZi79lt6EnwKgBj8Quuzms0OSdHvf1k6zSeyzZ_lz"}
+ apispamwatch = (await http.get(f"https://api.spamwat.ch/banlist/{user.id}", headers=headers)).json()
if not apispamwatch.get("error"):
- await app.ban_chat_member(
- member.chat.id, user.id, datetime.now() + timedelta(seconds=30)
- )
+ await app.ban_chat_member(member.chat.id, user.id, datetime.now() + timedelta(seconds=30))
userspammer += f"#SpamWatch Federation Ban\nUser {mention} [{user.id}] has been kicked because {apispamwatch.get('reason')}.\n"
except Exception as err:
LOGGER.error(f"ERROR in Spamwatch Detection. {err}")
# Combot API Detection
try:
- apicombot = (
- await http.get(f"https://api.cas.chat/check?user_id={user.id}")
- ).json()
+ apicombot = (await http.get(f"https://api.cas.chat/check?user_id={user.id}")).json()
if apicombot.get("ok") == "true":
- await app.ban_chat_member(
- member.chat.id, user.id, datetime.now() + timedelta(seconds=30)
- )
+ await app.ban_chat_member(member.chat.id, user.id, datetime.now() + timedelta(seconds=30))
userspammer += f"#CAS Federation Ban\nUser {mention} [{user.id}] detected as spambot and has been kicked. Powered by Combot AntiSpam."
except Exception as err:
LOGGER.error(f"ERROR in Combot API Detection. {err}")
@@ -185,9 +153,7 @@ async def save_group(bot, message):
await db.add_chat(message.chat.id, message.chat.title)
if message.chat.id in temp.BANNED_CHATS:
# Inspired from a boat of a banana tree
- buttons = [
- [InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]
- ]
+ buttons = [[InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]]
reply_markup = InlineKeyboardMarkup(buttons)
k = await message.reply(
text="CHAT NOT ALLOWED ๐\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..",
@@ -202,9 +168,7 @@ async def save_group(bot, message):
return
buttons = [
[
- InlineKeyboardButton(
- "โน๏ธ Help", url=f"https://t.me/{temp.U_NAME}?start=help"
- ),
+ InlineKeyboardButton("โน๏ธ Help", url=f"https://t.me/{temp.U_NAME}?start=help"),
InlineKeyboardButton("๐ข Updates", url="https://t.me/YasirPediaChannel"),
]
]
@@ -217,14 +181,10 @@ async def save_group(bot, message):
for u in message.new_chat_members:
count = await app.get_chat_members_count(message.chat.id)
try:
- pic = await app.download_media(
- u.photo.big_file_id, file_name=f"pp{u.id}.png"
- )
+ pic = await app.download_media(u.photo.big_file_id, file_name=f"pp{u.id}.png")
except AttributeError:
pic = "img/profilepic.png"
- welcomeimg = await welcomepic(
- pic, u.first_name, message.chat.title, count, u.id
- )
+ welcomeimg = await welcomepic(pic, u.first_name, message.chat.title, count, u.id)
if (temp.MELCOW).get(f"welcome-{message.chat.id}") is not None:
try:
await (temp.MELCOW[f"welcome-{message.chat.id}"]).delete()
@@ -255,9 +215,7 @@ async def leave_a_chat(bot, message):
except:
chat = chat
try:
- buttons = [
- [InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]
- ]
+ buttons = [[InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]]
reply_markup = InlineKeyboardMarkup(buttons)
await bot.send_message(
chat_id=chat,
@@ -289,16 +247,12 @@ async def disable_chat(bot, message):
if not cha_t:
return await message.reply("Chat Not Found In DB")
if cha_t["is_disabled"]:
- return await message.reply(
- f"This chat is already disabled:\nReason- {cha_t['reason']} "
- )
+ return await message.reply(f"This chat is already disabled:\nReason- {cha_t['reason']} ")
await db.disable_chat(chat_, reason)
temp.BANNED_CHATS.append(chat_)
await message.reply("Chat Succesfully Disabled")
try:
- buttons = [
- [InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]
- ]
+ buttons = [[InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]]
reply_markup = InlineKeyboardMarkup(buttons)
await bot.send_message(
chat_id=chat_,
@@ -343,9 +297,7 @@ async def gen_invite(bot, message):
try:
link = await bot.create_chat_invite_link(chat)
except ChatAdminRequired:
- return await message.reply(
- "Invite Link Generation Failed, Iam Not Having Sufficient Rights"
- )
+ return await message.reply("Invite Link Generation Failed, Iam Not Having Sufficient Rights")
except Exception as e:
return await message.reply(f"Error {e}")
await message.reply(f"Here is your Invite Link {link.invite_link}")
@@ -358,15 +310,11 @@ async def adminlist(_, message):
return await message.reply("Perintah ini hanya untuk grup")
try:
administrators = []
- async for m in app.get_chat_members(
- message.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS
- ):
+ async for m in app.get_chat_members(message.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS):
administrators.append(f"{m.user.first_name}")
res = "".join(f"~ {i}\n" for i in administrators)
- return await message.reply(
- f"Daftar Admin di {message.chat.title} ({message.chat.id}):\n~ {res}"
- )
+ return await message.reply(f"Daftar Admin di {message.chat.title} ({message.chat.id}):\n~ {res}")
except Exception as e:
await message.reply(f"ERROR: {str(e)}")
@@ -384,9 +332,7 @@ async def kickme(_, message):
await message.reply_text(txt)
await message.chat.unban_member(message.from_user.id)
except RPCError as ef:
- await message.reply_text(
- f"Sepertinya ada error, silahkan report ke owner saya. \nERROR: {str(ef)}"
- )
+ await message.reply_text(f"Sepertinya ada error, silahkan report ke owner saya. \nERROR: {str(ef)}")
except Exception as err:
await message.reply(f"ERROR: {err}")
diff --git a/misskaty/plugins/imdb_search.py b/misskaty/plugins/imdb_search.py
index b358172a..992992aa 100644
--- a/misskaty/plugins/imdb_search.py
+++ b/misskaty/plugins/imdb_search.py
@@ -73,13 +73,9 @@ async def imdbsetlang(client, query):
)
is_imdb, lang = await is_imdbset(query.from_user.id)
if is_imdb:
- buttons.row(
- InlineButton("๐ Remove UserSetting", f"setimdb#rm#{query.from_user.id}")
- )
+ buttons.row(InlineButton("๐ Remove UserSetting", f"setimdb#rm#{query.from_user.id}"))
buttons.row(InlineButton("โ Close", f"close#{query.from_user.id}"))
- await query.message.edit_caption(
- "Please select available language below..", reply_markup=buttons
- )
+ await query.message.edit_caption("Please select available language below..", reply_markup=buttons)
@app.on_callback_query(filters.regex("^setimdb"))
@@ -89,19 +85,13 @@ async def imdbsetlang(client, query):
return await query.answer("โ ๏ธ Access Denied!", True)
if lang == "eng":
await add_imdbset(query.from_user.id, lang)
- await query.message.edit_caption(
- "Language interface for IMDB has been changed to English."
- )
+ await query.message.edit_caption("Language interface for IMDB has been changed to English.")
elif lang == "ind":
await add_imdbset(query.from_user.id, lang)
- await query.message.edit_caption(
- "Bahasa tampilan IMDB sudah diubah ke Indonesia."
- )
+ await query.message.edit_caption("Bahasa tampilan IMDB sudah diubah ke Indonesia.")
else:
await remove_imdbset(query.from_user.id)
- await query.message.edit_caption(
- "UserSetting for IMDB has been deleted from database."
- )
+ await query.message.edit_caption("UserSetting for IMDB has been deleted from database.")
async def imdb_search_id(kueri, message):
@@ -117,9 +107,7 @@ async def imdb_search_id(kueri, message):
r = await http.get(f"https://yasirapi.eu.org/imdb-search?q={kueri}")
res = json.loads(r.text).get("result")
if not res:
- return await k.edit_caption(
- f"โ๏ธ Tidak ditemukan hasil untuk kueri: {kueri}"
- )
+ return await k.edit_caption(f"โ๏ธ Tidak ditemukan hasil untuk kueri: {kueri}")
msg += f"๐ฌ Ditemukan ({len(res)}) hasil untuk kueri: {kueri}\n\n"
for num, movie in enumerate(res, start=1):
title = movie.get("l")
@@ -133,22 +121,22 @@ async def imdb_search_id(kueri, message):
callback_data=f"imdbres_id#{message.from_user.id}#{movieID}",
)
)
- BTN.append(
- InlineKeyboardButton(
- text="๐ฉ Language", callback_data=f"imdbset#{message.from_user.id}"
- )
- )
- BTN.append(
- InlineKeyboardButton(
- text="โ Close", callback_data=f"close#{message.from_user.id}"
+ BTN.extend(
+ (
+ InlineKeyboardButton(
+ text="๐ฉ Language",
+ callback_data=f"imdbset#{message.from_user.id}",
+ ),
+ InlineKeyboardButton(
+ text="โ Close",
+ callback_data=f"close#{message.from_user.id}",
+ ),
)
)
buttons.add(*BTN)
await k.edit_caption(msg, reply_markup=buttons)
except Exception as err:
- await k.edit_caption(
- f"Ooppss, gagal mendapatkan daftar judul di IMDb.\n\nERROR: {err}"
- )
+ await k.edit_caption(f"Ooppss, gagal mendapatkan daftar judul di IMDb.\n\nERROR: {err}")
async def imdb_search_en(kueri, message):
@@ -164,9 +152,7 @@ async def imdb_search_en(kueri, message):
r = await http.get(f"https://yasirapi.eu.org/imdb-search?q={kueri}")
res = json.loads(r.text).get("result")
if not res:
- return await k.edit_caption(
- f"โ๏ธ Result not found for keywords: {kueri}"
- )
+ return await k.edit_caption(f"โ๏ธ Result not found for keywords: {kueri}")
msg += f"๐ฌ Found ({len(res)}) result for keywords: {kueri}\n\n"
for num, movie in enumerate(res, start=1):
title = movie.get("l")
@@ -180,22 +166,22 @@ async def imdb_search_en(kueri, message):
callback_data=f"imdbres_en#{message.from_user.id}#{movieID}",
)
)
- BTN.append(
- InlineKeyboardButton(
- text="๐ฉ Language", callback_data=f"imdbset#{message.from_user.id}"
- )
- )
- BTN.append(
- InlineKeyboardButton(
- text="โ Close", callback_data=f"close#{message.from_user.id}"
+ BTN.extend(
+ (
+ InlineKeyboardButton(
+ text="๐ฉ Language",
+ callback_data=f"imdbset#{message.from_user.id}",
+ ),
+ InlineKeyboardButton(
+ text="โ Close",
+ callback_data=f"close#{message.from_user.id}",
+ ),
)
)
buttons.add(*BTN)
await k.edit_caption(msg, reply_markup=buttons)
except Exception as err:
- await k.edit_caption(
- f"Failed when requesting movies title.\n\nERROR: {err}"
- )
+ await k.edit_caption(f"Failed when requesting movies title.\n\nERROR: {err}")
@app.on_callback_query(filters.regex("^imdcari_id"))
@@ -216,9 +202,7 @@ async def imdbcari_id(client, query):
r = await http.get(f"https://yasirapi.eu.org/imdb-search?q={kueri}")
res = json.loads(r.text).get("result")
if not res:
- return await query.message.edit_caption(
- f"โ๏ธ Tidak ditemukan hasil untuk kueri: {kueri}"
- )
+ return await query.message.edit_caption(f"โ๏ธ Tidak ditemukan hasil untuk kueri: {kueri}")
msg += f"๐ฌ Ditemukan ({len(res)}) hasil dari: {kueri} ~ {query.from_user.mention}\n\n"
for num, movie in enumerate(res, start=1):
title = movie.get("l")
@@ -226,19 +210,17 @@ async def imdbcari_id(client, query):
type = movie.get("q").replace("feature", "movie").capitalize()
movieID = re.findall(r"tt(\d+)", movie.get("id"))[0]
msg += f"{num}. {title} {year} - {type}\n"
- BTN.append(
- InlineKeyboardButton(
- text=num, callback_data=f"imdbres_id#{uid}#{movieID}"
- )
+ BTN.append(InlineKeyboardButton(text=num, callback_data=f"imdbres_id#{uid}#{movieID}"))
+ BTN.extend(
+ (
+ InlineKeyboardButton(text="๐ฉ Language", callback_data=f"imdbset#{uid}"),
+ InlineKeyboardButton(text="โ Close", callback_data=f"close#{uid}"),
)
- BTN.append(InlineKeyboardButton(text="๐ฉ Language", callback_data=f"imdbset#{uid}"))
- BTN.append(InlineKeyboardButton(text="โ Close", callback_data=f"close#{uid}"))
+ )
buttons.add(*BTN)
await query.message.edit_caption(msg, reply_markup=buttons)
except Exception as err:
- await query.message.edit_caption(
- f"Ooppss, gagal mendapatkan daftar judul di IMDb.\n\nERROR: {err}"
- )
+ await query.message.edit_caption(f"Ooppss, gagal mendapatkan daftar judul di IMDb.\n\nERROR: {err}")
@app.on_callback_query(filters.regex("^imdbcari_en"))
@@ -246,12 +228,12 @@ async def imdbcari_en(client, query):
BTN = []
i, msg, uid = query.data.split("#")
if query.from_user.id != int(uid):
- return await query.answer(f"โ ๏ธ Access Denied!", True)
+ return await query.answer("โ ๏ธ Access Denied!", True)
try:
kueri = LIST_CARI.get(msg)
del LIST_CARI[msg]
except KeyError:
- return await query.message.edit_caption(f"โ ๏ธ Callback Query Expired!")
+ return await query.message.edit_caption("โ ๏ธ Callback Query Expired!")
await query.message.edit_caption("๐ Looking in the IMDB Database..")
msg = ""
buttons = InlineKeyboard(row_width=4)
@@ -259,9 +241,7 @@ async def imdbcari_en(client, query):
r = await http.get(f"https://yasirapi.eu.org/imdb-search?q={kueri}")
res = json.loads(r.text).get("result")
if not res:
- return await query.message.edit_caption(
- f"โ๏ธ Result not found for keywords: {kueri}"
- )
+ return await query.message.edit_caption(f"โ๏ธ Result not found for keywords: {kueri}")
msg += f"๐ฌ Found ({len(res)}) result for keywords: {kueri} ~ {query.from_user.mention}\n\n"
for num, movie in enumerate(res, start=1):
title = movie.get("l")
@@ -269,27 +249,17 @@ async def imdbcari_en(client, query):
type = movie.get("q").replace("feature", "movie").capitalize()
movieID = re.findall(r"tt(\d+)", movie.get("id"))[0]
msg += f"{num}. {title} {year} - {type}\n"
- BTN.append(
- InlineKeyboardButton(
- text=num, callback_data=f"imdbres_en#{uid}#{movieID}"
- )
- )
- BTN.append(
- InlineKeyboardButton(
- text="๐ฉ Language", callback_data=f"imdbset#{uid}"
- )
- )
- BTN.append(
- InlineKeyboardButton(
- text="โ Close", callback_data=f"close#{uid}"
+ BTN.append(InlineKeyboardButton(text=num, callback_data=f"imdbres_en#{uid}#{movieID}"))
+ BTN.extend(
+ (
+ InlineKeyboardButton(text="๐ฉ Language", callback_data=f"imdbset#{uid}"),
+ InlineKeyboardButton(text="โ Close", callback_data=f"close#{uid}"),
)
)
buttons.add(*BTN)
await query.message.edit_caption(msg, reply_markup=buttons)
except Exception as err:
- await query.message.edit_caption(
- f"Failed when requesting movies title @ IMDb\n\nERROR: {err}"
- )
+ await query.message.edit_caption(f"Failed when requesting movies title @ IMDb\n\nERROR: {err}")
@app.on_callback_query(filters.regex("^imdbres_id"))
@@ -302,23 +272,15 @@ async def imdb_id_callback(bot, query):
url = f"https://www.imdb.com/title/tt{movie}/"
resp = await http.get(
url,
- 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"},
)
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"
@@ -327,64 +289,30 @@ async def imdb_id_callback(bot, query):
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 = ""
- for i in r_json["genre"]:
- if i in GENRES_EMOJI:
- genre += (
- f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, "
- )
- else:
- genre += f"#{i.replace('-', '_').replace(' ', '_')}, "
+ 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"
@@ -415,9 +343,7 @@ async def imdb_id_callback(bot, query):
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(",")
@@ -428,11 +354,7 @@ async def imdb_id_callback(bot, query):
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"
@@ -442,33 +364,19 @@ async def imdb_id_callback(bot, query):
markup = InlineKeyboardMarkup(
[
[
- InlineKeyboardButton(
- "๐ฌ Open IMDB", url=f"https://www.imdb.com{r_json['url']}"
- ),
+ 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.edit_media(
- InputMediaPhoto(thumb, caption=res_str), reply_markup=markup
- )
+ await query.message.edit_media(InputMediaPhoto(thumb, caption=res_str), reply_markup=markup)
except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty):
poster = thumb.replace(".jpg", "._V1_UX360.jpg")
- await query.message.edit_media(
- InputMediaPhoto(poster, caption=res_str), reply_markup=markup
- )
+ await query.message.edit_media(InputMediaPhoto(poster, caption=res_str), reply_markup=markup)
except Exception:
await query.message.edit_caption(res_str, reply_markup=markup)
else:
@@ -489,23 +397,15 @@ async def imdb_en_callback(bot, query):
url = f"https://www.imdb.com/title/tt{movie}/"
resp = await http.get(
url,
- 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"},
)
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"
@@ -514,62 +414,30 @@ async def imdb_en_callback(bot, query):
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 = ""
- for i in r_json["genre"]:
- if i in GENRES_EMOJI:
- genre += (
- f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, "
- )
- else:
- genre += f"#{i.replace('-', '_').replace(' ', '_')}, "
+ 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"
@@ -610,11 +478,7 @@ async def imdb_en_callback(bot, query):
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"
@@ -624,33 +488,19 @@ async def imdb_en_callback(bot, query):
markup = InlineKeyboardMarkup(
[
[
- InlineKeyboardButton(
- "๐ฌ Open IMDB", url=f"https://www.imdb.com{r_json['url']}"
- ),
+ 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.edit_media(
- InputMediaPhoto(thumb, caption=res_str), reply_markup=markup
- )
+ await query.message.edit_media(InputMediaPhoto(thumb, caption=res_str), reply_markup=markup)
except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty):
poster = thumb.replace(".jpg", "._V1_UX360.jpg")
- await query.message.edit_media(
- InputMediaPhoto(poster, caption=res_str), reply_markup=markup
- )
+ await query.message.edit_media(InputMediaPhoto(poster, caption=res_str), reply_markup=markup)
except Exception:
await query.message.edit_caption(res_str, reply_markup=markup)
else:
diff --git a/misskaty/plugins/inkick_user.py b/misskaty/plugins/inkick_user.py
index 6dbfffa3..0a1ba139 100644
--- a/misskaty/plugins/inkick_user.py
+++ b/misskaty/plugins/inkick_user.py
@@ -19,9 +19,7 @@ __HELP__ = """"
"""
-@app.on_message(
- filters.incoming & ~filters.private & filters.command(["inkick"], COMMAND_HANDLER)
-)
+@app.on_message(filters.incoming & ~filters.private & filters.command(["inkick"], COMMAND_HANDLER))
async def inkick(_, message):
if message.sender_chat:
return await message.reply("This feature not available for channel.")
@@ -29,61 +27,44 @@ async def inkick(_, message):
if user.status.value in ("administrator", "owner"):
if len(message.command) > 1:
input_str = message.command
- sent_message = await message.reply_text(
- "๐ฎ**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**"
- )
+ sent_message = await message.reply_text("๐ฎ**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**")
count = 0
async for member in app.get_chat_members(message.chat.id):
if member.user.is_bot:
continue
- if (
- member.user.status.value in input_str
- and member.status.value not in ("administrator", "owner")
- ):
+ if member.user.status.value in input_str and member.status.value not in ("administrator", "owner"):
try:
await message.chat.ban_member(member.user.id)
count += 1
await sleep(1)
await message.chat.unban_member(member.user.id)
except (ChatAdminRequired, UserAdminInvalid):
- await sent_message.edit(
- "โ**Oh tidaakk, saya bukan admin disini**\n__Saya pergi dari sini, tambahkan aku kembali dengan perijinan banned pengguna.__"
- )
+ await sent_message.edit("โ**Oh tidaakk, saya bukan admin disini**\n__Saya pergi dari sini, tambahkan aku kembali dengan perijinan banned pengguna.__")
await app.leave_chat(message.chat.id)
break
except FloodWait as e:
await sleep(e.value)
try:
- await sent_message.edit(
- f"โ๏ธ **Berhasil menendang {count} pengguna berdasarkan argumen.**"
- )
+ await sent_message.edit(f"โ๏ธ **Berhasil menendang {count} pengguna berdasarkan argumen.**")
except ChatWriteForbidden:
await app.leave_chat(message.chat.id)
else:
- await message.reply_text(
- "โ **Arguments Required**\n__See /help in personal message for more information.__"
- )
+ await message.reply_text("โ **Arguments Required**\n__See /help in personal message for more information.__")
else:
- sent_message = await message.reply_text(
- "โ **You have to be the group creator to do that.**"
- )
+ sent_message = await message.reply_text("โ **You have to be the group creator to do that.**")
await sleep(5)
await sent_message.delete()
# Kick User Without Username
-@app.on_message(
- filters.incoming & ~filters.private & filters.command(["uname"], COMMAND_HANDLER)
-)
+@app.on_message(filters.incoming & ~filters.private & filters.command(["uname"], COMMAND_HANDLER))
async def uname(_, message):
if message.sender_chat:
return await message.reply("This feature not available for channel.")
user = await app.get_chat_member(message.chat.id, message.from_user.id)
if user.status.value in ("administrator", "owner"):
- sent_message = await message.reply_text(
- "๐ฎ**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**"
- )
+ sent_message = await message.reply_text("๐ฎ**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**")
count = 0
async for member in app.get_chat_members(message.chat.id):
if not member.user.username and member.status.value not in (
@@ -96,39 +77,29 @@ async def uname(_, message):
await sleep(1)
await message.chat.unban_member(member.user.id)
except (ChatAdminRequired, UserAdminInvalid):
- await sent_message.edit(
- "โ**Oh tidaakk, saya bukan admin disini**\n__Saya pergi dari sini, tambahkan aku kembali dengan perijinan banned pengguna.__"
- )
+ await sent_message.edit("โ**Oh tidaakk, saya bukan admin disini**\n__Saya pergi dari sini, tambahkan aku kembali dengan perijinan banned pengguna.__")
await app.leave_chat(message.chat.id)
break
except FloodWait as e:
await sleep(e.value)
try:
- await sent_message.edit(
- f"โ๏ธ **Berhasil menendang {count} pengguna berdasarkan argumen.**"
- )
+ await sent_message.edit(f"โ๏ธ **Berhasil menendang {count} pengguna berdasarkan argumen.**")
except ChatWriteForbidden:
await app.leave_chat(message.chat.id)
else:
- sent_message = await message.reply_text(
- "โ **You have to be the group creator to do that.**"
- )
+ sent_message = await message.reply_text("โ **You have to be the group creator to do that.**")
await sleep(5)
await sent_message.delete()
-@app.on_message(
- filters.incoming & ~filters.private & filters.command(["dkick"], COMMAND_HANDLER)
-)
+@app.on_message(filters.incoming & ~filters.private & filters.command(["dkick"], COMMAND_HANDLER))
async def dkick(client, message):
if message.sender_chat:
return await message.reply("This feature not available for channel.")
user = await app.get_chat_member(message.chat.id, message.from_user.id)
if user.status.value in ("administrator", "owner"):
- sent_message = await message.reply_text(
- "๐ฎ**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**"
- )
+ sent_message = await message.reply_text("๐ฎ**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**")
count = 0
async for member in app.get_chat_members(message.chat.id):
if member.user.is_deleted and member.status.value not in (
@@ -141,9 +112,7 @@ async def dkick(client, message):
await sleep(1)
await message.chat.unban_member(member.user.id)
except (ChatAdminRequired, UserAdminInvalid):
- await sent_message.edit(
- "โ**Oh tidaakk, saya bukan admin disini**\n__Saya pergi dari sini, tambahkan aku kembali dengan perijinan banned pengguna.__"
- )
+ await sent_message.edit("โ**Oh tidaakk, saya bukan admin disini**\n__Saya pergi dari sini, tambahkan aku kembali dengan perijinan banned pengguna.__")
await app.leave_chat(message.chat.id)
break
except FloodWait as e:
@@ -153,16 +122,12 @@ async def dkick(client, message):
except ChatWriteForbidden:
await app.leave_chat(message.chat.id)
else:
- sent_message = await message.reply_text(
- "โ **Kamu harus jadi admin atau owner grup untuk melakukan tindakan ini.**"
- )
+ sent_message = await message.reply_text("โ **Kamu harus jadi admin atau owner grup untuk melakukan tindakan ini.**")
await sleep(5)
await sent_message.delete()
-@app.on_message(
- filters.incoming & ~filters.private & filters.command(["instatus"], COMMAND_HANDLER)
-)
+@app.on_message(filters.incoming & ~filters.private & filters.command(["instatus"], COMMAND_HANDLER))
async def instatus(client, message):
start_time = time.perf_counter()
user = await app.get_chat_member(message.chat.id, message.from_user.id)
@@ -171,9 +136,7 @@ async def instatus(client, message):
enums.ChatMemberStatus.ADMINISTRATOR,
enums.ChatMemberStatus.OWNER,
):
- sent_message = await message.reply_text(
- "**Sedang mengumpulkan informasi pengguna...**"
- )
+ sent_message = await message.reply_text("**Sedang mengumpulkan informasi pengguna...**")
recently = 0
within_week = 0
within_month = 0
@@ -185,13 +148,9 @@ async def instatus(client, message):
banned = 0
uncached = 0
bot = 0
- async for ban in app.get_chat_members(
- message.chat.id, filter=enums.ChatMembersFilter.BANNED
- ):
+ async for ban in app.get_chat_members(message.chat.id, filter=enums.ChatMembersFilter.BANNED):
banned += 1
- async for restr in app.get_chat_members(
- message.chat.id, filter=enums.ChatMembersFilter.RESTRICTED
- ):
+ async for restr in app.get_chat_members(message.chat.id, filter=enums.ChatMembersFilter.RESTRICTED):
restricted += 1
async for member in app.get_chat_members(message.chat.id):
user = member.user
@@ -234,8 +193,6 @@ async def instatus(client, message):
)
)
else:
- sent_message = await message.reply_text(
- "โ **Kamu harus jadi admin atau owner grup untuk melakukan tindakan ini.**"
- )
+ sent_message = await message.reply_text("โ **Kamu harus jadi admin atau owner grup untuk melakukan tindakan ini.**")
await sleep(5)
await sent_message.delete()
diff --git a/misskaty/plugins/inline_search.py b/misskaty/plugins/inline_search.py
index 57dc5986..50aab842 100644
--- a/misskaty/plugins/inline_search.py
+++ b/misskaty/plugins/inline_search.py
@@ -43,16 +43,11 @@ PRVT_MSGS = {}
async def inline_menu(_, inline_query: InlineQuery):
if inline_query.query.strip().lower().strip() == "":
buttons = InlineKeyboard(row_width=2)
- buttons.add(
- *[
- (InlineKeyboardButton(text=i, switch_inline_query_current_chat=i))
- for i in keywords_list
- ]
- )
+ buttons.add(*[(InlineKeyboardButton(text=i, switch_inline_query_current_chat=i)) for i in keywords_list])
btn = InlineKeyboard(row_width=2)
- bot_state = "Dead" if not await app.get_me() else "Alive"
- ubot_state = "Dead" if not await user.get_me() else "Alive"
+ bot_state = "Alive" if await app.get_me() else "Dead"
+ ubot_state = "Alive" if await user.get_me() else "Dead"
btn.add(
InlineKeyboardButton("Stats", callback_data="stats_callback"),
InlineKeyboardButton("Go Inline!", switch_inline_query_current_chat=""),
@@ -72,27 +67,21 @@ async def inline_menu(_, inline_query: InlineQuery):
InlineQueryResultArticle(
title="Inline Commands",
description="Help Related To Inline Usage.",
- input_message_content=InputTextMessageContent(
- "Click A Button To Get Started."
- ),
+ input_message_content=InputTextMessageContent("Click A Button To Get Started."),
thumb_url="https://hamker.me/cy00x5x.png",
reply_markup=buttons,
),
InlineQueryResultArticle(
title="Github Repo",
description="Github Repo of This Bot.",
- input_message_content=InputTextMessageContent(
- f"Github Repo @{BOT_USERNAME}\n\nhttps://github.com/yasirarism/MissKatyPyro"
- ),
+ input_message_content=InputTextMessageContent(f"Github Repo @{BOT_USERNAME}\n\nhttps://github.com/yasirarism/MissKatyPyro"),
thumb_url="https://hamker.me/gjc9fo3.png",
),
InlineQueryResultArticle(
title="Alive",
description="Check Bot's Stats",
thumb_url="https://yt3.ggpht.com/ytc/AMLnZu-zbtIsllERaGYY8Aecww3uWUASPMjLUUEt7ecu=s900-c-k-c0x00ffffff-no-rj",
- input_message_content=InputTextMessageContent(
- msg, disable_web_page_preview=True
- ),
+ input_message_content=InputTextMessageContent(msg, disable_web_page_preview=True),
reply_markup=btn,
),
]
@@ -105,13 +94,8 @@ async def inline_menu(_, inline_query: InlineQuery):
switch_pm_parameter="inline",
)
judul = inline_query.query.split(None, 1)[1].strip()
- 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"
- }
- search_results = await http.get(
- f"https://www.google.com/search?q={judul}&num=20", 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"}
+ search_results = await http.get(f"https://www.google.com/search?q={judul}&num=20", headers=headers)
soup = BeautifulSoup(search_results.text, "lxml")
data = []
for result in soup.select(".tF2Cxc"):
@@ -134,9 +118,7 @@ async def inline_menu(_, inline_query: InlineQuery):
url=link,
description=snippet,
thumb_url="https://te.legra.ph/file/ed8ea62ae636793000bb4.jpg",
- reply_markup=InlineKeyboardMarkup(
- [[InlineKeyboardButton(text="Open Website", url=link)]]
- ),
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Open Website", url=link)]]),
)
)
await inline_query.answer(
@@ -160,9 +142,7 @@ async def inline_menu(_, inline_query: InlineQuery):
except Exception: # pylint: disable=broad-except
inline_query.stop_propagation()
return
- namanya = (
- f"{diaa.first_name} {diaa.last_name}" if diaa.last_name else diaa.first_name
- )
+ namanya = f"{diaa.first_name} {diaa.last_name}" if diaa.last_name else diaa.first_name
msg = f"๐ท Name: {namanya}\n๐ ID: {diaa.id}\n"
if diaa.username:
msg += f"๐ Username: @{diaa.username}\n"
@@ -193,7 +173,7 @@ async def inline_menu(_, inline_query: InlineQuery):
_id = inline_query.query.split()[1]
msg = inline_query.query.split(None, 2)[2].strip()
- if not (msg and msg.endswith(":")):
+ if not msg or not msg.endswith(":"):
inline_query.stop_propagation()
try:
@@ -210,11 +190,7 @@ async def inline_menu(_, inline_query: InlineQuery):
)
prvte_msg = InlineKeyboardMarkup(
[
- [
- InlineKeyboardButton(
- "Show Message ๐", callback_data=f"prvtmsg({inline_query.id})"
- )
- ],
+ [InlineKeyboardButton("Show Message ๐", callback_data=f"prvtmsg({inline_query.id})")],
[
InlineKeyboardButton(
"Destroyโ ๏ธ this msg",
@@ -223,14 +199,8 @@ async def inline_menu(_, inline_query: InlineQuery):
],
]
)
- mention = (
- f"{penerima.first_name}"
- if not penerima.username
- else f"@{penerima.username}"
- )
- msg_c = (
- f"๐ A private message to {mention} [{penerima.id}], "
- )
+ mention = f"@{penerima.username}" if penerima.username else f"{penerima.first_name}"
+ msg_c = f"๐ A private message to {mention} [{penerima.id}], "
msg_c += "Only he/she can open it."
results = [
InlineQueryResultArticle(
@@ -250,9 +220,7 @@ async def inline_menu(_, inline_query: InlineQuery):
switch_pm_parameter="inline",
)
query = inline_query.query.split(None, 1)[1].strip()
- search_results = await http.get(
- f"https://api.github.com/search/repositories?q={query}"
- )
+ search_results = await http.get(f"https://api.github.com/search/repositories?q={query}")
srch_results = json.loads(search_results.text)
item = srch_results.get("items")
data = []
@@ -275,9 +243,7 @@ async def inline_menu(_, inline_query: InlineQuery):
url=link,
description=deskripsi,
thumb_url="https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png",
- reply_markup=InlineKeyboardMarkup(
- [[InlineKeyboardButton(text="Open Github Link", url=link)]]
- ),
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Open Github Link", url=link)]]),
)
)
await inline_query.answer(
@@ -296,9 +262,7 @@ async def inline_menu(_, inline_query: InlineQuery):
switch_pm_parameter="inline",
)
query = inline_query.query.split(None, 1)[1].strip()
- search_results = await http.get(
- f"https://api.hayo.my.id/api/pypi?package={query}"
- )
+ search_results = await http.get(f"https://api.hayo.my.id/api/pypi?package={query}")
srch_results = json.loads(search_results.text)
data = []
for sraeo in srch_results:
@@ -319,9 +283,7 @@ async def inline_menu(_, inline_query: InlineQuery):
url=link,
description=deskripsi,
thumb_url="https://raw.githubusercontent.com/github/explore/666de02829613e0244e9441b114edb85781e972c/topics/pip/pip.png",
- reply_markup=InlineKeyboardMarkup(
- [[InlineKeyboardButton(text="Open Link", url=link)]]
- ),
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Open Link", url=link)]]),
)
)
await inline_query.answer(
@@ -340,9 +302,7 @@ async def inline_menu(_, inline_query: InlineQuery):
switch_pm_parameter="inline",
)
judul = inline_query.query.split(None, 1)[1].strip()
- search_results = await http.get(
- f"https://api.abir-hasan.tk/youtube?query={judul}"
- )
+ search_results = await http.get(f"https://api.abir-hasan.tk/youtube?query={judul}")
srch_results = json.loads(search_results.text)
asroe = srch_results.get("results")
oorse = []
@@ -354,9 +314,7 @@ async def inline_menu(_, inline_query: InlineQuery):
durasi = sraeo.get("accessibility").get("duration")
publishTime = sraeo.get("publishedTime")
try:
- deskripsi = "".join(
- f"{i['text']} " for i in sraeo.get("descriptionSnippet")
- )
+ deskripsi = "".join(f"{i['text']} " for i in sraeo.get("descriptionSnippet"))
except:
deskripsi = "-"
message_text = f"{title}\n"
@@ -375,9 +333,7 @@ async def inline_menu(_, inline_query: InlineQuery):
url=link,
description=deskripsi,
thumb_url=thumb,
- reply_markup=InlineKeyboardMarkup(
- [[InlineKeyboardButton(text="Watch Video ๐น", url=link)]]
- ),
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Watch Video ๐น", url=link)]]),
)
)
await inline_query.answer(
@@ -396,9 +352,7 @@ async def inline_menu(_, inline_query: InlineQuery):
switch_pm_parameter="inline",
)
movie_name = inline_query.query.split(None, 1)[1].strip()
- search_results = await http.get(
- f"https://yasirapi.eu.org/imdb-search?q={movie_name}"
- )
+ search_results = await http.get(f"https://yasirapi.eu.org/imdb-search?q={movie_name}")
res = json.loads(search_results.text).get("result")
oorse = []
for midb in res:
@@ -407,11 +361,7 @@ async def inline_menu(_, inline_query: InlineQuery):
stars = midb.get("s", "")
imdb_url = f"https://imdb.com/title/{midb.get('id')}"
year = f"({midb.get('y')})" if midb.get("y") else ""
- image_url = (
- midb.get("i").get("imageUrl").replace(".jpg", "._V1_UX360.jpg")
- if midb.get("i")
- else "https://te.legra.ph/file/e263d10ff4f4426a7c664.jpg"
- )
+ image_url = midb.get("i").get("imageUrl").replace(".jpg", "._V1_UX360.jpg") if midb.get("i") else "https://te.legra.ph/file/e263d10ff4f4426a7c664.jpg"
caption = f"๐ฌ"
caption += f"{title} {year}"
oorse.append(
@@ -486,82 +436,45 @@ async def imdb_inl(_, query):
url = f"https://www.imdb.com/title/{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"
if r_json.get("alternateName"):
- res_str += (
- f"๐ข AKA: {r_json.get('alternateName')}\n\n"
- )
+ res_str += f"๐ข AKA: {r_json.get('alternateName')}\n\n"
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"
- ]
+ 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 = ""
- for i in r_json["genre"]:
- if i in GENRES_EMOJI:
- genre += f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, "
- else:
- genre += f"#{i.replace('-', '_').replace(' ', '_')}, "
+ 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"
- )
+ 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"
@@ -592,9 +505,7 @@ async def imdb_inl(_, query):
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(",")
@@ -605,11 +516,7 @@ async def imdb_inl(_, query):
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"
diff --git a/misskaty/plugins/karma.py b/misskaty/plugins/karma.py
index ae5df068..8ec92683 100644
--- a/misskaty/plugins/karma.py
+++ b/misskaty/plugins/karma.py
@@ -26,9 +26,7 @@ Give reputation to other people in group.
karma_positive_group = 3
karma_negative_group = 4
-regex_upvote = (
- r"^(\+|\+\+|\+1|thx|tnx|ty|thank you|thanx|thanks|pro|cool|good|makasih|๐|\+\+ .+)$"
-)
+regex_upvote = r"^(\+|\+\+|\+1|thx|tnx|ty|thank you|thanx|thanks|pro|cool|good|makasih|๐|\+\+ .+)$"
regex_downvote = r"^(-|--|-1|๐|-- .+)$"
n = "\n"
@@ -49,30 +47,18 @@ def section(
text = (bold_ul(title) + n) if underline else bold(title) + n
for key, value in body.items():
- text += (
- indent * w
- + bold(key)
- + ((value[0] + n) if isinstance(value, list) else mono(value))
- )
+ text += indent * w + bold(key) + ((value[0] + n) if isinstance(value, list) else mono(value))
return text
async def get_user_id_and_usernames(client) -> dict:
with client.storage.lock, client.storage.conn:
- users = client.storage.conn.execute(
- 'SELECT * FROM peers WHERE type in ("user", "bot") AND username NOT null'
- ).fetchall()
+ users = client.storage.conn.execute('SELECT * FROM peers WHERE type in ("user", "bot") AND username NOT null').fetchall()
return {user[0]: user[3] for user in users}
@app.on_message(
- filters.text
- & filters.group
- & filters.incoming
- & filters.reply
- & filters.regex(regex_upvote, re.IGNORECASE)
- & ~filters.via_bot
- & ~filters.bot,
+ filters.text & filters.group & filters.incoming & filters.reply & filters.regex(regex_upvote, re.IGNORECASE) & ~filters.via_bot & ~filters.bot,
group=karma_positive_group,
)
@capture_err
@@ -96,19 +82,11 @@ async def upvote(_, message):
karma = 1
new_karma = {"karma": karma}
await update_karma(chat_id, await int_to_alpha(user_id), new_karma)
- await message.reply_text(
- f"Incremented Karma of {user_mention} By 1 \nTotal Points: {karma}"
- )
+ await message.reply_text(f"Incremented Karma of {user_mention} By 1 \nTotal Points: {karma}")
@app.on_message(
- filters.text
- & filters.group
- & filters.incoming
- & filters.reply
- & filters.regex(regex_downvote, re.IGNORECASE)
- & ~filters.via_bot
- & ~filters.bot,
+ filters.text & filters.group & filters.incoming & filters.reply & filters.regex(regex_downvote, re.IGNORECASE) & ~filters.via_bot & ~filters.bot,
group=karma_negative_group,
)
@capture_err
@@ -133,9 +111,7 @@ async def downvote(_, message):
karma = 1
new_karma = {"karma": karma}
await update_karma(chat_id, await int_to_alpha(user_id), new_karma)
- await message.reply_text(
- f"Decremented Karma Of {user_mention} By 1 \nTotal Points: {karma}"
- )
+ await message.reply_text(f"Decremented Karma Of {user_mention} By 1 \nTotal Points: {karma}")
@app.on_message(filters.command("karma") & filters.group)
diff --git a/misskaty/plugins/mediainfo.py b/misskaty/plugins/mediainfo.py
index 05a53bd3..f9a11385 100644
--- a/misskaty/plugins/mediainfo.py
+++ b/misskaty/plugins/mediainfo.py
@@ -25,9 +25,7 @@ from utils import get_file_id
@app.on_message(filters.command(["mediainfo"], COMMAND_HANDLER))
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")
@@ -69,13 +67,9 @@ async def mediainfo(client, message):
link = message.text.split(" ", maxsplit=1)[1]
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"""
@@ -86,9 +80,7 @@ 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(
@@ -98,6 +90,4 @@ async def mediainfo(client, message):
)
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/memify.py b/misskaty/plugins/memify.py
index 92ca4006..21534698 100644
--- a/misskaty/plugins/memify.py
+++ b/misskaty/plugins/memify.py
@@ -135,9 +135,7 @@ async def draw_meme_text(image_path, text):
@app.on_message(filters.command(["mmf"], COMMAND_HANDLER))
@capture_err
async def memify(client, message):
- if message.reply_to_message and (
- message.reply_to_message.sticker or message.reply_to_message.photo
- ):
+ if message.reply_to_message and (message.reply_to_message.sticker or message.reply_to_message.photo):
try:
file = await message.reply_to_message.download()
res = await draw_meme_text(file, message.text.split(None, 1)[1].strip())
@@ -147,10 +145,6 @@ async def memify(client, message):
except:
pass
except:
- await message.reply(
- "Gunakan command /mmf dengan reply ke sticker, pisahkan dengan ; untuk membuat posisi text dibawah."
- )
+ await message.reply("Gunakan command /mmf dengan reply ke sticker, pisahkan dengan ; untuk membuat posisi text dibawah.")
else:
- await message.reply(
- "Gunakan command /mmf dengan reply ke sticker, pisahkan dengan ; untuk membuat posisi text dibawah."
- )
+ await message.reply("Gunakan command /mmf dengan reply ke sticker, pisahkan dengan ; untuk membuat posisi text dibawah.")
diff --git a/misskaty/plugins/misc_tools.py b/misskaty/plugins/misc_tools.py
index 4f824044..ff4b5ccb 100644
--- a/misskaty/plugins/misc_tools.py
+++ b/misskaty/plugins/misc_tools.py
@@ -53,21 +53,13 @@ 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()
msg = await message.reply("Getting data..")
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 msg.edit(hasil)
@@ -86,10 +78,7 @@ 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"
- }
+ 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,
@@ -118,9 +107,7 @@ 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)
@@ -133,9 +120,7 @@ async def gsearch(client, message):
@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:
@@ -149,14 +134,10 @@ async def translate(client, message):
try:
my_translator = GoogleTranslator(source="auto", target=target_lang)
result = my_translator.translate(text=text)
- await msg.edit(
- f"Translation using source = {my_translator.source} and target = {my_translator.target}\n\n-> {result}"
- )
+ await msg.edit(f"Translation using source = {my_translator.source} and target = {my_translator.target}\n\n-> {result}")
except MessageTooLong:
url = await rentry(result)
- 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}")
except Exception as err:
await msg.edit(f"Error: {str(err)}")
@@ -164,9 +145,7 @@ async def translate(client, message):
@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:
@@ -218,16 +197,12 @@ 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."
- )
+ 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=f"Sticker -> Image\n@{client.me.username}"
- )
+ await message.reply_photo(photo=photo, caption=f"Sticker -> Image\n@{client.me.username}")
os.remove(photo)
except Exception as e:
@@ -260,16 +235,10 @@ 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)
@@ -302,23 +271,13 @@ 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=f"close#{message.from_user.id}"
- )
- ]
- ]
+ buttons = [[InlineKeyboardButton("๐ Close", callback_data=f"close#{message.from_user.id}")]]
reply_markup = InlineKeyboardMarkup(buttons)
await message.reply_photo(
photo=local_user_photo,
@@ -329,13 +288,7 @@ async def who_is(client, message):
)
os.remove(local_user_photo)
else:
- buttons = [
- [
- InlineKeyboardButton(
- "๐ Close", callback_data=f"close#{message.from_user.id}"
- )
- ]
- ]
+ buttons = [[InlineKeyboardButton("๐ Close", callback_data=f"close#{message.from_user.id}")]]
reply_markup = InlineKeyboardMarkup(buttons)
await message.reply_text(
text=message_out_str,
@@ -354,9 +307,7 @@ async def close_callback(bot: Client, query: CallbackQuery):
await query.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):
@@ -409,22 +360,16 @@ 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:
@@ -433,17 +378,11 @@ 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}")
diff --git a/misskaty/plugins/nightmode.py b/misskaty/plugins/nightmode.py
index b4b93ca7..d89530cb 100644
--- a/misskaty/plugins/nightmode.py
+++ b/misskaty/plugins/nightmode.py
@@ -52,9 +52,7 @@ async def job_close():
tahun = now.strftime("%Y")
jam = now.strftime("%H:%M")
try:
- reply_markup = InlineKeyboardMarkup(
- [[InlineKeyboardButton(text="โค๏ธ", callback_data="nightmd")]]
- )
+ reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="โค๏ธ", callback_data="nightmd")]])
await app.set_chat_permissions(
-1001128045651,
ChatPermissions(can_send_messages=False, can_invite_users=True),
@@ -91,9 +89,7 @@ async def job_close_ymoviez():
tahun = now.strftime("%Y")
jam = now.strftime("%H:%M")
try:
- reply_markup = InlineKeyboardMarkup(
- [[InlineKeyboardButton(text="โค๏ธ", callback_data="nightmd")]]
- )
+ reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="โค๏ธ", callback_data="nightmd")]])
await app.set_chat_permissions(
-1001255283935,
ChatPermissions(can_send_messages=False, can_invite_users=True),
@@ -129,9 +125,7 @@ async def job_open():
tahun = now.strftime("%Y")
jam = now.strftime("%H:%M")
try:
- reply_markup = InlineKeyboardMarkup(
- [[InlineKeyboardButton(text="โค๏ธ", callback_data="nightmd")]]
- )
+ reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="โค๏ธ", callback_data="nightmd")]])
await app.set_chat_permissions(
-1001128045651,
ChatPermissions(
@@ -174,9 +168,7 @@ async def job_open_ymoviez():
tahun = now.strftime("%Y")
jam = now.strftime("%H:%M")
try:
- reply_markup = InlineKeyboardMarkup(
- [[InlineKeyboardButton(text="โค๏ธ", callback_data="nightmd")]]
- )
+ reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="โค๏ธ", callback_data="nightmd")]])
await app.set_chat_permissions(
-1001255283935,
ChatPermissions(
diff --git a/misskaty/plugins/notes.py b/misskaty/plugins/notes.py
index 90036bde..09ea7226 100644
--- a/misskaty/plugins/notes.py
+++ b/misskaty/plugins/notes.py
@@ -60,9 +60,7 @@ async def save_notee(_, message):
_type = "text" if message.reply_to_message.text else "sticker"
note = {
"type": _type,
- "data": message.reply_to_message.text.markdown
- if _type == "text"
- else message.reply_to_message.sticker.file_id,
+ "data": message.reply_to_message.text.markdown if _type == "text" else message.reply_to_message.sticker.file_id,
}
message.text.split()[0][0]
chat_id = message.chat.id
diff --git a/misskaty/plugins/ocr.py b/misskaty/plugins/ocr.py
index 72d4f144..477c7694 100644
--- a/misskaty/plugins/ocr.py
+++ b/misskaty/plugins/ocr.py
@@ -24,9 +24,7 @@ __HELP__ = "/ocr [reply to photo] - Read Text From Image"
async def ocr(_, message):
reply = message.reply_to_message
if not reply or not reply.photo and not reply.sticker:
- return await message.reply_text(
- f"Reply photo with /{message.command[0]} command"
- )
+ return await message.reply_text(f"Reply photo with /{message.command[0]} command")
msg = await message.reply("Reading image...")
try:
file_path = await reply.download()
diff --git a/misskaty/plugins/paste.py b/misskaty/plugins/paste.py
index c71627db..271a709e 100644
--- a/misskaty/plugins/paste.py
+++ b/misskaty/plugins/paste.py
@@ -66,18 +66,14 @@ async def create(_, message):
reply = message.reply_to_message
target = str(message.command[0]).split("@", maxsplit=1)[0]
if not reply and len(message.command) < 2:
- return await message.reply_text(
- f"**Reply To A Message With /{target} or with command**"
- )
+ return await message.reply_text(f"**Reply To A Message With /{target} or with command**")
msg = await message.reply_text("`Pasting to Rentry...`")
data = ""
limit = 1024 * 1024
if reply and reply.document:
if reply.document.file_size > limit:
- return await msg.edit(
- f"**You can only paste files smaller than {humanbytes(limit)}.**"
- )
+ return await msg.edit(f"**You can only paste files smaller than {humanbytes(limit)}.**")
if not pattern.search(reply.document.mime_type):
return await msg.edit("**Only text files can be pasted.**")
file = await reply.download()
@@ -100,9 +96,7 @@ async def create(_, message):
if message.from_user.username:
uname = f"@{message.from_user.username}"
else:
- uname = (
- f"[{message.from_user.first_name}](tg://user?id={message.from_user.id})"
- )
+ uname = f"[{message.from_user.first_name}](tg://user?id={message.from_user.id})"
else:
uname = message.sender_chat.title
@@ -116,11 +110,7 @@ async def create(_, message):
return await msg.edit("Text Too Short Or File Problems")
button = [
[InlineKeyboardButton("Open Link", url=url)],
- [
- InlineKeyboardButton(
- "Share Link", url=f"https://telegram.me/share/url?url={url}"
- )
- ],
+ [InlineKeyboardButton("Share Link", url=f"https://telegram.me/share/url?url={url}")],
]
pasted = f"**Successfully pasted your data to Rentry.\n\nPaste by {uname}**"
@@ -132,18 +122,14 @@ async def create(_, message):
reply = message.reply_to_message
target = str(message.command[0]).split("@", maxsplit=1)[0]
if not reply and len(message.command) < 2:
- return await message.reply_text(
- f"**Reply To A Message With /{target} or with command**"
- )
+ return await message.reply_text(f"**Reply To A Message With /{target} or with command**")
msg = await message.reply_text("`Pasting to TempPaste...`")
data = ""
limit = 1024 * 1024
if reply and reply.document:
if reply.document.file_size > limit:
- return await msg.edit(
- f"**You can only paste files smaller than {humanbytes(limit)}.**"
- )
+ return await msg.edit(f"**You can only paste files smaller than {humanbytes(limit)}.**")
if not pattern.search(reply.document.mime_type):
return await msg.edit("**Only text files can be pasted.**")
file = await reply.download()
@@ -166,9 +152,7 @@ async def create(_, message):
if message.from_user.username:
uname = f"@{message.from_user.username}"
else:
- uname = (
- f"[{message.from_user.first_name}](tg://user?id={message.from_user.id})"
- )
+ uname = f"[{message.from_user.first_name}](tg://user?id={message.from_user.id})"
else:
uname = message.sender_chat.title
@@ -193,11 +177,7 @@ async def create(_, message):
return await msg.edit("Text Too Short Or File Problems")
button = [
[InlineKeyboardButton("Open Link", url=url)],
- [
- InlineKeyboardButton(
- "Share Link", url=f"https://telegram.me/share/url?url={url}"
- )
- ],
+ [InlineKeyboardButton("Share Link", url=f"https://telegram.me/share/url?url={url}")],
]
pasted = f"**Successfully pasted your data to Tempaste.\n\nPaste by {uname}**"
diff --git a/misskaty/plugins/ping.py b/misskaty/plugins/ping.py
index d05ee225..08acd06b 100644
--- a/misskaty/plugins/ping.py
+++ b/misskaty/plugins/ping.py
@@ -25,9 +25,7 @@ async def ping(_, message):
end_t = time.time()
time_taken_s = round(end_t - start_t, 3)
try:
- await rm.edit(
- f"๐ MissKatyBot online.\n\nPing: {time_taken_s} detik\nUptime: {currentTime}"
- )
+ await rm.edit(f"๐ MissKatyBot online.\n\nPing: {time_taken_s} detik\nUptime: {currentTime}")
except Exception:
pass
@@ -53,9 +51,7 @@ async def ping_handler(_, message):
check=True,
capture_output=True,
)
- resp_time = findall(r"time=.+m?s", shell.stdout, MULTILINE)[0].replace(
- "time=", ""
- )
+ resp_time = findall(r"time=.+m?s", shell.stdout, MULTILINE)[0].replace("time=", "")
text += f" **{dc.upper()}:** {resp_time} โ
\n"
except Exception:
diff --git a/misskaty/plugins/quotly.py b/misskaty/plugins/quotly.py
index 9a036390..5cca75e4 100644
--- a/misskaty/plugins/quotly.py
+++ b/misskaty/plugins/quotly.py
@@ -40,11 +40,7 @@ async def get_message_sender_name(m: Message):
if m.forward_sender_name:
return m.forward_sender_name
elif m.forward_from:
- return (
- f"{m.forward_from.first_name} {m.forward_from.last_name}"
- if m.forward_from.last_name
- else m.forward_from.first_name
- )
+ return f"{m.forward_from.first_name} {m.forward_from.last_name}" if m.forward_from.last_name else m.forward_from.first_name
elif m.forward_from_chat:
return m.forward_from_chat.title
@@ -63,42 +59,22 @@ async def get_message_sender_name(m: Message):
async def get_custom_emoji(m: Message):
if m.forward_date:
- return (
- ""
- if m.forward_sender_name
- or not m.forward_from
- and m.forward_from_chat
- or not m.forward_from
- else m.forward_from.emoji_status.custom_emoji_id
- )
+ return "" if m.forward_sender_name or not m.forward_from and m.forward_from_chat or not m.forward_from else m.forward_from.emoji_status.custom_emoji_id
return m.from_user.emoji_status.custom_emoji_id if m.from_user else ""
async def get_message_sender_username(m: Message):
if m.forward_date:
- if (
- not m.forward_sender_name
- and not m.forward_from
- and m.forward_from_chat
- and m.forward_from_chat.username
- ):
+ if not m.forward_sender_name and not m.forward_from and m.forward_from_chat and m.forward_from_chat.username:
return m.forward_from_chat.username
- elif (
- not m.forward_sender_name
- and not m.forward_from
- and m.forward_from_chat
- or m.forward_sender_name
- or not m.forward_from
- ):
+ elif not m.forward_sender_name and not m.forward_from and m.forward_from_chat or m.forward_sender_name or not m.forward_from:
return ""
else:
return m.forward_from.username or ""
elif m.from_user and m.from_user.username:
return m.from_user.username
- elif (
- m.from_user or m.sender_chat and not m.sender_chat.username or not m.sender_chat
- ):
+ elif m.from_user or m.sender_chat and not m.sender_chat.username or not m.sender_chat:
return ""
else:
return m.sender_chat.username
@@ -106,25 +82,14 @@ async def get_message_sender_username(m: Message):
async def get_message_sender_photo(m: Message):
if m.forward_date:
- if (
- not m.forward_sender_name
- and not m.forward_from
- and m.forward_from_chat
- and m.forward_from_chat.photo
- ):
+ if not m.forward_sender_name and not m.forward_from and m.forward_from_chat and m.forward_from_chat.photo:
return {
"small_file_id": m.forward_from_chat.photo.small_file_id,
"small_photo_unique_id": m.forward_from_chat.photo.small_photo_unique_id,
"big_file_id": m.forward_from_chat.photo.big_file_id,
"big_photo_unique_id": m.forward_from_chat.photo.big_photo_unique_id,
}
- elif (
- not m.forward_sender_name
- and not m.forward_from
- and m.forward_from_chat
- or m.forward_sender_name
- or not m.forward_from
- ):
+ elif not m.forward_sender_name and not m.forward_from and m.forward_from_chat or m.forward_sender_name or not m.forward_from:
return ""
else:
return (
@@ -202,16 +167,10 @@ async def pyrogram_to_quotly(messages):
the_message_dict_to_append["avatar"] = True
the_message_dict_to_append["from"] = {}
the_message_dict_to_append["from"]["id"] = await get_message_sender_id(message)
- the_message_dict_to_append["from"]["name"] = await get_message_sender_name(
- message
- )
- the_message_dict_to_append["from"][
- "username"
- ] = await get_message_sender_username(message)
+ the_message_dict_to_append["from"]["name"] = await get_message_sender_name(message)
+ the_message_dict_to_append["from"]["username"] = await get_message_sender_username(message)
the_message_dict_to_append["from"]["type"] = message.chat.type.name.lower()
- the_message_dict_to_append["from"]["photo"] = await get_message_sender_photo(
- message
- )
+ the_message_dict_to_append["from"]["photo"] = await get_message_sender_photo(message)
if message.reply_to_message:
the_message_dict_to_append["replyMessage"] = {
"name": await get_message_sender_name(message.reply_to_message),
@@ -267,9 +226,7 @@ async def msg_quotly_cmd(c: Client, m: Message):
except Exception:
return await m.reply_text("๐คท๐ปโโ๏ธ")
try:
- messages_one = await c.get_messages(
- chat_id=m.chat.id, message_ids=m.reply_to_message.id, replies=-1
- )
+ messages_one = await c.get_messages(chat_id=m.chat.id, message_ids=m.reply_to_message.id, replies=-1)
messages = [messages_one]
except Exception:
return await m.reply_text("๐คท๐ปโโ๏ธ")
diff --git a/misskaty/plugins/scrapwebsite.py b/misskaty/plugins/scrapwebsite.py
index b3cbf35a..763465f5 100644
--- a/misskaty/plugins/scrapwebsite.py
+++ b/misskaty/plugins/scrapwebsite.py
@@ -34,9 +34,7 @@ __HELP__ = """
LOGGER = getLogger(__name__)
-headers = {
- "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
-}
+headers = {"User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"}
@app.on_message(filters.command(["zonafilm"], COMMAND_HANDLER))
@@ -53,10 +51,10 @@ async def zonafilm(_, msg):
entry = text.find_all(class_="entry-header")
if "Nothing Found" in entry[0].text:
await m.delete()
- if title != "":
- await msg.reply(f"404 Not FOUND For: {title}", True)
+ if not title:
+ await msg.reply("404 Not FOUND!", True)
else:
- await msg.reply(f"404 Not FOUND!", True)
+ await msg.reply(f"404 Not FOUND For: {title}", True)
return
data = []
for i in entry:
@@ -65,19 +63,12 @@ async def zonafilm(_, msg):
judul = i.find(class_="entry-title").find("a").text
link = i.find(class_="entry-title").find("a").get("href")
data.append({"judul": judul, "link": link, "genre": genre})
- if title != "":
- head = f"#Zonafilm Results For: {title}\n\n"
- else:
- head = f"#Zonafilm Latest:\n๐ Use /{msg.command[0]} [title] to start search with title.\n\n"
+ head = f"#Zonafilm Results For: {title}\n\n" if title else f"#Zonafilm Latest:\n๐ Use /{msg.command[0]} [title] to start search with title.\n\n"
msgs = ""
await m.delete()
for c, i in enumerate(data, start=1):
msgs += f"{c}. {i['judul']}\nGenre: {i['genre']}\n"
- msgs += (
- f"Extract: /{msg.command[0]}_scrap {i['link']}\n\n"
- if "/tv/" not in i["link"]
- else "\n"
- )
+ msgs += f"Extract: /{msg.command[0]}_scrap {i['link']}\n\n" if "/tv/" not in i["link"] else "\n"
if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
await msg.reply(
head + msgs,
@@ -132,10 +123,10 @@ async def nodrakor(_, msg):
entry = text.find_all(class_="entry-header")
if "Nothing Found" in entry[0].text:
await m.delete()
- if title != "":
- await msg.reply(f"404 Not FOUND For: {title}", True)
+ if not title:
+ await msg.reply("404 Not FOUND!", True)
else:
- await msg.reply(f"404 Not FOUND!", True)
+ await msg.reply(f"404 Not FOUND For: {title}", True)
return
data = []
for i in entry:
@@ -144,10 +135,7 @@ async def nodrakor(_, msg):
judul = i.find(class_="entry-title").find("a").text
link = i.find(class_="entry-title").find("a").get("href")
data.append({"judul": judul, "link": link, "genre": genre})
- if title != "":
- head = f"#Nodrakor Results For: {title}\n\n"
- else:
- head = f"#Nodrakor Latest:\n๐ Use /{msg.command[0]} [title] to start search with title.\n\n"
+ head = f"#Nodrakor Results For: {title}\n\n" if title else f"#Nodrakor Latest:\n๐ Use /{msg.command[0]} [title] to start search with title.\n\n"
msgs = ""
await m.delete()
for c, i in enumerate(data, start=1):
@@ -225,7 +213,7 @@ async def movikucc(_, msg):
data = []
if len(msg.command) == 1:
try:
- html = await http.get(f"https://107.152.37.223/")
+ html = await http.get("https://107.152.37.223/")
r = BeautifulSoup(html.text, "lxml")
res = r.find_all(class_="bx")
for i in res:
@@ -361,43 +349,6 @@ async def savefilm21(_, msg):
return await msg.reply("404 Result not FOUND!", True)
await m.delete()
head = f"#SaveFilm21 Results For: {title}\n\n"
- msgs = ""
- for c, i in enumerate(data, start=1):
- msgs += f"{c}. {i['judul']}\nExtract: /{msg.command[0]}_scrap {i['link']}\n\n"
- if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
- await msg.reply(
- head + msgs,
- True,
- disable_web_page_preview=True,
- reply_markup=InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- text="โ Close",
- callback_data=f"close#{msg.from_user.id}",
- )
- ]
- ]
- ),
- )
- await asyncio.sleep(2)
- msgs = ""
- if msgs != "":
- await msg.reply(
- head + msgs,
- True,
- disable_web_page_preview=True,
- reply_markup=InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- text="โ Close",
- callback_data=f"close#{msg.from_user.id}",
- )
- ]
- ]
- ),
- )
else:
html = await http.get(SITE, headers=headers)
bs4 = BeautifulSoup(html.text, "lxml")
@@ -409,28 +360,10 @@ async def savefilm21(_, msg):
data.append({"judul": judul, "link": link})
await m.delete()
head = f"#SaveFilm21 Latest:\n๐ Use /{msg.command[0]} [title] to start search with title.\n\n"
- msgs = ""
- for c, i in enumerate(data, start=1):
- msgs += f"{c}. {i['judul']}\nExtract: /{msg.command[0]}_scrap {i['link']}\n\n"
- if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
- await msg.reply(
- head + msgs,
- True,
- disable_web_page_preview=True,
- reply_markup=InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- text="โ Close",
- callback_data=f"close#{msg.from_user.id}",
- )
- ]
- ]
- ),
- )
- await asyncio.sleep(2)
- msgs = ""
- if msgs != "":
+ msgs = ""
+ for c, i in enumerate(data, start=1):
+ msgs += f"{c}. {i['judul']}\nExtract: /{msg.command[0]}_scrap {i['link']}\n\n"
+ if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
await msg.reply(
head + msgs,
True,
@@ -446,6 +379,24 @@ async def savefilm21(_, msg):
]
),
)
+ await asyncio.sleep(2)
+ msgs = ""
+ if msgs != "":
+ await msg.reply(
+ head + msgs,
+ True,
+ disable_web_page_preview=True,
+ reply_markup=InlineKeyboardMarkup(
+ [
+ [
+ InlineKeyboardButton(
+ text="โ Close",
+ callback_data=f"close#{msg.from_user.id}",
+ )
+ ]
+ ]
+ ),
+ )
except Exception as e:
await m.delete()
LOGGER.error(e)
@@ -593,11 +544,7 @@ async def pahe_scrap(_, msg):
if not res["result"]:
await m.delete()
return await msg.reply("404 Result not FOUND!", True)
- head = (
- f"#Pahe Results For: {title}\n\n"
- if title
- else f"#Pahe Latest:\n๐ Use /{msg.command[0]} [title] to start search with title.\n\n"
- )
+ head = f"#Pahe Results For: {title}\n\n" if title else f"#Pahe Latest:\n๐ Use /{msg.command[0]} [title] to start search with title.\n\n"
await m.delete()
msgs = ""
for c, i in enumerate(res["result"], start=1):
@@ -658,11 +605,7 @@ async def terbit21_scrap(_, msg):
msgs = ""
for c, i in enumerate(res["result"], start=1):
msgs += f"{c}. {i['judul']}\nCategory: {i['kategori']}\n"
- msgs += (
- f"๐ Download\n\n"
- if not re.search(r"Complete|Ongoing", i["kategori"])
- else "\n"
- )
+ msgs += "\n" if re.search(r"Complete|Ongoing", i["kategori"]) else f"๐ Download\n\n"
if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
await msg.reply(
head + msgs,
@@ -714,11 +657,7 @@ async def terbit21_scrap(_, msg):
msgs = ""
for c, i in enumerate(res["result"], start=1):
msgs += f"{c}. {i['judul']}\nCategory: {i['kategori']}\n"
- msgs += (
- f"๐ Download\n\n"
- if not re.search(r"Complete|Ongoing", i["kategori"])
- else "\n"
- )
+ msgs += "\n" if re.search(r"Complete|Ongoing", i["kategori"]) else f"๐ Download\n\n"
if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
await msg.reply(
head + msgs,
@@ -778,11 +717,7 @@ async def lk21_scrap(_, msg):
msgs = ""
for c, i in enumerate(res["result"], start=1):
msgs += f"{c}. {i['judul']}\nCategory: {i['kategori']}\n"
- msgs += (
- f"๐ Download\n\n"
- if not re.search(r"Complete|Ongoing", i["kategori"])
- else "\n"
- )
+ msgs += "\n" if re.search(r"Complete|Ongoing", i["kategori"]) else f"๐ Download\n\n"
if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
await msg.reply(
head + msgs,
@@ -837,11 +772,7 @@ async def lk21_scrap(_, msg):
msgs = ""
for c, i in enumerate(res["result"], start=1):
msgs += f"{c}. {i['judul']}\nCategory: {i['kategori']}\n"
- msgs += (
- f"๐ Download\n\n"
- if not re.search(r"Complete|Ongoing", i["kategori"])
- else "\n"
- )
+ msgs += "\n" if re.search(r"Complete|Ongoing", i["kategori"]) else f"๐ Download\n\n"
if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
await msg.reply(
head + msgs,
@@ -896,10 +827,10 @@ async def gomov_scrap(_, msg):
entry = text.find_all(class_="entry-header")
if "Nothing Found" in entry[0].text:
await m.delete()
- if title != "":
- await msg.reply(f"404 Not FOUND For: {title}", True)
+ if not title:
+ await msg.reply("404 Not FOUND!", True)
else:
- await msg.reply(f"404 Not FOUND!", True)
+ await msg.reply(f"404 Not FOUND For: {title}", True)
return
data = []
for i in entry:
@@ -908,19 +839,12 @@ async def gomov_scrap(_, msg):
judul = i.find(class_="entry-title").find("a").text
link = i.find(class_="entry-title").find("a").get("href")
data.append({"judul": judul, "link": link, "genre": genre})
- if title != "":
- head = f"#Gomov Results For: {title}\n\n"
- else:
- head = f"#Gomov Latest:\n๐ Use /{msg.command[0]} [title] to start search with title.\n\n"
+ head = f"#Gomov Results For: {title}\n\n" if title else f"#Gomov Latest:\n๐ Use /{msg.command[0]} [title] to start search with title.\n\n"
msgs = ""
await m.delete()
for c, i in enumerate(data, start=1):
msgs += f"{c}. {i['judul']}\nGenre: {i['genre']}\n"
- msgs += (
- f"Extract: /{msg.command[0]}_scrap {i['link']}\n\n"
- if not re.search(r"Series", i["genre"])
- else "\n"
- )
+ msgs += "\n" if re.search(r"Series", i["genre"]) else f"Extract: /{msg.command[0]}_scrap {i['link']}\n\n"
if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
await msg.reply(
head + msgs,
@@ -966,9 +890,7 @@ async def gomov_scrap(_, msg):
async def savefilm21_scrap(_, message):
try:
link = message.text.split(" ", maxsplit=1)[1]
- headers = {
- "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
- }
+ headers = {"User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"}
html = await http.get(link, headers=headers)
soup = BeautifulSoup(html.text, "lxml")
@@ -989,9 +911,7 @@ async def savefilm21_scrap(_, message):
),
)
except IndexError:
- return await message.reply(
- f"Gunakan command /{message.command[0]} [link] untuk scrap link download"
- )
+ return await message.reply(f"Gunakan command /{message.command[0]} [link] untuk scrap link download")
except Exception as e:
await message.reply(f"ERROR: {str(e)}")
@@ -1001,18 +921,14 @@ async def savefilm21_scrap(_, message):
async def nodrakor_scrap(_, message):
try:
link = message.text.split(" ", maxsplit=1)[1]
- headers = {
- "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
- }
+ headers = {"User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"}
html = await http.get(link, headers=headers)
soup = BeautifulSoup(html.text, "lxml")
hasil = soup.find_all(class_="gmr-download-wrap clearfix")[0]
await message.reply(f"Hasil Scrap dari {link}:\n{hasil}")
except IndexError:
- return await message.reply(
- f"Gunakan command /{message.command[0]} [link] untuk scrap link download"
- )
+ return await message.reply(f"Gunakan command /{message.command[0]} [link] untuk scrap link download")
except Exception as e:
await message.reply(f"ERROR: {str(e)}")
@@ -1023,9 +939,7 @@ async def nodrakor_scrap(_, message):
async def muviku_scrap(_, message):
try:
link = message.text.split(" ", maxsplit=1)[1]
- headers = {
- "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
- }
+ headers = {"User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"}
html = await http.get(link, headers=headers)
soup = BeautifulSoup(html.text, "lxml")
@@ -1042,9 +956,7 @@ async def muviku_scrap(_, message):
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(
- f"Gunakan command /{message.command[0]} [link] untuk scrap link download"
- )
+ return await message.reply(f"Gunakan command /{message.command[0]} [link] untuk scrap link download")
except Exception as e:
await message.reply(f"ERROR: {str(e)}")
@@ -1054,9 +966,7 @@ async def muviku_scrap(_, message):
async def melong_scrap(_, message):
try:
link = message.text.split(" ", maxsplit=1)[1]
- headers = {
- "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
- }
+ headers = {"User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"}
html = await http.get(link, headers=headers)
soup = BeautifulSoup(html.text, "lxml")
@@ -1066,9 +976,7 @@ async def melong_scrap(_, message):
rep = f"{hardsub}\n{softsub}"
await message.reply(rep)
except IndexError:
- await message.reply(
- f"Gunakan command /{message.command[0]} [link] untuk scrap link download"
- )
+ await message.reply(f"Gunakan command /{message.command[0]} [link] untuk scrap link download")
@app.on_message(filters.command(["gomov_scrap", "zonafilm_scrap"], COMMAND_HANDLER))
@@ -1076,9 +984,7 @@ async def melong_scrap(_, message):
async def gomov_zonafilm_dl(_, message):
try:
link = message.text.split(" ", maxsplit=1)[1]
- headers = {
- "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
- }
+ headers = {"User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"}
html = await http.get(link, headers=headers)
soup = BeautifulSoup(html.text, "lxml")
@@ -1102,6 +1008,4 @@ async def gomov_zonafilm_dl(_, message):
),
)
except IndexError:
- await message.reply(
- f"Gunakan command /{message.command[0]} [link] untuk scrap link download"
- )
+ await message.reply(f"Gunakan command /{message.command[0]} [link] untuk scrap link download")
diff --git a/misskaty/plugins/sed.py b/misskaty/plugins/sed.py
index d2a3c7a6..7a40d630 100644
--- a/misskaty/plugins/sed.py
+++ b/misskaty/plugins/sed.py
@@ -34,9 +34,7 @@ async def sed(c: app, m: Message):
return
try:
- res = regex.sub(
- pattern, replace_with, text, count=count, flags=rflags, timeout=1
- )
+ res = regex.sub(pattern, replace_with, text, count=count, flags=rflags, timeout=1)
except TimeoutError:
return await m.reply_text("Oops, your regex pattern has run for too long.")
except regex.error as e:
diff --git a/misskaty/plugins/stickers.py b/misskaty/plugins/stickers.py
index 371aca95..3d7fa5e9 100644
--- a/misskaty/plugins/stickers.py
+++ b/misskaty/plugins/stickers.py
@@ -37,11 +37,7 @@ __HELP__ = """
def get_emoji_regex():
- e_list = [
- getattr(emoji, e).encode("unicode-escape").decode("ASCII")
- for e in dir(emoji)
- if not e.startswith("_")
- ]
+ e_list = [getattr(emoji, e).encode("unicode-escape").decode("ASCII") for e in dir(emoji) if not e.startswith("_")]
# to avoid re.error excluding char that start with '*'
e_sort = sorted([x for x in e_list if not x.startswith("*")], reverse=True)
# Sort emojis by length to make sure multi-character emojis are
@@ -56,12 +52,10 @@ SUPPORTED_TYPES = ["jpeg", "png", "webp"]
@app.on_message(filters.command(["getsticker"], COMMAND_HANDLER))
async def getsticker_(c, m):
- sticker = m.reply_to_message.sticker
-
- if sticker:
+ if sticker := m.reply_to_message.sticker:
if sticker.is_animated:
await m.reply_text("Animated sticker is not supported!")
- elif not sticker.is_animated:
+ else:
with tempfile.TemporaryDirectory() as tempdir:
path = os.path.join(tempdir, "getsticker")
sticker_file = await c.download_media(
@@ -70,11 +64,7 @@ async def getsticker_(c, m):
)
await m.reply_to_message.reply_document(
document=sticker_file,
- caption=(
- f"Emoji: {sticker.emoji}\n"
- f"Sticker ID: {sticker.file_id}\n\n"
- f"Send by: @{BOT_USERNAME}"
- ),
+ caption=(f"Emoji: {sticker.emoji}\n" f"Sticker ID: {sticker.file_id}\n\n" f"Send by: @{BOT_USERNAME}"),
)
shutil.rmtree(tempdir, ignore_errors=True)
else:
@@ -84,11 +74,7 @@ async def getsticker_(c, m):
@app.on_message(filters.command("stickerid", COMMAND_HANDLER) & filters.reply)
async def getstickerid(c, m):
if m.reply_to_message.sticker:
- await m.reply_text(
- "The ID of this sticker is: {stickerid}".format(
- stickerid=m.reply_to_message.sticker.file_id
- )
- )
+ await m.reply_text("The ID of this sticker is: {stickerid}".format(stickerid=m.reply_to_message.sticker.file_id))
@app.on_message(filters.command("unkang", COMMAND_HANDLER) & filters.reply)
@@ -107,9 +93,7 @@ async def getstickerid(c, m):
except Exception as e:
await pp.edit(f"Failed remove sticker from your pack.\n\nERR: {e}")
else:
- await m.reply_text(
- f"Please reply sticker that created by {c.me.username} to remove sticker from your pack."
- )
+ await m.reply_text(f"Please reply sticker that created by {c.me.username} to remove sticker from your pack.")
@app.on_message(filters.command(["curi", "kang"], COMMAND_HANDLER))
@@ -173,10 +157,7 @@ async def kang_sticker(c, m):
packname = f"{pack_prefix}{packnum}_{m.from_user.id}_by_{c.me.username}"
if len(m.command) > 1:
# matches all valid emojis in input
- sticker_emoji = (
- "".join(set(EMOJI_PATTERN.findall("".join(m.command[1:]))))
- or sticker_emoji
- )
+ sticker_emoji = "".join(set(EMOJI_PATTERN.findall("".join(m.command[1:])))) or sticker_emoji
filename = await c.download_media(m.reply_to_message)
if not filename:
# Failed to download
@@ -187,11 +168,7 @@ async def kang_sticker(c, m):
filename = "sticker.png"
packname = f"c{m.from_user.id}_by_{c.me.username}"
img_url = next(
- (
- m.text[y.offset : (y.offset + y.length)]
- for y in m.entities
- if y.type == "url"
- ),
+ (m.text[y.offset : (y.offset + y.length)] for y in m.entities if y.type == "url"),
None,
)
@@ -211,15 +188,10 @@ async def kang_sticker(c, m):
packnum = m.command.pop(2)
packname = f"a{packnum}_{m.from_user.id}_by_{c.me.username}"
if len(m.command) > 2:
- sticker_emoji = (
- "".join(set(EMOJI_PATTERN.findall("".join(m.command[2:]))))
- or sticker_emoji
- )
+ sticker_emoji = "".join(set(EMOJI_PATTERN.findall("".join(m.command[2:])))) or sticker_emoji
resize = True
else:
- return await prog_msg.edit_text(
- "Want me to guess the sticker? Please tag a sticker."
- )
+ return await prog_msg.edit_text("Want me to guess the sticker? Please tag a sticker.")
try:
if resize:
filename = resize_image(filename)
@@ -238,9 +210,7 @@ async def kang_sticker(c, m):
)
if stickerset.set.count >= max_stickers:
packnum += 1
- packname = (
- f"{pack_prefix}_{packnum}_{m.from_user.id}_by_{c.me.username}"
- )
+ packname = f"{pack_prefix}_{packnum}_{m.from_user.id}_by_{c.me.username}"
else:
packname_found = True
except StickersetInvalid:
@@ -320,9 +290,7 @@ async def kang_sticker(c, m):
)
except BadRequest:
- return await prog_msg.edit_text(
- "Your Sticker Pack is full if your pack is not in v1 Type /kang 1, if it is not in v2 Type /kang 2 and so on."
- )
+ return await prog_msg.edit_text("Your Sticker Pack is full if your pack is not in v1 Type /kang 1, if it is not in v2 Type /kang 2 and so on.")
except Exception as all_e:
await prog_msg.edit_text(f"{all_e.__class__.__name__} : {all_e}")
else:
diff --git a/misskaty/plugins/sub_extractor.py b/misskaty/plugins/sub_extractor.py
index 51d1f54e..0087cba4 100644
--- a/misskaty/plugins/sub_extractor.py
+++ b/misskaty/plugins/sub_extractor.py
@@ -64,18 +64,12 @@ def get_subname(lang, url, format):
async def ceksub(_, m):
cmd = m.text.split(" ", 1)
if len(cmd) == 1:
- return await m.reply(
- f"Gunakan command /{m.command[0]} [link] untuk mengecek subtitle dan audio didalam video."
- )
+ return await m.reply(f"Gunakan command /{m.command[0]} [link] untuk mengecek subtitle dan audio didalam video.")
link = cmd[1]
start_time = perf_counter()
pesan = await m.reply("Sedang memproses perintah..", quote=True)
try:
- res = (
- await shell_exec(
- f"ffprobe -loglevel 0 -print_format json -show_format -show_streams {link}"
- )
- )[0]
+ res = (await shell_exec(f"ffprobe -loglevel 0 -print_format json -show_format -show_streams {link}"))[0]
details = json.loads(res)
buttons = []
for stream in details["streams"]:
@@ -108,32 +102,19 @@ async def ceksub(_, m):
)
except Exception:
traceback.format_exc()
- await pesan.edit(
- f"Failed extract media, make sure your link is not protected by WAF or maybe inaccessible for bot."
- )
+ await pesan.edit("Failed extract media, make sure your link is not protected by WAF or maybe inaccessible for bot.")
@app.on_message(filters.command(["converttosrt"], COMMAND_HANDLER))
@capture_err
async def convertsrt(c, m):
reply = m.reply_to_message
- if (
- not reply
- and reply.document
- and (
- reply.document.file_name.endswith(".vtt")
- or reply.document.file_name.endswith(".ass")
- )
- ):
- return await m.reply(
- f"Use command /{m.command[0]} by reply to .ass or .vtt file, to convert subtitle from .ass or .vtt to srt."
- )
+ if not reply and reply.document and (reply.document.file_name.endswith(".vtt") or reply.document.file_name.endswith(".ass")):
+ return await m.reply(f"Use command /{m.command[0]} by reply to .ass or .vtt file, to convert subtitle from .ass or .vtt to srt.")
msg = await m.reply("โณ Converting...")
dl = await reply.download()
filename = dl.split("/", 3)[3]
- LOGGER.info(
- f"ConvertSub: {filename} by {m.from_user.first_name} [{m.from_user.id}]"
- )
+ LOGGER.info(f"ConvertSub: {filename} by {m.from_user.first_name} [{m.from_user.id}]")
(await shell_exec(f"mediaextract -i '{dl}' '{filename}.srt'"))[0]
c_time = time()
await m.reply_document(
@@ -173,12 +154,8 @@ async def stream_extract(bot, update):
format = "srt"
start_time = perf_counter()
namafile = get_subname(lang, link, format)
- LOGGER.info(
- f"ExtractSub: {namafile} by {update.from_user.first_name} [{update.from_user.id}]"
- )
- extract = (await shell_exec(f"mediaextract -i {link} -map {map} '{namafile}'"))[
- 0
- ]
+ LOGGER.info(f"ExtractSub: {namafile} by {update.from_user.first_name} [{update.from_user.id}]")
+ extract = (await shell_exec(f"mediaextract -i {link} -map {map} '{namafile}'"))[0]
end_time = perf_counter()
timelog = "{:.2f}".format(end_time - start_time) + " second"
c_time = time()
@@ -195,6 +172,4 @@ async def stream_extract(bot, update):
except:
pass
except Exception as e:
- await update.message.edit(
- f"Failed extract sub, Maybe unsupported format..\n\nLink: {link}\nERR: {e}"
- )
+ await update.message.edit(f"Failed extract sub, Maybe unsupported format..\n\nLink: {link}\nERR: {e}")
diff --git a/misskaty/plugins/ubot_plugin.py b/misskaty/plugins/ubot_plugin.py
index 7cd02df8..b42dd6f5 100644
--- a/misskaty/plugins/ubot_plugin.py
+++ b/misskaty/plugins/ubot_plugin.py
@@ -41,22 +41,12 @@ async def add_keep(_, message: Message):
# @user.on_deleted_messages(filters.chat([-1001455886928, -1001255283935]))
async def del_msg(client, message):
- async for a in user.get_chat_event_log(
- message[0].chat.id, limit=1, filters=ChatEventFilter(deleted_messages=True)
- ):
+ async for a in user.get_chat_event_log(message[0].chat.id, limit=1, filters=ChatEventFilter(deleted_messages=True)):
try:
- ustat = (
- await user.get_chat_member(
- message[0].chat.id, a.deleted_message.from_user.id
- )
- ).status
+ ustat = (await user.get_chat_member(message[0].chat.id, a.deleted_message.from_user.id)).status
except:
ustat = enums.ChatMemberStatus.MEMBER
- if (
- ustat
- in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]
- or a.deleted_message.from_user.is_bot
- ):
+ if ustat in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER] or a.deleted_message.from_user.is_bot:
return
if a.user.id == a.deleted_message.from_user.id:
if a.deleted_message.text:
@@ -74,9 +64,7 @@ async def del_msg(client, message):
# @user.on_edited_message(filters.text & filters.chat(-1001455886928))
async def edit_msg(client, message):
try:
- ustat = (
- await user.get_chat_member(message.chat.id, message.from_user.id)
- ).status
+ ustat = (await user.get_chat_member(message.chat.id, message.from_user.id)).status
except:
ustat = enums.ChatMemberStatus.MEMBER
if message.from_user.is_bot or ustat in [
@@ -84,12 +72,8 @@ async def edit_msg(client, message):
enums.ChatMemberStatus.OWNER,
]:
return
- async for a in user.get_chat_event_log(
- message.chat.id, limit=1, filters=ChatEventFilter(edited_messages=True)
- ):
- if a.old_message.text.startswith(
- ("/mirror", "/leech", "/unzipmirror", "/unzipleech")
- ):
+ async for a in user.get_chat_event_log(message.chat.id, limit=1, filters=ChatEventFilter(edited_messages=True)):
+ if a.old_message.text.startswith(("/mirror", "/leech", "/unzipmirror", "/unzipleech")):
await app.send_message(
message.chat.id,
f"#EDITED_MESSAGE\n\n{a.user.first_name} mengedit pesannya ๐ง.\nPesan: {a.old_message.text}",
@@ -141,10 +125,7 @@ async def join_date(app, message: Message):
with open("joined_date.txt", "w", encoding="utf8") as f:
f.write("Join Date First Name\n")
for member in members:
- f.write(
- str(datetime.fromtimestamp(member[1]).strftime("%y-%m-%d %H:%M"))
- + f" {member[0]}\n"
- )
+ f.write(str(datetime.fromtimestamp(member[1]).strftime("%y-%m-%d %H:%M")) + f" {member[0]}\n")
await user.send_document(message.chat.id, "joined_date.txt")
os.remove("joined_date.txt")
@@ -171,9 +152,7 @@ async def recent_act(client, message):
limit=0,
)
)
- with open(
- f"recent_actions_{message.chat.id}.txt", "w", encoding="utf8"
- ) as log_file:
+ with open(f"recent_actions_{message.chat.id}.txt", "w", encoding="utf8") as log_file:
log_file.write(str(full_log))
await message.reply_document(f"recent_actions_{message.chat.id}.txt")
diff --git a/misskaty/plugins/webss.py b/misskaty/plugins/webss.py
index 306985e6..158518fe 100644
--- a/misskaty/plugins/webss.py
+++ b/misskaty/plugins/webss.py
@@ -22,11 +22,7 @@ __HELP__ = """
async def take_ss(_, message):
if len(message.command) == 1:
return await message.reply("Give A Url To Fetch Screenshot.")
- url = (
- message.command[1]
- if message.command[1].startswith("http")
- else f"https://{message.command[1]}"
- )
+ url = message.command[1] if message.command[1].startswith("http") else f"https://{message.command[1]}"
filename = f"imageToSave_{message.from_user.id}.png"
m = await message.reply("Capturing screenshot...")
try:
diff --git a/misskaty/plugins/ytdl_download_new.py b/misskaty/plugins/ytdl_download_new.py
index 48e1c477..04b3fd4b 100644
--- a/misskaty/plugins/ytdl_download_new.py
+++ b/misskaty/plugins/ytdl_download_new.py
@@ -17,9 +17,7 @@ from misskaty.helper.http import http
from misskaty.vars import COMMAND_HANDLER, LOG_CHANNEL
LOGGER = getLogger(__name__)
-regex = recompile(
- r"(https?://)?(www\.)?(youtube|youtu|youtube-nocookie)\.(com|be)/(watch\?v=|embed/|v/|.+\?v=)?(?P[A-Za-z0-9\-=_]{11})"
-)
+regex = recompile(r"(https?://)?(www\.)?(youtube|youtu|youtube-nocookie)\.(com|be)/(watch\?v=|embed/|v/|.+\?v=)?(?P[A-Za-z0-9\-=_]{11})")
YT_DB = {}
@@ -67,9 +65,7 @@ async def ytdownv2(_, message):
if len(message.command) == 1:
return await message.reply("Please input a valid YT-DLP Supported URL")
url = message.text.split(" ", maxsplit=1)[1]
- async with iYTDL(
- log_group_id=0, cache_path="cache", ffmpeg_location="/usr/bin/mediaextract"
- ) as ytdl:
+ async with iYTDL(log_group_id=0, cache_path="cache", ffmpeg_location="/usr/bin/mediaextract") as ytdl:
x = await ytdl.parse(url)
if x is None:
return await message.reply("Failed parse URL, check logs..")
@@ -84,13 +80,9 @@ async def ytdl_listall_callback(_, cq: CallbackQuery):
if cq.from_user.id != cq.message.reply_to_message.from_user.id:
return await cq.answer("Not your task", True)
callback = cq.data.split("|")
- async with iYTDL(
- log_group_id=0, cache_path="cache", ffmpeg_location="/usr/bin/mediaextract"
- ) as ytdl:
+ async with iYTDL(log_group_id=0, cache_path="cache", ffmpeg_location="/usr/bin/mediaextract") as ytdl:
media, buttons = await ytdl.listview(callback[1])
- await cq.edit_message_media(
- media=media, reply_markup=buttons.add(cq.from_user.id)
- )
+ await cq.edit_message_media(media=media, reply_markup=buttons.add(cq.from_user.id))
@app.on_callback_query(filters.regex(r"^yt_extract_info"))
@@ -99,9 +91,7 @@ async def ytdl_extractinfo_callback(_, cq: CallbackQuery):
return await cq.answer("Not your task", True)
await cq.answer("Please Wait...")
callback = cq.data.split("|")
- async with iYTDL(
- log_group_id=0, cache_path="cache", ffmpeg_location="/usr/bin/mediaextract"
- ) as ytdl:
+ async with iYTDL(log_group_id=0, cache_path="cache", ffmpeg_location="/usr/bin/mediaextract") as ytdl:
if data := await ytdl.extract_info_from_key(callback[1]):
if len(key) == 11:
await cq.edit_message_text(
@@ -127,36 +117,25 @@ async def ytdl_gendl_callback(_, cq: CallbackQuery):
callback = cq.data.split("|")
key = callback[1]
if callback[0] == "yt_gen":
- if (
- match := regex.match(cq.message.reply_to_message.command[1])
- or len(callback) == 2
- ):
+ if match := regex.match(cq.message.reply_to_message.command[1]) or len(callback) == 2:
x = await main.Extractor().get_download_button(key)
await cq.edit_message_caption(caption=x.caption, reply_markup=x.buttons)
else:
uid = callback[2]
type_ = callback[3]
- if type_ == "a":
- format_ = "audio"
- else:
- format_ = "video"
+ format_ = "audio" if type_ == "a" else "video"
async with iYTDL(
log_group_id=LOG_CHANNEL,
cache_path="cache",
ffmpeg_location="/usr/bin/mediaextract",
delete_media=True,
) as ytdl:
- upload_key = await ytdl.download(
- cq.message.reply_to_message.command[1], uid, format_, cq, True, 3
- )
+ upload_key = await ytdl.download(cq.message.reply_to_message.command[1], uid, format_, cq, True, 3)
await ytdl.upload(app, upload_key, format_, cq, True)
else:
uid = callback[2]
type_ = callback[3]
- if type_ == "a":
- format_ = "audio"
- else:
- format_ = "video"
+ format_ = "audio" if type_ == "a" else "video"
async with iYTDL(
log_group_id=LOG_CHANNEL,
cache_path="cache",
@@ -164,7 +143,12 @@ async def ytdl_gendl_callback(_, cq: CallbackQuery):
delete_media=True,
) as ytdl:
upload_key = await ytdl.download(
- "https://www.youtube.com/watch?v=" + key, uid, format_, cq, True, 3
+ f"https://www.youtube.com/watch?v={key}",
+ uid,
+ format_,
+ cq,
+ True,
+ 3,
)
await ytdl.upload(app, upload_key, format_, cq, True)
@@ -186,9 +170,7 @@ async def ytdl_scroll_callback(_, cq: CallbackQuery):
out += f"\nโฏ Uploader: {i['channel']['name']}\n\n"
scroll_btn = [
[
- InlineKeyboardButton(
- f"Back", callback_data=f"ytdl_scroll|{search_key}|{page-1}"
- ),
+ InlineKeyboardButton("Back", callback_data=f"ytdl_scroll|{search_key}|{page-1}"),
InlineKeyboardButton(
f"{page+1}/{len(search['result'])}",
callback_data=f"ytdl_scroll|{search_key}|{page+1}",
@@ -203,9 +185,7 @@ async def ytdl_scroll_callback(_, cq: CallbackQuery):
scroll_btn = [[scroll_btn.pop().pop(0)]]
btn = [[InlineKeyboardButton("Download", callback_data=f"yt_gen|{i['id']}")]]
btn = InlineKeyboardMarkup(scroll_btn + btn)
- await cq.edit_message_media(
- InputMediaPhoto(await get_ytthumb(i["id"]), caption=out), reply_markup=btn
- )
+ await cq.edit_message_media(InputMediaPhoto(await get_ytthumb(i["id"]), caption=out), reply_markup=btn)
async def get_ytthumb(videoid: str):
diff --git a/misskaty/vars.py b/misskaty/vars.py
index 4b8c5da3..49f810eb 100644
--- a/misskaty/vars.py
+++ b/misskaty/vars.py
@@ -54,13 +54,9 @@ FORWARD_FROM_CHAT_ID = list(
}
)
# Forward To Chat ID
-FORWARD_TO_CHAT_ID = list(
- {int(x) for x in environ.get("FORWARD_TO_CHAT_ID", "-1001210537567").split()}
-)
+FORWARD_TO_CHAT_ID = list({int(x) for x in environ.get("FORWARD_TO_CHAT_ID", "-1001210537567").split()})
FORWARD_FILTERS = list(set(environ.get("FORWARD_FILTERS", "video document").split()))
-BLOCK_FILES_WITHOUT_EXTENSIONS = bool(
- environ.get("BLOCK_FILES_WITHOUT_EXTENSIONS", True)
-)
+BLOCK_FILES_WITHOUT_EXTENSIONS = bool(environ.get("BLOCK_FILES_WITHOUT_EXTENSIONS", True))
BLOCKED_EXTENSIONS = list(
set(
environ.get(