Sourcery refactored master branch (#3)

* 'Refactored by Sourcery'

* reformating: code

Co-authored-by: Sourcery AI <>
Co-authored-by: yasirarism <mail@yasir.eu.org>
This commit is contained in:
sourcery-ai[bot] 2022-12-08 12:11:49 +07:00 committed by GitHub
parent e8e2b649ff
commit 983f3b50ca
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
47 changed files with 389 additions and 1306 deletions

View file

@ -47,9 +47,7 @@ async def is_afk(user_id: int) -> bool:
async def add_afk(user_id: int, mode): async def add_afk(user_id: int, mode):
await usersdb.update_one( await usersdb.update_one({"user_id": user_id}, {"$set": {"reason": mode}}, upsert=True)
{"user_id": user_id}, {"$set": {"reason": mode}}, upsert=True
)
async def remove_afk(user_id: int): async def remove_afk(user_id: int):

View file

@ -6,9 +6,7 @@ filtersdb = dbname.filters
async def _get_filters(chat_id: int) -> Dict[str, int]: async def _get_filters(chat_id: int) -> Dict[str, int]:
_filters = await filtersdb.find_one({"chat_id": chat_id}) _filters = await filtersdb.find_one({"chat_id": chat_id})
if not _filters: return _filters["filters"] if _filters else {}
return {}
return _filters["filters"]
async def delete_filter(chat_id: int, name: str) -> bool: async def delete_filter(chat_id: int, name: str) -> bool:
@ -28,9 +26,7 @@ async def delete_filter(chat_id: int, name: str) -> bool:
async def get_filter(chat_id: int, name: str) -> Union[bool, dict]: async def get_filter(chat_id: int, name: str) -> Union[bool, dict]:
name = name.lower().strip() name = name.lower().strip()
_filters = await _get_filters(chat_id) _filters = await _get_filters(chat_id)
if name in _filters: return _filters[name] if name in _filters else False
return _filters[name]
return False
async def get_filters_names(chat_id: int) -> List[str]: async def get_filters_names(chat_id: int) -> List[str]:

View file

@ -42,9 +42,7 @@ async def update_karma(chat_id: int, name: str, karma: dict):
name = name.lower().strip() name = name.lower().strip()
karmas = await get_karmas(chat_id) karmas = await get_karmas(chat_id)
karmas[name] = karma karmas[name] = karma
await karmadb.update_one( await karmadb.update_one({"chat_id": chat_id}, {"$set": {"karma": karmas}}, upsert=True)
{"chat_id": chat_id}, {"$set": {"karma": karmas}}, upsert=True
)
async def is_karma_on(chat_id: int) -> bool: async def is_karma_on(chat_id: int) -> bool:

View file

@ -6,9 +6,7 @@ notesdb = dbname.notes
async def _get_notes(chat_id: int) -> Dict[str, int]: async def _get_notes(chat_id: int) -> Dict[str, int]:
_notes = await notesdb.find_one({"chat_id": chat_id}) _notes = await notesdb.find_one({"chat_id": chat_id})
if not _notes: return _notes["notes"] if _notes else {}
return {}
return _notes["notes"]
async def delete_note(chat_id: int, name: str) -> bool: async def delete_note(chat_id: int, name: str) -> bool:
@ -28,9 +26,7 @@ async def delete_note(chat_id: int, name: str) -> bool:
async def get_note(chat_id: int, name: str) -> Union[bool, dict]: async def get_note(chat_id: int, name: str) -> Union[bool, dict]:
name = name.lower().strip() name = name.lower().strip()
_notes = await _get_notes(chat_id) _notes = await _get_notes(chat_id)
if name in _notes: return _notes[name] if name in _notes else False
return _notes[name]
return False
async def get_note_names(chat_id: int) -> List[str]: async def get_note_names(chat_id: int) -> List[str]:
@ -45,6 +41,4 @@ async def save_note(chat_id: int, name: str, note: dict):
_notes = await _get_notes(chat_id) _notes = await _get_notes(chat_id)
_notes[name] = note _notes[name] = note
await notesdb.update_one( await notesdb.update_one({"chat_id": chat_id}, {"$set": {"notes": _notes}}, upsert=True)
{"chat_id": chat_id}, {"$set": {"notes": _notes}}, upsert=True
)

View file

@ -79,18 +79,14 @@ class Database:
is_disabled=False, is_disabled=False,
reason="", reason="",
) )
await self.grp.update_one( await self.grp.update_one({"id": int(id)}, {"$set": {"chat_status": chat_status}})
{"id": int(id)}, {"$set": {"chat_status": chat_status}}
)
async def disable_chat(self, chat, reason="No Reason"): async def disable_chat(self, chat, reason="No Reason"):
chat_status = dict( chat_status = dict(
is_disabled=True, is_disabled=True,
reason=reason, reason=reason,
) )
await self.grp.update_one( await self.grp.update_one({"id": int(chat)}, {"$set": {"chat_status": chat_status}})
{"id": int(chat)}, {"$set": {"chat_status": chat_status}}
)
async def total_chat_count(self): async def total_chat_count(self):
return await self.grp.count_documents({}) return await self.grp.count_documents({})

View file

@ -31,9 +31,7 @@ async def add_warn(chat_id: int, name: str, warn: dict):
warns = await get_warns(chat_id) warns = await get_warns(chat_id)
warns[name] = warn warns[name] = warn
await warnsdb.update_one( await warnsdb.update_one({"chat_id": chat_id}, {"$set": {"warns": warns}}, upsert=True)
{"chat_id": chat_id}, {"$set": {"warns": warns}}, upsert=True
)
async def remove_warns(chat_id: int, name: str) -> bool: async def remove_warns(chat_id: int, name: str) -> bool:

View file

@ -40,4 +40,4 @@ BOT_NAME = bot.first_name
BOT_USERNAME = bot.username BOT_USERNAME = bot.username
UBOT_ID = ubot.id UBOT_ID = ubot.id
UBOT_NAME = ubot.first_name UBOT_NAME = ubot.first_name
UBOT_USERNAME = ubot.username UBOT_USERNAME = ubot.username

View file

@ -49,12 +49,7 @@ async def list_admins(chat_id: int):
admins_in_chat[chat_id] = { admins_in_chat[chat_id] = {
"last_updated_at": time(), "last_updated_at": time(),
"data": [ "data": [member.user.id async for member in app.get_chat_members(chat_id, filter=enums.ChatMembersFilter.ADMINISTRATORS)],
member.user.id
async for member in app.get_chat_members(
chat_id, filter=enums.ChatMembersFilter.ADMINISTRATORS
)
],
} }
return admins_in_chat[chat_id]["data"] return admins_in_chat[chat_id]["data"]
@ -76,11 +71,8 @@ async def authorised(func, subFunc2, client, message, *args, **kwargs):
async def unauthorised(message: Message, permission, subFunc2): async def unauthorised(message: Message, permission, subFunc2):
text = f"You don't have the required permission to perform this action.\n**Permission:** __{permission}__"
chatID = message.chat.id chatID = message.chat.id
text = (
"You don't have the required permission to perform this action."
+ f"\n**Permission:** __{permission}__"
)
try: try:
await message.reply_text(text) await message.reply_text(text)
except ChatWriteForbidden: except ChatWriteForbidden:

View file

@ -113,11 +113,8 @@ def extract_text_and_keyb(ikb, text: str, row_width: int = 2):
keyboard = {} keyboard = {}
try: try:
text = text.strip() text = text.strip()
if text.startswith("`"): text = text.removeprefix("`")
text = text[1:] text = text.removesuffix("`")
if text.endswith("`"):
text = text[:-1]
text, keyb = text.split("~") text, keyb = text.split("~")
keyb = findall(r"\[.+\,.+\]", keyb) keyb = findall(r"\[.+\,.+\]", keyb)

View file

@ -63,15 +63,9 @@ def paginate_modules(page_n, module_dict, prefix, chat=None):
if len(pairs) > COLUMN_SIZE: if len(pairs) > COLUMN_SIZE:
pairs = pairs[modulo_page * COLUMN_SIZE : COLUMN_SIZE * (modulo_page + 1)] + [ pairs = pairs[modulo_page * COLUMN_SIZE : COLUMN_SIZE * (modulo_page + 1)] + [
( (
EqInlineKeyboardButton( EqInlineKeyboardButton("", callback_data=f"{prefix}_prev({modulo_page})"),
"", 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(
"Back", callback_data=f"{prefix}_home({modulo_page})"
),
EqInlineKeyboardButton(
"", callback_data=f"{prefix}_next({modulo_page})"
),
) )
] ]

View file

@ -3,7 +3,7 @@ import string
import psutil import psutil
import time import time
import os import os
from misskaty import botStartTime, user, app, UBOT_NAME, BOT_NAME from misskaty import BOT_NAME, UBOT_NAME, botStartTime
from misskaty.plugins import ALL_MODULES from misskaty.plugins import ALL_MODULES
from misskaty.helper.human_read import get_readable_time from misskaty.helper.human_read import get_readable_time
from misskaty.helper.http import http from misskaty.helper.http import http

View file

@ -19,32 +19,18 @@ def __list_all_modules():
# This generates a list of modules in this # This generates a list of modules in this
# folder for the * in __main__ to work. # folder for the * in __main__ to work.
mod_paths = glob.glob(f"{dirname(__file__)}/*.py") mod_paths = glob.glob(f"{dirname(__file__)}/*.py")
all_modules = [ all_modules = [basename(f)[:-3] for f in mod_paths if isfile(f) and f.endswith(".py") and not f.endswith("__init__.py") and not f.endswith("__main__.py")]
basename(f)[:-3]
for f in mod_paths
if isfile(f)
and f.endswith(".py")
and not f.endswith("__init__.py")
and not f.endswith("__main__.py")
]
if MOD_LOAD or MOD_NOLOAD: if MOD_LOAD or MOD_NOLOAD:
to_load = MOD_LOAD to_load = MOD_LOAD
if to_load: if to_load:
if not all( if not all(any(mod == module_name for module_name in all_modules) for mod in to_load):
any(mod == module_name for module_name in all_modules)
for mod in to_load
):
sys.exit() sys.exit()
else: else:
to_load = all_modules to_load = all_modules
return ( return [item for item in to_load if item not in MOD_NOLOAD] if MOD_NOLOAD else to_load
[item for item in to_load if item not in MOD_NOLOAD]
if MOD_NOLOAD
else to_load
)
return all_modules return all_modules

View file

@ -59,12 +59,7 @@ async def admin_cache_func(_, cmu):
if cmu.old_chat_member and cmu.old_chat_member.promoted_by: if cmu.old_chat_member and cmu.old_chat_member.promoted_by:
admins_in_chat[cmu.chat.id] = { admins_in_chat[cmu.chat.id] = {
"last_updated_at": time(), "last_updated_at": time(),
"data": [ "data": [member.user.id async for member in app.get_chat_members(cmu.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS)],
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}]") LOGGER.info(f"Updated admin cache for {cmu.chat.id} [{cmu.chat.title}]")
@ -146,9 +141,7 @@ async def kickFunc(_, message):
# Ban/DBan/TBan User # Ban/DBan/TBan User
@app.on_message( @app.on_message(filters.command(["ban", "dban", "tban"], COMMAND_HANDLER) & ~filters.private)
filters.command(["ban", "dban", "tban"], COMMAND_HANDLER) & ~filters.private
)
@adminsOnly("can_restrict_members") @adminsOnly("can_restrict_members")
async def banFunc(_, message): async def banFunc(_, message):
user_id, reason = await extract_user_and_reason(message, sender_chat=True) user_id, reason = await extract_user_and_reason(message, sender_chat=True)
@ -160,23 +153,14 @@ async def banFunc(_, message):
if user_id in SUDO: if user_id in SUDO:
return await message.reply_text("You Wanna Ban The Elevated One?, RECONSIDER!") return await message.reply_text("You Wanna Ban The Elevated One?, RECONSIDER!")
if user_id in (await list_admins(message.chat.id)): if user_id in (await list_admins(message.chat.id)):
return await message.reply_text( return await message.reply_text("I can't ban an admin, You know the rules, so do i.")
"I can't ban an admin, You know the rules, so do i."
)
try: try:
mention = (await app.get_users(user_id)).mention mention = (await app.get_users(user_id)).mention
except IndexError: except IndexError:
mention = ( mention = message.reply_to_message.sender_chat.title if message.reply_to_message else "Anon"
message.reply_to_message.sender_chat.title
if message.reply_to_message
else "Anon"
)
msg = ( msg = f"**Banned User:** {mention}\n" f"**Banned By:** {message.from_user.mention if message.from_user else 'Anon'}\n"
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": if message.command[0][0] == "d":
await message.reply_to_message.delete() await message.reply_to_message.delete()
if message.command[0] == "tban": if message.command[0] == "tban":
@ -221,33 +205,25 @@ async def unban_func(_, message):
elif len(message.command) == 1 and reply: elif len(message.command) == 1 and reply:
user = message.reply_to_message.from_user.id user = message.reply_to_message.from_user.id
else: else:
return await message.reply_text( return await message.reply_text("Provide a username or reply to a user's message to unban.")
"Provide a username or reply to a user's message to unban."
)
await message.chat.unban_member(user) await message.chat.unban_member(user)
umention = (await app.get_users(user)).mention umention = (await app.get_users(user)).mention
await message.reply_text(f"Unbanned! {umention}") await message.reply_text(f"Unbanned! {umention}")
# Ban users listed in a message # Ban users listed in a message
@app.on_message( @app.on_message(filters.user(SUDO) & filters.command("listban", COMMAND_HANDLER) & ~filters.private)
filters.user(SUDO) & filters.command("listban", COMMAND_HANDLER) & ~filters.private
)
async def list_ban_(c, message): async def list_ban_(c, message):
userid, msglink_reason = await extract_user_and_reason(message) userid, msglink_reason = await extract_user_and_reason(message)
if not userid or not msglink_reason: if not userid or not msglink_reason:
return await message.reply_text( return await message.reply_text("Provide a userid/username along with message link and reason to list-ban")
"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 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") return await message.reply_text("You must provide a reason to list-ban")
# seperate messge link from reason # seperate messge link from reason
lreason = msglink_reason.split() lreason = msglink_reason.split()
messagelink, reason = lreason[0], " ".join(lreason[1:]) messagelink, reason = lreason[0], " ".join(lreason[1:])
if not re.search( if not re.search(r"(https?://)?t(elegram)?\.me/\w+/\d+", messagelink): # validate link
r"(https?://)?t(elegram)?\.me/\w+/\d+", messagelink
): # validate link
return await message.reply_text("Invalid message link provided") return await message.reply_text("Invalid message link provided")
if userid == 1507530289: if userid == 1507530289:
@ -256,9 +232,7 @@ async def list_ban_(c, message):
return await message.reply_text("You Wanna Ban The Elevated One?, RECONSIDER!") return await message.reply_text("You Wanna Ban The Elevated One?, RECONSIDER!")
splitted = messagelink.split("/") splitted = messagelink.split("/")
uname, mid = splitted[-2], int(splitted[-1]) uname, mid = splitted[-2], int(splitted[-1])
m = await message.reply_text( m = await message.reply_text("`Banning User from multiple groups. This may take some time`")
"`Banning User from multiple groups. This may take some time`"
)
try: try:
msgtext = (await app.get_messages(uname, mid)).text msgtext = (await app.get_messages(uname, mid)).text
gusernames = re.findall("@\w+", msgtext) gusernames = re.findall("@\w+", msgtext)
@ -287,17 +261,11 @@ async def list_ban_(c, message):
# Unban users listed in a message # Unban users listed in a message
@app.on_message( @app.on_message(filters.user(SUDO) & filters.command("listunban", COMMAND_HANDLER) & ~filters.private)
filters.user(SUDO)
& filters.command("listunban", COMMAND_HANDLER)
& ~filters.private
)
async def list_unban_(c, message): async def list_unban_(c, message):
userid, msglink = await extract_user_and_reason(message) userid, msglink = await extract_user_and_reason(message)
if not userid or not msglink: if not userid or not msglink:
return await message.reply_text( return await message.reply_text("Provide a userid/username along with message link to list-unban")
"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 if not re.search(r"(https?://)?t(elegram)?\.me/\w+/\d+", msglink): # validate link
return await message.reply_text("Invalid message link provided") return await message.reply_text("Invalid message link provided")
@ -344,9 +312,7 @@ async def deleteFunc(_, message):
# Promote Members # Promote Members
@app.on_message( @app.on_message(filters.command(["promote", "fullpromote"], COMMAND_HANDLER) & ~filters.private)
filters.command(["promote", "fullpromote"], COMMAND_HANDLER) & ~filters.private
)
@adminsOnly("can_promote_members") @adminsOnly("can_promote_members")
async def promoteFunc(_, message): async def promoteFunc(_, message):
user_id = await extract_user(message) user_id = await extract_user(message)
@ -450,15 +416,10 @@ async def mute(_, message):
if user_id in SUDO: if user_id in SUDO:
return await message.reply_text("You wanna mute the elevated one?, RECONSIDER!") return await message.reply_text("You wanna mute the elevated one?, RECONSIDER!")
if user_id in (await list_admins(message.chat.id)): if user_id in (await list_admins(message.chat.id)):
return await message.reply_text( return await message.reply_text("I can't mute an admin, You know the rules, so do i.")
"I can't mute an admin, You know the rules, so do i."
)
mention = (await app.get_users(user_id)).mention mention = (await app.get_users(user_id)).mention
keyboard = ikb({"🚨 Unmute 🚨": f"unmute_{user_id}"}) keyboard = ikb({"🚨 Unmute 🚨": f"unmute_{user_id}"})
msg = ( msg = f"**Muted User:** {mention}\n" f"**Muted By:** {message.from_user.mention if message.from_user else 'Anon'}\n"
f"**Muted User:** {mention}\n"
f"**Muted By:** {message.from_user.mention if message.from_user else 'Anon'}\n"
)
if message.command[0] == "tmute": if message.command[0] == "tmute":
split = reason.split(None, 1) split = reason.split(None, 1)
time_value = split[0] time_value = split[0]
@ -534,9 +495,7 @@ async def warn_user(_, message):
if user_id in SUDO: if user_id in SUDO:
return await message.reply_text("You Wanna Warn The Elevated One?, RECONSIDER!") return await message.reply_text("You Wanna Warn The Elevated One?, RECONSIDER!")
if user_id in (await list_admins(chat_id)): if user_id in (await list_admins(chat_id)):
return await message.reply_text( return await message.reply_text("I can't warn an admin, You know the rules, so do i.")
"I can't warn an admin, You know the rules, so do i."
)
user, warns = await asyncio.gather( user, warns = await asyncio.gather(
app.get_users(user_id), app.get_users(user_id),
get_warn(chat_id, await int_to_alpha(user_id)), get_warn(chat_id, await int_to_alpha(user_id)),
@ -569,8 +528,7 @@ async def remove_warning(_, cq):
permission = "can_restrict_members" permission = "can_restrict_members"
if permission not in permissions: if permission not in permissions:
return await cq.answer( return await cq.answer(
"You don't have enough permissions to perform this action.\n" "You don't have enough permissions to perform this action.\n" + f"Permission needed: {permission}",
+ f"Permission needed: {permission}",
show_alert=True, show_alert=True,
) )
user_id = cq.data.split("_")[1] user_id = cq.data.split("_")[1]
@ -595,8 +553,7 @@ async def unmute_user(_, cq):
permission = "can_restrict_members" permission = "can_restrict_members"
if permission not in permissions: if permission not in permissions:
return await cq.answer( return await cq.answer(
"You don't have enough permissions to perform this action.\n" "You don't have enough permissions to perform this action.\n" + f"Permission needed: {permission}",
+ f"Permission needed: {permission}",
show_alert=True, show_alert=True,
) )
user_id = cq.data.split("_")[1] user_id = cq.data.split("_")[1]
@ -615,8 +572,7 @@ async def unban_user(_, cq):
permission = "can_restrict_members" permission = "can_restrict_members"
if permission not in permissions: if permission not in permissions:
return await cq.answer( return await cq.answer(
"You don't have enough permissions to perform this action.\n" "You don't have enough permissions to perform this action.\n" + f"Permission needed: {permission}",
+ f"Permission needed: {permission}",
show_alert=True, show_alert=True,
) )
user_id = cq.data.split("_")[1] user_id = cq.data.split("_")[1]
@ -633,9 +589,7 @@ async def unban_user(_, cq):
@adminsOnly("can_restrict_members") @adminsOnly("can_restrict_members")
async def remove_warnings(_, message): async def remove_warnings(_, message):
if not message.reply_to_message: if not message.reply_to_message:
return await message.reply_text( return await message.reply_text("Reply to a message to remove a user's warnings.")
"Reply to a message to remove a user's warnings."
)
user_id = message.reply_to_message.from_user.id user_id = message.reply_to_message.from_user.id
mention = message.reply_to_message.from_user.mention mention = message.reply_to_message.from_user.mention
chat_id = message.chat.id chat_id = message.chat.id
@ -666,13 +620,7 @@ async def check_warns(_, message):
# Report User in Group # Report User in Group
@app.on_message( @app.on_message((filters.command("report", COMMAND_HANDLER) | filters.command(["admins", "admin"], prefixes="@")) & ~filters.private)
(
filters.command("report", COMMAND_HANDLER)
| filters.command(["admins", "admin"], prefixes="@")
)
& ~filters.private
)
@capture_err @capture_err
async def report_user(_, message): async def report_user(_, message):
if not message.reply_to_message: if not message.reply_to_message:
@ -687,28 +635,13 @@ async def report_user(_, message):
linked_chat = (await app.get_chat(message.chat.id)).linked_chat linked_chat = (await app.get_chat(message.chat.id)).linked_chat
if linked_chat is None: if linked_chat is None:
if reply_id in list_of_admins or reply_id == message.chat.id: if reply_id in list_of_admins or reply_id == message.chat.id:
return await message.reply_text( return await message.reply_text("Do you know that the user you are replying is an admin ?")
"Do you know that the user you are replying is an admin ?"
)
elif ( elif reply_id in list_of_admins or reply_id == message.chat.id or reply_id == linked_chat.id:
reply_id in list_of_admins return await message.reply_text("Do you know that the user you are replying is an admin ?")
or reply_id == message.chat.id user_mention = reply.from_user.mention if reply.from_user else reply.sender_chat.title
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!" text = f"Reported {user_mention} to admins!"
admin_data = [ admin_data = [m async for m in app.get_chat_members(message.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS)]
m
async for m in app.get_chat_members(
message.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS
)
]
for admin in admin_data: for admin in admin_data:
if admin.user.is_bot or admin.user.is_deleted: if admin.user.is_bot or admin.user.is_deleted:
# return bots or deleted admins # return bots or deleted admins

View file

@ -9,7 +9,7 @@
# #
# Modified plugin by me from https://github.com/TeamYukki/YukkiAFKBot to make compatible with pyrogram v2 # Modified plugin by me from https://github.com/TeamYukki/YukkiAFKBot to make compatible with pyrogram v2
import time, asyncio import time
from misskaty import app from misskaty import app
from utils import put_cleanmode from utils import put_cleanmode
from pyrogram import filters from pyrogram import filters
@ -18,7 +18,6 @@ from database.afk_db import (
remove_afk, remove_afk,
is_afk, is_afk,
add_afk, add_afk,
is_cleanmode_on,
cleanmode_off, cleanmode_off,
cleanmode_on, cleanmode_on,
) )
@ -49,39 +48,41 @@ async def active_afk(_, message):
data = reasondb["data"] data = reasondb["data"]
reasonafk = reasondb["reason"] reasonafk = reasondb["reason"]
seenago = get_readable_time2((int(time.time() - timeafk))) seenago = get_readable_time2((int(time.time() - timeafk)))
if afktype == "text": if afktype == "animation":
send = (
await message.reply_animation(
data,
caption=f"**{message.from_user.first_name}** is back online and was away for {seenago}",
)
if str(reasonafk) == "None"
else await message.reply_animation(
data,
caption=f"**{message.from_user.first_name}** is back online and was away for {seenago}\n\nReason: `{reasonafk}`",
)
)
elif afktype == "photo":
send = (
await message.reply_photo(
photo=f"downloads/{user_id}.jpg",
caption=f"**{message.from_user.first_name}** is back online and was away for {seenago}",
)
if str(reasonafk) == "None"
else await message.reply_photo(
photo=f"downloads/{user_id}.jpg",
caption=f"**{message.from_user.first_name}** is back online and was away for {seenago}\n\nReason: `{reasonafk}`",
)
)
elif afktype == "text":
send = await message.reply_text( send = await message.reply_text(
f"**{message.from_user.first_name}** is back online and was away for {seenago}", f"**{message.from_user.first_name}** is back online and was away for {seenago}",
disable_web_page_preview=True, disable_web_page_preview=True,
) )
if afktype == "text_reason": elif afktype == "text_reason":
send = await message.reply_text( send = await message.reply_text(
f"**{message.from_user.first_name}** is back online and was away for {seenago}\n\nReason: `{reasonafk}`", f"**{message.from_user.first_name}** is back online and was away for {seenago}\n\nReason: `{reasonafk}`",
disable_web_page_preview=True, disable_web_page_preview=True,
) )
if afktype == "animation": except Exception:
if str(reasonafk) == "None":
send = await message.reply_animation(
data,
caption=f"**{message.from_user.first_name}** is back online and was away for {seenago}",
)
else:
send = await message.reply_animation(
data,
caption=f"**{message.from_user.first_name}** is back online and was away for {seenago}\n\nReason: `{reasonafk}`",
)
if afktype == "photo":
if str(reasonafk) == "None":
send = await message.reply_photo(
photo=f"downloads/{user_id}.jpg",
caption=f"**{message.from_user.first_name}** is back online and was away for {seenago}",
)
else:
send = await message.reply_photo(
photo=f"downloads/{user_id}.jpg",
caption=f"**{message.from_user.first_name}** is back online and was away for {seenago}\n\nReason: `{reasonafk}`",
)
except Exception as e:
send = await message.reply_text( send = await message.reply_text(
f"**{message.from_user.first_name}** is back online", f"**{message.from_user.first_name}** is back online",
disable_web_page_preview=True, disable_web_page_preview=True,
@ -146,9 +147,7 @@ async def active_afk(_, message):
"reason": None, "reason": None,
} }
else: else:
await app.download_media( await app.download_media(message.reply_to_message, file_name=f"{user_id}.jpg")
message.reply_to_message, file_name=f"{user_id}.jpg"
)
details = { details = {
"type": "photo", "type": "photo",
"time": time.time(), "time": time.time(),
@ -165,9 +164,7 @@ async def active_afk(_, message):
"reason": _reason, "reason": _reason,
} }
else: else:
await app.download_media( await app.download_media(message.reply_to_message, file_name=f"{user_id}.jpg")
message.reply_to_message, file_name=f"{user_id}.jpg"
)
details = { details = {
"type": "photo", "type": "photo",
"time": time.time(), "time": time.time(),
@ -183,9 +180,7 @@ async def active_afk(_, message):
} }
await add_afk(user_id, details) await add_afk(user_id, details)
send = await message.reply_text( send = await message.reply_text(f"{message.from_user.mention} [<code>{message.from_user.id}</code>] is now AFK!.")
f"{message.from_user.mention} [<code>{message.from_user.id}</code>] is now AFK!."
)
await put_cleanmode(message.chat.id, send.id) await put_cleanmode(message.chat.id, send.id)

View file

@ -19,12 +19,8 @@ async def approve_join_chat(c, m):
markup = InlineKeyboardMarkup( markup = InlineKeyboardMarkup(
[ [
[ [
InlineKeyboardButton( InlineKeyboardButton(text="Sudah", callback_data=f"approve_{m.chat.id}"),
text="Sudah", callback_data=f"approve_{m.chat.id}" InlineKeyboardButton(text="Belum", callback_data=f"declined_{m.chat.id}"),
),
InlineKeyboardButton(
text="Belum", callback_data=f"declined_{m.chat.id}"
),
] ]
] ]
) )
@ -42,14 +38,10 @@ async def approve_join_chat(c, m):
async def approve_chat(c, q): async def approve_chat(c, q):
i, chat = q.data.split("_") i, chat = q.data.split("_")
try: try:
await q.message.edit( await q.message.edit("Yeayy, selamat kamu bisa bergabung di Channel YMovieZ Reborn...")
"Yeayy, selamat kamu bisa bergabung di Channel YMovieZ Reborn..."
)
await c.approve_chat_join_request(chat, q.from_user.id) await c.approve_chat_join_request(chat, q.from_user.id)
except UserAlreadyParticipant: except UserAlreadyParticipant:
await q.message.edit( await q.message.edit("Kamu sudah di acc join grup, jadi ga perlu menekan button.")
"Kamu sudah di acc join grup, jadi ga perlu menekan button."
)
except Exception as err: except Exception as err:
await q.message.edit(err) await q.message.edit(err)
@ -58,13 +50,9 @@ async def approve_chat(c, q):
async def decline_chat(c, q): async def decline_chat(c, q):
i, chat = q.data.split("_") i, chat = q.data.split("_")
try: try:
await q.message.edit( await q.message.edit("Yahh, kamu ditolak join channel. Biasakan rajin membaca yahhh..")
"Yahh, kamu ditolak join channel. Biasakan rajin membaca yahhh.."
)
await c.decline_chat_join_request(chat, q.from_user.id) await c.decline_chat_join_request(chat, q.from_user.id)
except UserAlreadyParticipant: except UserAlreadyParticipant:
await q.message.edit( await q.message.edit("Kamu sudah di acc join grup, jadi ga perlu menekan button.")
"Kamu sudah di acc join grup, jadi ga perlu menekan button."
)
except Exception as err: except Exception as err:
await q.message.edit(err) await q.message.edit(err)

View file

@ -18,9 +18,7 @@ LOGGER = getLogger(__name__)
async def FilterMessage(message: Message): async def FilterMessage(message: Message):
if (message.forward_from or message.forward_from_chat) and ( if (message.forward_from or message.forward_from_chat) and ("forwarded" not in FORWARD_FILTERS):
"forwarded" not in FORWARD_FILTERS
):
return 400 return 400
if (len(FORWARD_FILTERS) == 9) or ( if (len(FORWARD_FILTERS) == 9) or (
(message.video and ("video" in FORWARD_FILTERS)) (message.video and ("video" in FORWARD_FILTERS))
@ -44,10 +42,7 @@ async def CheckBlockedExt(event: Message):
if (media is not None) and (media.file_name is not None): if (media is not None) and (media.file_name is not None):
_file = media.file_name.rsplit(".", 1) _file = media.file_name.rsplit(".", 1)
if len(_file) == 2: if len(_file) == 2:
return ( return _file[-1].lower() in BLOCKED_EXTENSIONS or _file[-1].upper() in BLOCKED_EXTENSIONS
_file[-1].lower() in BLOCKED_EXTENSIONS
or _file[-1].upper() in BLOCKED_EXTENSIONS
)
else: else:
return False return False
@ -81,9 +76,7 @@ async def ForwardMessage(client: user, msg: Message):
LOGGER.warning(f"#FloodWait: Stopped Forwarder for {e.x}s!") LOGGER.warning(f"#FloodWait: Stopped Forwarder for {e.x}s!")
await ForwardMessage(client, msg) await ForwardMessage(client, msg)
except Exception as err: except Exception as err:
LOGGER.warning( LOGGER.warning(f"#ERROR: {err}\n\nUnable to Forward Message to {str(FORWARD_TO_CHAT_ID[i])}, reason: <code>{err}</code>")
f"#ERROR: {err}\n\nUnable to Forward Message to {str(FORWARD_TO_CHAT_ID[i])}, reason: <code>{err}</code>"
)
except Exception as err: except Exception as err:
LOGGER.warning(f"#ERROR: {err}") LOGGER.warning(f"#ERROR: {err}")

View file

@ -8,9 +8,7 @@ from misskaty import app
async def banned_users(_, client, message: Message): async def banned_users(_, client, message: Message):
return ( return (message.from_user is not None or not message.sender_chat) and message.from_user.id in temp.BANNED_USERS
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) 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) @app.on_message(filters.private & banned_user & filters.incoming)
async def ban_reply(bot, message): async def ban_reply(bot, message):
ban = await db.get_ban_status(message.from_user.id) ban = await db.get_ban_status(message.from_user.id)
await message.reply( await message.reply(f'Sorry Dude, You are Banned to use Me. \nBan Reason: {ban["ban_reason"]}')
f'Sorry Dude, You are Banned to use Me. \nBan Reason: {ban["ban_reason"]}'
)
@app.on_message(filters.group & disabled_group & filters.incoming) @app.on_message(filters.group & disabled_group & filters.incoming)

View file

@ -35,10 +35,6 @@ async def broadcast(bot, message):
done += 1 done += 1
await asyncio.sleep(2) await asyncio.sleep(2)
if not done % 20: if not done % 20:
await sts.edit( await sts.edit(f"Broadcast in progress:\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}")
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)) time_taken = datetime.timedelta(seconds=int(time.time() - start_time))
await sts.edit( 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}")
f"Broadcast Completed:\nCompleted in {time_taken} seconds.\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}"
)

View file

@ -42,10 +42,7 @@ async def pling_bypass(url):
res = await http.get(link) res = await http.get(link)
json_dic_files = res.json().pop("files") json_dic_files = res.json().pop("files")
msg = f"\n**Source Link** :\n`{url}`\n**Direct Link :**\n" msg = f"\n**Source Link** :\n`{url}`\n**Direct Link :**\n"
msg += "\n".join( msg += "\n".join(f'**→ [{i["name"]}]({unquote(i["url"])}) ({get_readable_file_size(int(i["size"]))})**' for i in json_dic_files)
f'**→ [{i["name"]}]({unquote(i["url"])}) ({get_readable_file_size(int(i["size"]))})**'
for i in json_dic_files
)
return msg return msg
except Exception as e: except Exception as e:
return e return e
@ -78,9 +75,7 @@ def wetransfer_bypass(url: str) -> str:
r = s.get("https://wetransfer.com/") r = s.get("https://wetransfer.com/")
m = re.search('name="csrf-token" content="([^"]+)"', r.text) m = re.search('name="csrf-token" content="([^"]+)"', r.text)
s.headers.update({"x-csrf-token": m[1], "x-requested-with": "XMLHttpRequest"}) s.headers.update({"x-csrf-token": m[1], "x-requested-with": "XMLHttpRequest"})
r = s.post( r = s.post(f"https://wetransfer.com/api/v4/transfers/{transfer_id}/download", json=j)
f"https://wetransfer.com/api/v4/transfers/{transfer_id}/download", json=j
)
j = r.json() j = r.json()
dl_url = j["direct_link"] dl_url = j["direct_link"]
@ -91,11 +86,9 @@ def wetransfer_bypass(url: str) -> str:
@capture_err @capture_err
async def bypass(_, message): async def bypass(_, message):
if len(message.command) == 1: if len(message.command) == 1:
return await message.reply( return await message.reply(f"Gunakan perintah /{message.command[0]} untuk bypass url")
f"Gunakan perintah /{message.command[0]} untuk bypass url"
)
url = message.command[1] url = message.command[1]
host = urllib.parse.urlparse(url).netloc urllib.parse.urlparse(url).netloc
msg = await message.reply("Bypassing URL..", quote=True) msg = await message.reply("Bypassing URL..", quote=True)
mention = f"**Bypasser:** {message.from_user.mention} ({message.from_user.id})" mention = f"**Bypasser:** {message.from_user.mention} ({message.from_user.id})"
if re.match(r"https?://(store.kde.org|www.pling.com)\/p\/(\d+)", url): if re.match(r"https?://(store.kde.org|www.pling.com)\/p\/(\d+)", url):
@ -117,8 +110,6 @@ async def bypass(_, message):
reply_markup=markup, reply_markup=markup,
disable_web_page_preview=True, disable_web_page_preview=True,
) )
elif "we.tl" or "wetransfer.com" in host: else:
data = wetransfer_bypass(url) data = wetransfer_bypass(url)
await msg.edit(f"{data}\n\n{mention}") await msg.edit(f"{data}\n\n{mention}")
else:
await msg.edit("Unsupported link..")

View file

@ -7,9 +7,7 @@ from misskaty.helper.http import http
@app.on_message(filters.command("ask", COMMAND_HANDLER)) @app.on_message(filters.command("ask", COMMAND_HANDLER))
async def chatbot(c, m): async def chatbot(c, m):
if len(m.command) == 1: if len(m.command) == 1:
return await m.reply( return await m.reply(f"Gunakan perintah <code>/{m.command[0]} [pertanyaan]</code> untuk menanyakan pertanyaan menggunakan AI.")
f"Gunakan perintah <code>/{m.command[0]} [pertanyaan]</code> untuk menanyakan pertanyaan menggunakan AI."
)
pertanyaan = m.text.split(" ", maxsplit=1)[1] pertanyaan = m.text.split(" ", maxsplit=1)[1]
headers = { headers = {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -24,11 +22,7 @@ async def chatbot(c, m):
} }
msg = await m.reply("Wait a moment looking for your answer..") msg = await m.reply("Wait a moment looking for your answer..")
try: try:
response = ( response = (await http.post("https://api.openai.com/v1/completions", headers=headers, json=json_data)).json()
await http.post(
"https://api.openai.com/v1/completions", headers=headers, json=json_data
)
).json()
await msg.edit(response["choices"][0]["text"]) await msg.edit(response["choices"][0]["text"])
except: except:
await msg.edit("Yahh, sorry i can't get your answer.") await msg.edit("Yahh, sorry i can't get your answer.")

View file

@ -66,9 +66,7 @@ async def glot(lang, langcode, code):
"content-type": "application/json", "content-type": "application/json",
"Authorization": "Token b8a2b75a-a078-4089-869c-e53d448b1ebb", "Authorization": "Token b8a2b75a-a078-4089-869c-e53d448b1ebb",
} }
r = await session.post( r = await session.post(f"https://glot.io/api/run/{lang}/latest", headers=headers, json=data)
f"https://glot.io/api/run/{lang}/latest", headers=headers, json=data
)
return await r.json() return await r.json()
@ -76,9 +74,7 @@ async def glot(lang, langcode, code):
async def list_lang(client, message): async def list_lang(client, message):
daftarlang = await listcode() daftarlang = await listcode()
list_ = "".join(f"~> {i['name']}\n" for i in daftarlang) list_ = "".join(f"~> {i['name']}\n" for i in daftarlang)
return await message.reply( return await message.reply(f"<b>List of Supported Programming Languages:</b>\n{list_}")
f"<b>List of Supported Programming Languages:</b>\n{list_}"
)
@app.on_message(filters.command(["assembly"], "!")) @app.on_message(filters.command(["assembly"], "!"))

View file

@ -192,9 +192,7 @@ async def chat_watcher_func(_, message):
reasonafk = reasondb["reason"] reasonafk = reasondb["reason"]
seenago = get_readable_time2((int(time.time() - timeafk))) seenago = get_readable_time2((int(time.time() - timeafk)))
if afktype == "text": if afktype == "text":
msg += ( msg += f"**{first_name[:25]}** is AFK since {seenago} ago.\n\n"
f"**{first_name[:25]}** is AFK since {seenago} ago.\n\n"
)
if afktype == "text_reason": if afktype == "text_reason":
msg += f"**{first_name[:25]}** is AFK since {seenago} ago.\n\n**Reason:** {reasonafk}\n\n" msg += f"**{first_name[:25]}** is AFK since {seenago} ago.\n\n**Reason:** {reasonafk}\n\n"
if afktype == "animation": if afktype == "animation":

View file

@ -6,7 +6,6 @@ import asyncio
from pyrogram import filters, enums from pyrogram import filters, enums
from misskaty import app from misskaty import app
from misskaty.vars import COMMAND_HANDLER, SUDO from misskaty.vars import COMMAND_HANDLER, SUDO
from misskaty.core.custom_filter import edited
__MODULE__ = "DevCommand" __MODULE__ = "DevCommand"
__HELP__ = """ __HELP__ = """
@ -37,9 +36,7 @@ async def donate(_, message):
) )
@app.on_message( @app.on_message(filters.command(["balas"], COMMAND_HANDLER) & filters.user(SUDO) & filters.reply)
filters.command(["balas"], COMMAND_HANDLER) & filters.user(SUDO) & filters.reply
)
async def balas(c, m): async def balas(c, m):
pesan = m.text.split(" ", 1) pesan = m.text.split(" ", 1)
await m.delete() await m.delete()
@ -53,9 +50,7 @@ async def neofetch(c, m):
@app.on_message(filters.command(["shell", "sh"], COMMAND_HANDLER) & filters.user(SUDO)) @app.on_message(filters.command(["shell", "sh"], COMMAND_HANDLER) & filters.user(SUDO))
@app.on_edited_message( @app.on_edited_message(filters.command(["shell", "sh"], COMMAND_HANDLER) & filters.user(SUDO))
filters.command(["shell", "sh"], COMMAND_HANDLER) & filters.user(SUDO)
)
async def shell(client, message): async def shell(client, message):
cmd = message.text.split(" ", 1) cmd = message.text.split(" ", 1)
if len(cmd) == 1: if len(cmd) == 1:
@ -127,17 +122,12 @@ async def evaluation_cmd_t(client, message):
async def aexec(code, client, message): async def aexec(code, client, message):
exec( exec("async def __aexec(client, message): " + "".join(f"\n {l_}" for l_ in code.split("\n")))
"async def __aexec(client, message): "
+ "".join(f"\n {l_}" for l_ in code.split("\n"))
)
return await locals()["__aexec"](client, message) return await locals()["__aexec"](client, message)
async def shell_exec(code, treat=True): async def shell_exec(code, treat=True):
process = await asyncio.create_subprocess_shell( process = await asyncio.create_subprocess_shell(code, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)
code, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT
)
stdout = (await process.communicate())[0] stdout = (await process.communicate())[0]
if treat: if treat:

View file

@ -2,11 +2,8 @@ import time
import asyncio import asyncio
import math import math
import os import os
import aiohttp
import json
from misskaty.helper.http import http from misskaty.helper.http import http
from logging import getLogger from logging import getLogger
from bs4 import BeautifulSoup
from misskaty import app from misskaty import app
from pySmartDL import SmartDL from pySmartDL import SmartDL
from datetime import datetime from datetime import datetime
@ -54,15 +51,7 @@ async def upload(bot, message):
text = callapi.json() text = callapi.json()
output = f'<u>File Uploaded to Anonfile</u>\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"]}' output = f'<u>File Uploaded to Anonfile</u>\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( btn = InlineKeyboardMarkup([[InlineKeyboardButton("📥 Download 📥", url=f"{text['data']['file']['url']['full']}")]])
[
[
InlineKeyboardButton(
"📥 Download 📥", url=f"{text['data']['file']['url']['full']}"
)
]
]
)
await m.edit(output, reply_markup=btn) await m.edit(output, reply_markup=btn)
except Exception as e: except Exception as e:
await bot.send_message(message.chat.id, text=f"Something Went Wrong!\n\n{e}") await bot.send_message(message.chat.id, text=f"Something Went Wrong!\n\n{e}")
@ -83,9 +72,7 @@ async def download(client, message):
) )
end_t = datetime.now() end_t = datetime.now()
ms = (end_t - start_t).seconds ms = (end_t - start_t).seconds
await pesan.edit( await pesan.edit(f"Downloaded to <code>{the_real_download_location}</code> in <u>{ms}</u> seconds.")
f"Downloaded to <code>{the_real_download_location}</code> in <u>{ms}</u> seconds."
)
elif len(message.command) > 1: elif len(message.command) > 1:
start_t = datetime.now() start_t = datetime.now()
the_url_parts = " ".join(message.command[1:]) the_url_parts = " ".join(message.command[1:])
@ -121,14 +108,10 @@ async def download(client, message):
current_message += f"File Name: <code>{custom_file_name}</code>\n" current_message += f"File Name: <code>{custom_file_name}</code>\n"
current_message += f"Speed: {speed}\n" current_message += f"Speed: {speed}\n"
current_message += f"{progress_str}\n" current_message += f"{progress_str}\n"
current_message += ( current_message += f"{humanbytes(downloaded)} of {humanbytes(total_length)}\n"
f"{humanbytes(downloaded)} of {humanbytes(total_length)}\n"
)
current_message += f"ETA: {estimated_total_time}" current_message += f"ETA: {estimated_total_time}"
if round(diff % 10.00) == 0 and current_message != display_message: if round(diff % 10.00) == 0 and current_message != display_message:
await pesan.edit( await pesan.edit(disable_web_page_preview=True, text=current_message)
disable_web_page_preview=True, text=current_message
)
display_message = current_message display_message = current_message
await asyncio.sleep(10) await asyncio.sleep(10)
except Exception as e: except Exception as e:
@ -136,22 +119,16 @@ async def download(client, message):
if os.path.exists(download_file_path): if os.path.exists(download_file_path):
end_t = datetime.now() end_t = datetime.now()
ms = (end_t - start_t).seconds ms = (end_t - start_t).seconds
await pesan.edit( await pesan.edit(f"Downloaded to <code>{download_file_path}</code> in {ms} seconds")
f"Downloaded to <code>{download_file_path}</code> in {ms} seconds"
)
else: else:
await pesan.edit( await pesan.edit("Reply to a Telegram Media, to download it to my local server.")
"Reply to a Telegram Media, to download it to my local server."
)
@app.on_message(filters.command(["tiktokdl"], COMMAND_HANDLER)) @app.on_message(filters.command(["tiktokdl"], COMMAND_HANDLER))
@capture_err @capture_err
async def tiktokdl(client, message): async def tiktokdl(client, message):
if len(message.command) == 1: if len(message.command) == 1:
return await message.reply( return await message.reply(f"Use command /{message.command[0]} [link] to download tiktok video.")
f"Use command /{message.command[0]} [link] to download tiktok video."
)
link = message.command[1] link = message.command[1]
msg = await message.reply("Trying download...") msg = await message.reply("Trying download...")
try: try:
@ -170,9 +147,7 @@ async def tiktokdl(client, message):
@capture_err @capture_err
async def fbdl(client, message): async def fbdl(client, message):
if len(message.command) == 1: if len(message.command) == 1:
return await message.reply( return await message.reply(f"Use command /{message.command[0]} [link] to download Facebook video.")
f"Use command /{message.command[0]} [link] to download Facebook video."
)
link = message.command[1] link = message.command[1]
msg = await message.reply("Trying download...") msg = await message.reply("Trying download...")
try: try:
@ -194,7 +169,5 @@ async def fbdl(client, message):
except: except:
pass pass
except Exception as e: except Exception as e:
await message.reply( await message.reply(f"Failed to download Facebook video..\n\n<b>Reason:</b> {e}")
f"Failed to download Facebook video..\n\n<b>Reason:</b> {e}"
)
await msg.delete() await msg.delete()

View file

@ -17,28 +17,17 @@ async def start(_, message):
await message.reply_text(text=f"Wa'alaikumsalam {message.from_user.mention} 😇") await message.reply_text(text=f"Wa'alaikumsalam {message.from_user.mention} 😇")
@app.on_message( @app.on_message(filters.regex(r"#request|#req", re.I) & (filters.text | filters.photo) & filters.chat(-1001255283935) & ~filters.channel)
filters.regex(r"#request|#req", re.I)
& (filters.text | filters.photo)
& filters.chat(-1001255283935)
& ~filters.channel
)
@capture_err @capture_err
async def request_user(client, message): async def request_user(client, message):
if message.sender_chat: if message.sender_chat:
return await message.reply( return await message.reply(f"{message.from_user.mention} mohon gunakan akun asli saat request.")
f"{message.from_user.mention} mohon gunakan akun asli saat request."
)
is_in_gap, sleep_time = await check_time_gap(message.from_user.id) is_in_gap, sleep_time = await check_time_gap(message.from_user.id)
if is_in_gap: if is_in_gap:
return await message.reply("Sabar dikit napa.. 🙄") return await message.reply("Sabar dikit napa.. 🙄")
markup = InlineKeyboardMarkup( 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( InlineKeyboardButton(
text="🚫 Tolak", text="🚫 Tolak",
@ -70,9 +59,7 @@ async def request_user(client, message):
else: else:
REQUEST_DB[user_id] = 1 REQUEST_DB[user_id] = 1
if REQUEST_DB[user_id] > 3: if REQUEST_DB[user_id] > 3:
return await message.reply( return await message.reply(f"Mohon maaf {message.from_user.mention}, maksimal request hanya 3x perhari. Kalo mau tambah 5k per request 😝😝.")
f"Mohon maaf {message.from_user.mention}, maksimal request hanya 3x perhari. Kalo mau tambah 5k per request 😝😝."
)
if message.text: if message.text:
forward = await client.send_message( forward = await client.send_message(
-1001575525902, -1001575525902,
@ -153,36 +140,18 @@ async def _callbackreq(c, q):
if q.message.caption: if q.message.caption:
await q.message.edit_text( await q.message.edit_text(
f"<b>COMPLETED</b>\n\n<s>{q.message.caption}</s>", f"<b>COMPLETED</b>\n\n<s>{q.message.caption}</s>",
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="✅ Request Completed", callback_data="reqcompl")]]),
[
[
InlineKeyboardButton(
text="✅ Request Completed", callback_data="reqcompl"
)
]
]
),
) )
else: else:
await q.message.edit_text( await q.message.edit_text(
f"<b>COMPLETED</b>\n\n<s>{q.message.text}</s>", f"<b>COMPLETED</b>\n\n<s>{q.message.text}</s>",
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="✅ Request Completed", callback_data="reqcompl")]]),
[
[
InlineKeyboardButton(
text="✅ Request Completed", callback_data="reqcompl"
)
]
]
),
) )
await q.answer("Request berhasil diselesaikan ✅") await q.answer("Request berhasil diselesaikan ✅")
else: else:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True) await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True)
except UserNotParticipant: except UserNotParticipant:
return await q.answer( return await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10)
"Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10
)
except PeerIdInvalid: except PeerIdInvalid:
return await q.answer( return await q.answer(
"Silahkan kirim pesan digrup supaya bot bisa merespon.", "Silahkan kirim pesan digrup supaya bot bisa merespon.",
@ -238,9 +207,7 @@ async def _callbackreqada(c, q):
else: else:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True) await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True)
except UserNotParticipant: except UserNotParticipant:
return await q.answer( return await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10)
"Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10
)
except PeerIdInvalid: except PeerIdInvalid:
return await q.answer( return await q.answer(
"Silahkan kirim pesan digrup supaya bot bisa merespon.", "Silahkan kirim pesan digrup supaya bot bisa merespon.",
@ -267,36 +234,18 @@ async def _callbackreject(c, q):
if q.message.caption: if q.message.caption:
await q.message.edit_text( await q.message.edit_text(
f"<b>REJECTED</b>\n\n<s>{q.message.caption}</s>", f"<b>REJECTED</b>\n\n<s>{q.message.caption}</s>",
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="🚫 Request Rejected", callback_data="reqreject")]]),
[
[
InlineKeyboardButton(
text="🚫 Request Rejected", callback_data="reqreject"
)
]
]
),
) )
else: else:
await q.message.edit_text( await q.message.edit_text(
f"<b>REJECTED</b>\n\n<s>{q.message.text}</s>", f"<b>REJECTED</b>\n\n<s>{q.message.text}</s>",
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="🚫 Request Rejected", callback_data="reqreject")]]),
[
[
InlineKeyboardButton(
text="🚫 Request Rejected", callback_data="reqreject"
)
]
]
),
) )
await q.answer("Request berhasil ditolak 🚫") await q.answer("Request berhasil ditolak 🚫")
else: else:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True) await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True)
except UserNotParticipant: except UserNotParticipant:
await q.answer( await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10)
"Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10
)
except PeerIdInvalid: except PeerIdInvalid:
return await q.answer( return await q.answer(
"Silahkan kirim pesan digrup supaya bot bisa merespon.", "Silahkan kirim pesan digrup supaya bot bisa merespon.",
@ -348,9 +297,7 @@ async def _callbackunav(c, q):
] ]
), ),
) )
await q.answer( await q.answer("Request tidak tersedia, mungkin belum rilis atau memang tidak tersedia versi digital.")
"Request tidak tersedia, mungkin belum rilis atau memang tidak tersedia versi digital."
)
else: else:
await q.answer( await q.answer(
"Apa motivasi kamu menekan tombol ini?", "Apa motivasi kamu menekan tombol ini?",
@ -358,9 +305,7 @@ async def _callbackunav(c, q):
cache_time=1000, cache_time=1000,
) )
except UserNotParticipant: except UserNotParticipant:
await q.answer( await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10)
"Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10
)
except PeerIdInvalid: except PeerIdInvalid:
return await q.answer( return await q.answer(
"Silahkan kirim pesan digrup supaya bot bisa merespon.", "Silahkan kirim pesan digrup supaya bot bisa merespon.",
@ -398,9 +343,7 @@ async def _callbackaft_unav(c, q):
@app.on_callback_query(filters.regex(r"^reqavailable$")) @app.on_callback_query(filters.regex(r"^reqavailable$"))
async def _callbackaft_dahada(c, q): async def _callbackaft_dahada(c, q):
await q.answer( await q.answer("Request ini sudah ada, silahkan cari 🔍 di channelnya yaa 😉..", show_alert=True)
"Request ini sudah ada, silahkan cari 🔍 di channelnya yaa 😉..", show_alert=True
)
scheduler = AsyncIOScheduler(timezone="Asia/Jakarta") scheduler = AsyncIOScheduler(timezone="Asia/Jakarta")

View file

@ -48,13 +48,9 @@ You can use markdown or html to save text too.
@adminsOnly("can_change_info") @adminsOnly("can_change_info")
async def save_filters(_, message): async def save_filters(_, message):
if len(message.command) == 1 or not message.reply_to_message: if len(message.command) == 1 or not message.reply_to_message:
return await message.reply_text( return await message.reply_text("**Usage:**\nReply to a text or sticker with /filter [FILTER_NAME] to save it.")
"**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: if not message.reply_to_message.text and not message.reply_to_message.sticker:
return await message.reply_text( return await message.reply_text("__**You can only save text or stickers in filters for now.**__")
"__**You can only save text or stickers in filters for now.**__"
)
name = message.text.split(None, 1)[1].strip() name = message.text.split(None, 1)[1].strip()
if not name: if not name:
return await message.reply_text("**Usage:**\n__/filter [FILTER_NAME]__") return await message.reply_text("**Usage:**\n__/filter [FILTER_NAME]__")
@ -62,9 +58,7 @@ async def save_filters(_, message):
_type = "text" if message.reply_to_message.text else "sticker" _type = "text" if message.reply_to_message.text else "sticker"
_filter = { _filter = {
"type": _type, "type": _type,
"data": message.reply_to_message.text.markdown "data": message.reply_to_message.text.markdown if _type == "text" else message.reply_to_message.sticker.file_id,
if _type == "text"
else message.reply_to_message.sticker.file_id,
} }
await save_filter(chat_id, name, _filter) await save_filter(chat_id, name, _filter)
await message.reply(f"__**Saved filter {name}.**__") await message.reply(f"__**Saved filter {name}.**__")
@ -119,8 +113,7 @@ async def filters_re(_, message):
if data_type == "text": if data_type == "text":
keyb = None keyb = None
if re.findall(r"\[.+\,.+\]", data): if re.findall(r"\[.+\,.+\]", data):
keyboard = extract_text_and_keyb(ikb, data) if keyboard := extract_text_and_keyb(ikb, data):
if keyboard:
data, keyb = keyboard data, keyb = keyboard
if message.reply_to_message: if message.reply_to_message:

View file

@ -50,16 +50,12 @@ async def genss(client, message):
chat_id=message.chat.id, chat_id=message.chat.id,
message_id=process.id, message_id=process.id,
) )
await client.send_chat_action( await client.send_chat_action(chat_id=message.chat.id, action=enums.ChatAction.UPLOAD_PHOTO)
chat_id=message.chat.id, action=enums.ChatAction.UPLOAD_PHOTO
)
try: try:
await gather( await gather(
*[ *[
message.reply_document( message.reply_document(images, reply_to_message_id=message.id),
images, reply_to_message_id=message.id
),
message.reply_photo(images, reply_to_message_id=message.id), message.reply_photo(images, reply_to_message_id=message.id),
] ]
) )
@ -67,9 +63,7 @@ async def genss(client, message):
await sleep(e.value) await sleep(e.value)
await gather( await gather(
*[ *[
message.reply_document( message.reply_document(images, reply_to_message_id=message.id),
images, reply_to_message_id=message.id
),
message.reply_photo(images, reply_to_message_id=message.id), message.reply_photo(images, reply_to_message_id=message.id),
] ]
) )
@ -100,13 +94,9 @@ async def genss_link(client, message):
try: try:
link = message.text.split(" ")[1] link = message.text.split(" ")[1]
if link.startswith("https://file.yasirweb.my.id"): if link.startswith("https://file.yasirweb.my.id"):
link = link.replace( link = link.replace("https://file.yasirweb.my.id", "https://file.yasiraris.workers.dev")
"https://file.yasirweb.my.id", "https://file.yasiraris.workers.dev"
)
if link.startswith("https://link.yasirweb.my.id"): if link.startswith("https://link.yasirweb.my.id"):
link = link.replace( link = link.replace("https://link.yasirweb.my.id", "https://yasirrobot.herokuapp.com")
"https://link.yasirweb.my.id", "https://yasirrobot.herokuapp.com"
)
process = await message.reply_text("`Processing, please wait..`") process = await message.reply_text("`Processing, please wait..`")
tmp_directory_for_each_user = f"./MissKaty_Genss/{str(message.from_user.id)}" tmp_directory_for_each_user = f"./MissKaty_Genss/{str(message.from_user.id)}"
if not os.path.isdir(tmp_directory_for_each_user): if not os.path.isdir(tmp_directory_for_each_user):
@ -118,9 +108,7 @@ async def genss_link(client, message):
chat_id=message.chat.id, chat_id=message.chat.id,
message_id=process.id, message_id=process.id,
) )
await client.send_chat_action( await client.send_chat_action(chat_id=message.chat.id, action=enums.ChatAction.UPLOAD_PHOTO)
chat_id=message.chat.id, action=enums.ChatAction.UPLOAD_PHOTO
)
try: try:
await message.reply_media_group(images, reply_to_message_id=message.id) await message.reply_media_group(images, reply_to_message_id=message.id)
except FloodWait as e: except FloodWait as e:

View file

@ -45,9 +45,7 @@ def draw_multiple_line_text(image, text, font, text_start_height):
lines = textwrap.wrap(text, width=50) lines = textwrap.wrap(text, width=50)
for line in lines: for line in lines:
line_width, line_height = font.getsize(line) line_width, line_height = font.getsize(line)
draw.text( draw.text(((image_width - line_width) / 2, y_text), line, font=font, fill="black")
((image_width - line_width) / 2, y_text), line, font=font, fill="black"
)
y_text += line_height y_text += line_height
@ -57,12 +55,8 @@ def welcomepic(pic, user, chat, count, id):
background = background.resize((1024, 500), Image.ANTIALIAS) background = background.resize((1024, 500), Image.ANTIALIAS)
pfp = Image.open(pic).convert("RGBA") pfp = Image.open(pic).convert("RGBA")
pfp = circle(pfp) pfp = circle(pfp)
pfp = pfp.resize( pfp = pfp.resize((265, 265)) # Resizes the Profilepicture so it fits perfectly in the circle
(265, 265) font = ImageFont.truetype("Calistoga-Regular.ttf", 37) # <- Text Font of the Member Count. Change the text size for your preference
) # 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 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, member_text, font, 395)
draw_multiple_line_text(background, chat, font, 47) draw_multiple_line_text(background, chat, font, 47)
@ -73,22 +67,14 @@ def welcomepic(pic, user, chat, count, id):
size=20, size=20,
align="right", align="right",
) )
background.paste( background.paste(pfp, (379, 123), pfp) # Pastes the Profilepicture on the Background Image
pfp, (379, 123), pfp background.save(f"downloads/welcome#{id}.png") # Saves the finished Image in the folder with the filename
) # 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" return f"downloads/welcome#{id}.png"
@app.on_chat_member_updated(filters.group & filters.chat(-1001128045651)) @app.on_chat_member_updated(filters.group & filters.chat(-1001128045651))
async def member_has_joined(c: app, member: ChatMemberUpdated): async def member_has_joined(c: app, member: ChatMemberUpdated):
if ( if not member.new_chat_member or member.new_chat_member.status in {"banned", "left", "restricted"} or member.old_chat_member:
not member.new_chat_member
or member.new_chat_member.status in {"banned", "left", "restricted"}
or member.old_chat_member
):
return return
user = member.new_chat_member.user if member.new_chat_member else member.from_user user = member.new_chat_member.user if member.new_chat_member else member.from_user
if user.id in SUDO: if user.id in SUDO:
@ -107,21 +93,15 @@ async def member_has_joined(c: app, member: ChatMemberUpdated):
pass pass
mention = f"<a href='tg://user?id={user.id}'>{user.first_name}</a>" mention = f"<a href='tg://user?id={user.id}'>{user.first_name}</a>"
joined_date = datetime.fromtimestamp(time.time()).strftime("%Y.%m.%d %H:%M:%S") joined_date = datetime.fromtimestamp(time.time()).strftime("%Y.%m.%d %H:%M:%S")
first_name = ( first_name = f"{user.first_name} {user.last_name}" if user.last_name else user.first_name
f"{user.first_name} {user.last_name}" if user.last_name else user.first_name
)
id = user.id id = user.id
dc = user.dc_id or "Member tanpa PP" dc = user.dc_id or "Member tanpa PP"
count = await app.get_chat_members_count(member.chat.id) count = await app.get_chat_members_count(member.chat.id)
try: try:
pic = await app.download_media( pic = await app.download_media(user.photo.big_file_id, file_name=f"pp{user.id}.png")
user.photo.big_file_id, file_name=f"pp{user.id}.png"
)
except AttributeError: except AttributeError:
pic = "img/profilepic.png" pic = "img/profilepic.png"
welcomeimg = await welcomepic( welcomeimg = await welcomepic(pic, user.first_name, member.chat.title, count, user.id)
pic, user.first_name, member.chat.title, count, user.id
)
temp.MELCOW[f"welcome-{member.chat.id}"] = await c.send_photo( temp.MELCOW[f"welcome-{member.chat.id}"] = await c.send_photo(
member.chat.id, member.chat.id,
photo=welcomeimg, photo=welcomeimg,
@ -130,30 +110,18 @@ async def member_has_joined(c: app, member: ChatMemberUpdated):
userspammer = "" userspammer = ""
# Spamwatch Detection # Spamwatch Detection
try: try:
headers = { headers = {"Authorization": "Bearer XvfzE4AUNXkzCy0DnIVpFDlxZi79lt6EnwKgBj8Quuzms0OSdHvf1k6zSeyzZ_lz"}
"Authorization": "Bearer XvfzE4AUNXkzCy0DnIVpFDlxZi79lt6EnwKgBj8Quuzms0OSdHvf1k6zSeyzZ_lz" apispamwatch = (await http.get(f"https://api.spamwat.ch/banlist/{user.id}", headers=headers)).json()
}
apispamwatch = (
await http.get(
f"https://api.spamwat.ch/banlist/{user.id}", headers=headers
)
).json()
if not apispamwatch.get("error"): if not apispamwatch.get("error"):
await app.ban_chat_member( await app.ban_chat_member(member.chat.id, user.id, datetime.now() + timedelta(seconds=30))
member.chat.id, user.id, datetime.now() + timedelta(seconds=30)
)
userspammer += f"<b>#SpamWatch Federation Ban</b>\nUser {mention} [<code>{user.id}</code>] has been kicked because <code>{apispamwatch.get('reason')}</code>.\n" userspammer += f"<b>#SpamWatch Federation Ban</b>\nUser {mention} [<code>{user.id}</code>] has been kicked because <code>{apispamwatch.get('reason')}</code>.\n"
except Exception as err: except Exception as err:
LOGGER.error(f"ERROR in Spamwatch Detection. {err}") LOGGER.error(f"ERROR in Spamwatch Detection. {err}")
# Combot API Detection # Combot API Detection
try: try:
apicombot = ( apicombot = (await http.get(f"https://api.cas.chat/check?user_id={user.id}")).json()
await http.get(f"https://api.cas.chat/check?user_id={user.id}")
).json()
if apicombot.get("ok") == "true": if apicombot.get("ok") == "true":
await app.ban_chat_member( await app.ban_chat_member(member.chat.id, user.id, datetime.now() + timedelta(seconds=30))
member.chat.id, user.id, datetime.now() + timedelta(seconds=30)
)
userspammer += f"<b>#CAS Federation Ban</b>\nUser {mention} [<code>{user.id}</code>] detected as spambot and has been kicked. Powered by <a href='https://api.cas.chat/check?user_id={user.id}'>Combot AntiSpam.</a>" userspammer += f"<b>#CAS Federation Ban</b>\nUser {mention} [<code>{user.id}</code>] detected as spambot and has been kicked. Powered by <a href='https://api.cas.chat/check?user_id={user.id}'>Combot AntiSpam.</a>"
except Exception as err: except Exception as err:
LOGGER.error(f"ERROR in Combot API Detection. {err}") LOGGER.error(f"ERROR in Combot API Detection. {err}")
@ -181,9 +149,7 @@ async def save_group(bot, message):
await db.add_chat(message.chat.id, message.chat.title) await db.add_chat(message.chat.id, message.chat.title)
if message.chat.id in temp.BANNED_CHATS: if message.chat.id in temp.BANNED_CHATS:
# Inspired from a boat of a banana tree # Inspired from a boat of a banana tree
buttons = [ buttons = [[InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]]
[InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]
]
reply_markup = InlineKeyboardMarkup(buttons) reply_markup = InlineKeyboardMarkup(buttons)
k = await message.reply( k = await message.reply(
text="<b>CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..</b>", text="<b>CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..</b>",
@ -198,9 +164,7 @@ async def save_group(bot, message):
return return
buttons = [ buttons = [
[ [
InlineKeyboardButton( InlineKeyboardButton(" Help", url=f"https://t.me/{temp.U_NAME}?start=help"),
" Help", url=f"https://t.me/{temp.U_NAME}?start=help"
),
InlineKeyboardButton("📢 Updates", url="https://t.me/YasirPediaChannel"), InlineKeyboardButton("📢 Updates", url="https://t.me/YasirPediaChannel"),
] ]
] ]
@ -213,14 +177,10 @@ async def save_group(bot, message):
for u in message.new_chat_members: for u in message.new_chat_members:
count = await app.get_chat_members_count(message.chat.id) count = await app.get_chat_members_count(message.chat.id)
try: try:
pic = await app.download_media( pic = await app.download_media(u.photo.big_file_id, file_name=f"pp{u.id}.png")
u.photo.big_file_id, file_name=f"pp{u.id}.png"
)
except AttributeError: except AttributeError:
pic = "img/profilepic.png" pic = "img/profilepic.png"
welcomeimg = await welcomepic( welcomeimg = await welcomepic(pic, u.first_name, message.chat.title, count, u.id)
pic, u.first_name, message.chat.title, count, u.id
)
if (temp.MELCOW).get(f"welcome-{message.chat.id}") is not None: if (temp.MELCOW).get(f"welcome-{message.chat.id}") is not None:
try: try:
await (temp.MELCOW[f"welcome-{message.chat.id}"]).delete() await (temp.MELCOW[f"welcome-{message.chat.id}"]).delete()
@ -251,9 +211,7 @@ async def leave_a_chat(bot, message):
except: except:
chat = chat chat = chat
try: try:
buttons = [ buttons = [[InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]]
[InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]
]
reply_markup = InlineKeyboardMarkup(buttons) reply_markup = InlineKeyboardMarkup(buttons)
await bot.send_message( await bot.send_message(
chat_id=chat, chat_id=chat,
@ -285,16 +243,12 @@ async def disable_chat(bot, message):
if not cha_t: if not cha_t:
return await message.reply("Chat Not Found In DB") return await message.reply("Chat Not Found In DB")
if cha_t["is_disabled"]: if cha_t["is_disabled"]:
return await message.reply( return await message.reply(f"This chat is already disabled:\nReason-<code> {cha_t['reason']} </code>")
f"This chat is already disabled:\nReason-<code> {cha_t['reason']} </code>"
)
await db.disable_chat(chat_, reason) await db.disable_chat(chat_, reason)
temp.BANNED_CHATS.append(chat_) temp.BANNED_CHATS.append(chat_)
await message.reply("Chat Succesfully Disabled") await message.reply("Chat Succesfully Disabled")
try: try:
buttons = [ buttons = [[InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]]
[InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]
]
reply_markup = InlineKeyboardMarkup(buttons) reply_markup = InlineKeyboardMarkup(buttons)
await bot.send_message( await bot.send_message(
chat_id=chat_, chat_id=chat_,
@ -339,9 +293,7 @@ async def gen_invite(bot, message):
try: try:
link = await bot.create_chat_invite_link(chat) link = await bot.create_chat_invite_link(chat)
except ChatAdminRequired: except ChatAdminRequired:
return await message.reply( return await message.reply("Invite Link Generation Failed, Iam Not Having Sufficient Rights")
"Invite Link Generation Failed, Iam Not Having Sufficient Rights"
)
except Exception as e: except Exception as e:
return await message.reply(f"Error {e}") return await message.reply(f"Error {e}")
await message.reply(f"Here is your Invite Link {link.invite_link}") await message.reply(f"Here is your Invite Link {link.invite_link}")
@ -354,15 +306,11 @@ async def adminlist(_, message):
return await message.reply("Perintah ini hanya untuk grup") return await message.reply("Perintah ini hanya untuk grup")
try: try:
administrators = [] administrators = []
async for m in app.get_chat_members( async for m in app.get_chat_members(message.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS):
message.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS
):
administrators.append(f"{m.user.first_name}") administrators.append(f"{m.user.first_name}")
res = "".join(f"~ {i}\n" for i in administrators) res = "".join(f"~ {i}\n" for i in administrators)
return await message.reply( return await message.reply(f"Daftar Admin di <b>{message.chat.title}</b> ({message.chat.id}):\n~ {res}")
f"Daftar Admin di <b>{message.chat.title}</b> ({message.chat.id}):\n~ {res}"
)
except Exception as e: except Exception as e:
await message.reply(f"ERROR: {str(e)}") await message.reply(f"ERROR: {str(e)}")
@ -380,9 +328,7 @@ async def kickme(_, message):
await message.reply_text(txt) await message.reply_text(txt)
await message.unban_member(message.from_user.id) await message.unban_member(message.from_user.id)
except RPCError as ef: except RPCError as ef:
await message.reply_text( await message.reply_text(f"Sepertinya ada error, silahkan report ke owner saya. \nERROR: {str(ef)}")
f"Sepertinya ada error, silahkan report ke owner saya. \nERROR: {str(ef)}"
)
return return

View file

@ -17,67 +17,48 @@ __HELP__ = """"
""" """
@app.on_message( @app.on_message(filters.incoming & ~filters.private & filters.command(["inkick"], COMMAND_HANDLER))
filters.incoming & ~filters.private & filters.command(["inkick"], COMMAND_HANDLER)
)
async def inkick(_, message): async def inkick(_, message):
user = await app.get_chat_member(message.chat.id, message.from_user.id) user = await app.get_chat_member(message.chat.id, message.from_user.id)
if user.status.value in ("administrator", "owner"): if user.status.value in ("administrator", "owner"):
if len(message.command) > 1: if len(message.command) > 1:
input_str = message.command input_str = message.command
sent_message = await message.reply_text( sent_message = await message.reply_text("🚮**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**")
"🚮**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**"
)
count = 0 count = 0
async for member in app.get_chat_members(message.chat.id): async for member in app.get_chat_members(message.chat.id):
if member.user.is_bot: if member.user.is_bot:
continue continue
if ( if member.user.status.value in input_str and member.status.value not in ("administrator", "owner"):
member.user.status.value in input_str
and member.status.value not in ("administrator", "owner")
):
try: try:
await message.chat.ban_member(member.user.id) await message.chat.ban_member(member.user.id)
count += 1 count += 1
await sleep(1) await sleep(1)
await message.chat.unban_member(member.user.id) await message.chat.unban_member(member.user.id)
except (ChatAdminRequired, UserAdminInvalid): except (ChatAdminRequired, UserAdminInvalid):
await sent_message.edit( await sent_message.edit("❗**Oh tidaakk, saya bukan admin disini**\n__Saya pergi dari sini, tambahkan aku kembali dengan perijinan banned pengguna.__")
"❗**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) await app.leave_chat(message.chat.id)
break break
except FloodWait as e: except FloodWait as e:
await sleep(e.value) await sleep(e.value)
try: try:
await sent_message.edit( await sent_message.edit(f"✔️ **Berhasil menendang {count} pengguna berdasarkan argumen.**")
f"✔️ **Berhasil menendang {count} pengguna berdasarkan argumen.**"
)
except ChatWriteForbidden: except ChatWriteForbidden:
await app.leave_chat(message.chat.id) await app.leave_chat(message.chat.id)
else: else:
await message.reply_text( await message.reply_text("❗ **Arguments Required**\n__See /help in personal message for more information.__")
"❗ **Arguments Required**\n__See /help in personal message for more information.__"
)
else: else:
sent_message = await message.reply_text( sent_message = await message.reply_text("❗ **You have to be the group creator to do that.**")
"❗ **You have to be the group creator to do that.**"
)
await sleep(5) await sleep(5)
await sent_message.delete() await sent_message.delete()
# Kick User Without Username # Kick User Without Username
@app.on_message( @app.on_message(filters.incoming & ~filters.private & filters.command(["uname"], COMMAND_HANDLER))
filters.incoming & ~filters.private & filters.command(["uname"], COMMAND_HANDLER)
)
async def uname(_, message): async def uname(_, message):
user = await app.get_chat_member(message.chat.id, message.from_user.id) user = await app.get_chat_member(message.chat.id, message.from_user.id)
if user.status.value in ("administrator", "owner"): if user.status.value in ("administrator", "owner"):
sent_message = await message.reply_text( sent_message = await message.reply_text("🚮**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**")
"🚮**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**"
)
count = 0 count = 0
async for member in app.get_chat_members(message.chat.id): async for member in app.get_chat_members(message.chat.id):
if not member.user.username and member.status.value not in ( if not member.user.username and member.status.value not in (
@ -90,37 +71,27 @@ async def uname(_, message):
await sleep(1) await sleep(1)
await message.chat.unban_member(member.user.id) await message.chat.unban_member(member.user.id)
except (ChatAdminRequired, UserAdminInvalid): except (ChatAdminRequired, UserAdminInvalid):
await sent_message.edit( await sent_message.edit("❗**Oh tidaakk, saya bukan admin disini**\n__Saya pergi dari sini, tambahkan aku kembali dengan perijinan banned pengguna.__")
"❗**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) await app.leave_chat(message.chat.id)
break break
except FloodWait as e: except FloodWait as e:
await sleep(e.value) await sleep(e.value)
try: try:
await sent_message.edit( await sent_message.edit(f"✔️ **Berhasil menendang {count} pengguna berdasarkan argumen.**")
f"✔️ **Berhasil menendang {count} pengguna berdasarkan argumen.**"
)
except ChatWriteForbidden: except ChatWriteForbidden:
await app.leave_chat(message.chat.id) await app.leave_chat(message.chat.id)
else: else:
sent_message = await message.reply_text( sent_message = await message.reply_text("❗ **You have to be the group creator to do that.**")
"❗ **You have to be the group creator to do that.**"
)
await sleep(5) await sleep(5)
await sent_message.delete() await sent_message.delete()
@app.on_message( @app.on_message(filters.incoming & ~filters.private & filters.command(["dkick"], COMMAND_HANDLER))
filters.incoming & ~filters.private & filters.command(["dkick"], COMMAND_HANDLER)
)
async def dkick(client, message): async def dkick(client, message):
user = await app.get_chat_member(message.chat.id, message.from_user.id) user = await app.get_chat_member(message.chat.id, message.from_user.id)
if user.status.value in ("administrator", "owner"): if user.status.value in ("administrator", "owner"):
sent_message = await message.reply_text( sent_message = await message.reply_text("🚮**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**")
"🚮**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**"
)
count = 0 count = 0
async for member in app.get_chat_members(message.chat.id): async for member in app.get_chat_members(message.chat.id):
if member.user.is_deleted and member.status.value not in ( if member.user.is_deleted and member.status.value not in (
@ -133,9 +104,7 @@ async def dkick(client, message):
await sleep(1) await sleep(1)
await message.chat.unban_member(member.user.id) await message.chat.unban_member(member.user.id)
except (ChatAdminRequired, UserAdminInvalid): except (ChatAdminRequired, UserAdminInvalid):
await sent_message.edit( await sent_message.edit("❗**Oh tidaakk, saya bukan admin disini**\n__Saya pergi dari sini, tambahkan aku kembali dengan perijinan banned pengguna.__")
"❗**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) await app.leave_chat(message.chat.id)
break break
except FloodWait as e: except FloodWait as e:
@ -145,16 +114,12 @@ async def dkick(client, message):
except ChatWriteForbidden: except ChatWriteForbidden:
await app.leave_chat(message.chat.id) await app.leave_chat(message.chat.id)
else: else:
sent_message = await message.reply_text( sent_message = await message.reply_text("❗ **Kamu harus jadi admin atau owner grup untuk melakukan tindakan ini.**")
"❗ **Kamu harus jadi admin atau owner grup untuk melakukan tindakan ini.**"
)
await sleep(5) await sleep(5)
await sent_message.delete() await sent_message.delete()
@app.on_message( @app.on_message(filters.incoming & ~filters.private & filters.command(["instatus"], COMMAND_HANDLER))
filters.incoming & ~filters.private & filters.command(["instatus"], COMMAND_HANDLER)
)
async def instatus(client, message): async def instatus(client, message):
start_time = time.perf_counter() start_time = time.perf_counter()
user = await app.get_chat_member(message.chat.id, message.from_user.id) user = await app.get_chat_member(message.chat.id, message.from_user.id)
@ -163,9 +128,7 @@ async def instatus(client, message):
enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.ADMINISTRATOR,
enums.ChatMemberStatus.OWNER, enums.ChatMemberStatus.OWNER,
): ):
sent_message = await message.reply_text( sent_message = await message.reply_text("**Sedang mengumpulkan informasi pengguna...**")
"**Sedang mengumpulkan informasi pengguna...**"
)
recently = 0 recently = 0
within_week = 0 within_week = 0
within_month = 0 within_month = 0
@ -177,13 +140,9 @@ async def instatus(client, message):
banned = 0 banned = 0
uncached = 0 uncached = 0
bot = 0 bot = 0
async for ban in app.get_chat_members( async for ban in app.get_chat_members(message.chat.id, filter=enums.ChatMembersFilter.BANNED):
message.chat.id, filter=enums.ChatMembersFilter.BANNED
):
banned += 1 banned += 1
async for restr in app.get_chat_members( async for restr in app.get_chat_members(message.chat.id, filter=enums.ChatMembersFilter.RESTRICTED):
message.chat.id, filter=enums.ChatMembersFilter.RESTRICTED
):
restricted += 1 restricted += 1
async for member in app.get_chat_members(message.chat.id): async for member in app.get_chat_members(message.chat.id):
user = member.user user = member.user
@ -226,8 +185,6 @@ async def instatus(client, message):
) )
) )
else: else:
sent_message = await message.reply_text( sent_message = await message.reply_text("❗ **Kamu harus jadi admin atau owner grup untuk melakukan tindakan ini.**")
"❗ **Kamu harus jadi admin atau owner grup untuk melakukan tindakan ini.**"
)
await sleep(5) await sleep(5)
await sent_message.delete() await sent_message.delete()

View file

@ -38,12 +38,7 @@ PRVT_MSGS = {}
async def inline_menu(_, inline_query: InlineQuery): async def inline_menu(_, inline_query: InlineQuery):
if inline_query.query.strip().lower().strip() == "": if inline_query.query.strip().lower().strip() == "":
buttons = InlineKeyboard(row_width=2) buttons = InlineKeyboard(row_width=2)
buttons.add( buttons.add(*[(InlineKeyboardButton(text=i, switch_inline_query_current_chat=i)) for i in keywords_list])
*[
(InlineKeyboardButton(text=i, switch_inline_query_current_chat=i))
for i in keywords_list
]
)
btn = InlineKeyboard(row_width=2) btn = InlineKeyboard(row_width=2)
bot_state = "Alive" if await app.get_me() else "Dead" bot_state = "Alive" if await app.get_me() else "Dead"
@ -67,27 +62,21 @@ async def inline_menu(_, inline_query: InlineQuery):
InlineQueryResultArticle( InlineQueryResultArticle(
title="Inline Commands", title="Inline Commands",
description="Help Related To Inline Usage.", description="Help Related To Inline Usage.",
input_message_content=InputTextMessageContent( input_message_content=InputTextMessageContent("Click A Button To Get Started."),
"Click A Button To Get Started."
),
thumb_url="https://hamker.me/cy00x5x.png", thumb_url="https://hamker.me/cy00x5x.png",
reply_markup=buttons, reply_markup=buttons,
), ),
InlineQueryResultArticle( InlineQueryResultArticle(
title="Github Repo", title="Github Repo",
description="Github Repo of This Bot.", description="Github Repo of This Bot.",
input_message_content=InputTextMessageContent( input_message_content=InputTextMessageContent(f"<b>Github Repo @{BOT_USERNAME}</b>\n\nhttps://github.com/yasirarism/MissKatyPyro"),
f"<b>Github Repo @{BOT_USERNAME}</b>\n\nhttps://github.com/yasirarism/MissKatyPyro"
),
thumb_url="https://hamker.me/gjc9fo3.png", thumb_url="https://hamker.me/gjc9fo3.png",
), ),
InlineQueryResultArticle( InlineQueryResultArticle(
title="Alive", title="Alive",
description="Check Bot's Stats", description="Check Bot's Stats",
thumb_url="https://yt3.ggpht.com/ytc/AMLnZu-zbtIsllERaGYY8Aecww3uWUASPMjLUUEt7ecu=s900-c-k-c0x00ffffff-no-rj", thumb_url="https://yt3.ggpht.com/ytc/AMLnZu-zbtIsllERaGYY8Aecww3uWUASPMjLUUEt7ecu=s900-c-k-c0x00ffffff-no-rj",
input_message_content=InputTextMessageContent( input_message_content=InputTextMessageContent(msg, disable_web_page_preview=True),
msg, disable_web_page_preview=True
),
reply_markup=btn, reply_markup=btn,
), ),
] ]
@ -100,13 +89,8 @@ async def inline_menu(_, inline_query: InlineQuery):
switch_pm_parameter="inline", switch_pm_parameter="inline",
) )
judul = inline_query.query.split(None, 1)[1].strip() judul = inline_query.query.split(None, 1)[1].strip()
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"}
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " search_results = await http.get(f"https://www.google.com/search?q={judul}&num=20", headers=headers)
"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") soup = BeautifulSoup(search_results.text, "lxml")
data = [] data = []
for result in soup.select(".tF2Cxc"): for result in soup.select(".tF2Cxc"):
@ -129,9 +113,7 @@ async def inline_menu(_, inline_query: InlineQuery):
url=link, url=link,
description=snippet, description=snippet,
thumb_url="https://te.legra.ph/file/ed8ea62ae636793000bb4.jpg", thumb_url="https://te.legra.ph/file/ed8ea62ae636793000bb4.jpg",
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Open Website", url=link)]]),
[[InlineKeyboardButton(text="Open Website", url=link)]]
),
) )
) )
await inline_query.answer( await inline_query.answer(
@ -169,11 +151,7 @@ async def inline_menu(_, inline_query: InlineQuery):
) )
prvte_msg = InlineKeyboardMarkup( prvte_msg = InlineKeyboardMarkup(
[ [
[ [InlineKeyboardButton("Show Message 🔐", callback_data=f"prvtmsg({inline_query.id})")],
InlineKeyboardButton(
"Show Message 🔐", callback_data=f"prvtmsg({inline_query.id})"
)
],
[ [
InlineKeyboardButton( InlineKeyboardButton(
"Destroy☠ this msg", "Destroy☠ this msg",
@ -182,15 +160,9 @@ async def inline_menu(_, inline_query: InlineQuery):
], ],
] ]
) )
mention = ( mention = f"@{penerima.username}" if penerima.username else f"<a href='tg://user?id={penerima.id}'>{penerima.first_name}</a>"
f"@{penerima.username}"
if penerima.username
else f"<a href='tg://user?id={penerima.id}'>{penerima.first_name}</a>"
)
msg_c = ( msg_c = f"🔒 A <b>private message</b> to {mention} [<code>{penerima.id}</code>], "
f"🔒 A <b>private message</b> to {mention} [<code>{penerima.id}</code>], "
)
msg_c += "Only he/she can open it." msg_c += "Only he/she can open it."
results = [ results = [
InlineQueryResultArticle( InlineQueryResultArticle(
@ -210,9 +182,7 @@ async def inline_menu(_, inline_query: InlineQuery):
switch_pm_parameter="inline", switch_pm_parameter="inline",
) )
query = inline_query.query.split(None, 1)[1].strip() query = inline_query.query.split(None, 1)[1].strip()
search_results = await http.get( search_results = await http.get(f"https://api.github.com/search/repositories?q={query}")
f"https://api.github.com/search/repositories?q={query}"
)
srch_results = json.loads(search_results.text) srch_results = json.loads(search_results.text)
item = srch_results.get("items") item = srch_results.get("items")
data = [] data = []
@ -235,9 +205,7 @@ async def inline_menu(_, inline_query: InlineQuery):
url=link, url=link,
description=deskripsi, description=deskripsi,
thumb_url="https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png", thumb_url="https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png",
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Open Github Link", url=link)]]),
[[InlineKeyboardButton(text="Open Github Link", url=link)]]
),
) )
) )
await inline_query.answer( await inline_query.answer(
@ -256,9 +224,7 @@ async def inline_menu(_, inline_query: InlineQuery):
switch_pm_parameter="inline", switch_pm_parameter="inline",
) )
query = inline_query.query.split(None, 1)[1].strip() query = inline_query.query.split(None, 1)[1].strip()
search_results = await http.get( search_results = await http.get(f"https://api.hayo.my.id/api/pypi?package={query}")
f"https://api.hayo.my.id/api/pypi?package={query}"
)
srch_results = json.loads(search_results.text) srch_results = json.loads(search_results.text)
data = [] data = []
for sraeo in srch_results: for sraeo in srch_results:
@ -279,9 +245,7 @@ async def inline_menu(_, inline_query: InlineQuery):
url=link, url=link,
description=deskripsi, description=deskripsi,
thumb_url="https://raw.githubusercontent.com/github/explore/666de02829613e0244e9441b114edb85781e972c/topics/pip/pip.png", thumb_url="https://raw.githubusercontent.com/github/explore/666de02829613e0244e9441b114edb85781e972c/topics/pip/pip.png",
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Open Link", url=link)]]),
[[InlineKeyboardButton(text="Open Link", url=link)]]
),
) )
) )
await inline_query.answer( await inline_query.answer(
@ -300,9 +264,7 @@ async def inline_menu(_, inline_query: InlineQuery):
switch_pm_parameter="inline", switch_pm_parameter="inline",
) )
judul = inline_query.query.split(None, 1)[1].strip() judul = inline_query.query.split(None, 1)[1].strip()
search_results = await http.get( search_results = await http.get(f"https://api.abir-hasan.tk/youtube?query={judul}")
f"https://api.abir-hasan.tk/youtube?query={judul}"
)
srch_results = json.loads(search_results.text) srch_results = json.loads(search_results.text)
asroe = srch_results.get("results") asroe = srch_results.get("results")
oorse = [] oorse = []
@ -314,9 +276,7 @@ async def inline_menu(_, inline_query: InlineQuery):
durasi = sraeo.get("accessibility").get("duration") durasi = sraeo.get("accessibility").get("duration")
publishTime = sraeo.get("publishedTime") publishTime = sraeo.get("publishedTime")
try: try:
deskripsi = "".join( deskripsi = "".join(f"{i['text']} " for i in sraeo.get("descriptionSnippet"))
f"{i['text']} " for i in sraeo.get("descriptionSnippet")
)
except: except:
deskripsi = "-" deskripsi = "-"
message_text = f"<a href='{link}'>{title}</a>\n" message_text = f"<a href='{link}'>{title}</a>\n"
@ -335,9 +295,7 @@ async def inline_menu(_, inline_query: InlineQuery):
url=link, url=link,
description=deskripsi, description=deskripsi,
thumb_url=thumb, thumb_url=thumb,
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="Watch Video 📹", url=link)]]),
[[InlineKeyboardButton(text="Watch Video 📹", url=link)]]
),
) )
) )
await inline_query.answer( await inline_query.answer(
@ -356,9 +314,7 @@ async def inline_menu(_, inline_query: InlineQuery):
switch_pm_parameter="inline", switch_pm_parameter="inline",
) )
movie_name = inline_query.query.split(None, 1)[1].strip() movie_name = inline_query.query.split(None, 1)[1].strip()
search_results = await http.get( search_results = await http.get(f"https://yasirapi.eu.org/imdb-search?q={movie_name}")
f"https://yasirapi.eu.org/imdb-search?q={movie_name}"
)
res = json.loads(search_results.text).get("result") res = json.loads(search_results.text).get("result")
oorse = [] oorse = []
for midb in res: for midb in res:
@ -367,11 +323,7 @@ async def inline_menu(_, inline_query: InlineQuery):
stars = midb.get("s", "") stars = midb.get("s", "")
imdb_url = f"https://imdb.com/title/{midb.get('id')}" imdb_url = f"https://imdb.com/title/{midb.get('id')}"
year = f"({midb.get('y')})" if midb.get("y") else "" year = f"({midb.get('y')})" if midb.get("y") else ""
image_url = ( image_url = midb.get("i").get("imageUrl").replace(".jpg", "._V1_UX360.jpg") if midb.get("i") else "https://te.legra.ph/file/e263d10ff4f4426a7c664.jpg"
midb.get("i").get("imageUrl").replace(".jpg", "._V1_UX360.jpg")
if midb.get("i")
else "https://te.legra.ph/file/e263d10ff4f4426a7c664.jpg"
)
caption = f"<a href='{image_url}'>🎬</a>" caption = f"<a href='{image_url}'>🎬</a>"
caption += f"<a href='{imdb_url}'>{title} {year}</a>" caption += f"<a href='{imdb_url}'>{title} {year}</a>"
oorse.append( oorse.append(
@ -446,83 +398,46 @@ async def imdb_inl(_, query):
url = f"https://www.imdb.com/title/{movie}/" url = f"https://www.imdb.com/title/{movie}/"
resp = await get_content(url) resp = await get_content(url)
sop = BeautifulSoup(resp, "lxml") sop = BeautifulSoup(resp, "lxml")
r_json = json.loads( r_json = json.loads(sop.find("script", attrs={"type": "application/ld+json"}).contents[0])
sop.find("script", attrs={"type": "application/ld+json"}).contents[0]
)
res_str = "" res_str = ""
type = f"<code>{r_json['@type']}</code>" if r_json.get("@type") else "" type = f"<code>{r_json['@type']}</code>" if r_json.get("@type") else ""
if r_json.get("name"): if r_json.get("name"):
try: try:
tahun = ( tahun = sop.select('ul[data-testid="hero-title-block__metadata"]')[0].find(class_="sc-8c396aa2-2 itZqyK").text
sop.select('ul[data-testid="hero-title-block__metadata"]')[0]
.find(class_="sc-8c396aa2-2 itZqyK")
.text
)
except: except:
tahun = "-" tahun = "-"
res_str += f"<b>📹 Judul:</b> <a href='{url}'>{r_json['name']} [{tahun}]</a> (<code>{type}</code>)\n" res_str += f"<b>📹 Judul:</b> <a href='{url}'>{r_json['name']} [{tahun}]</a> (<code>{type}</code>)\n"
if r_json.get("alternateName"): if r_json.get("alternateName"):
res_str += ( res_str += f"<b>📢 AKA:</b> <code>{r_json.get('alternateName')}</code>\n\n"
f"<b>📢 AKA:</b> <code>{r_json.get('alternateName')}</code>\n\n"
)
else: else:
res_str += "\n" res_str += "\n"
if sop.select('li[data-testid="title-techspec_runtime"]'): if sop.select('li[data-testid="title-techspec_runtime"]'):
durasi = ( durasi = sop.select('li[data-testid="title-techspec_runtime"]')[0].find(class_="ipc-metadata-list-item__content-container").text
sop.select('li[data-testid="title-techspec_runtime"]')[0]
.find(class_="ipc-metadata-list-item__content-container")
.text
)
res_str += f"<b>Durasi:</b> <code>{GoogleTranslator('auto', 'id').translate(durasi)}</code>\n" res_str += f"<b>Durasi:</b> <code>{GoogleTranslator('auto', 'id').translate(durasi)}</code>\n"
if r_json.get("contentRating"): if r_json.get("contentRating"):
res_str += f"<b>Kategori:</b> <code>{r_json['contentRating']}</code> \n" res_str += f"<b>Kategori:</b> <code>{r_json['contentRating']}</code> \n"
if r_json.get("aggregateRating"): if r_json.get("aggregateRating"):
res_str += f"<b>Peringkat:</b> <code>{r_json['aggregateRating']['ratingValue']}⭐️ dari {r_json['aggregateRating']['ratingCount']} pengguna</code> \n" res_str += f"<b>Peringkat:</b> <code>{r_json['aggregateRating']['ratingValue']}⭐️ dari {r_json['aggregateRating']['ratingCount']} pengguna</code> \n"
if sop.select('li[data-testid="title-details-releasedate"]'): if sop.select('li[data-testid="title-details-releasedate"]'):
rilis = ( 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
sop.select('li[data-testid="title-details-releasedate"]')[0] 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"]
.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"<b>Rilis:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n" res_str += f"<b>Rilis:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n"
if r_json.get("genre"): if r_json.get("genre"):
genre = "".join( 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"])
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] genre = genre[:-2]
res_str += f"<b>Genre:</b> {genre}\n" res_str += f"<b>Genre:</b> {genre}\n"
if sop.select('li[data-testid="title-details-origin"]'): if sop.select('li[data-testid="title-details-origin"]'):
country = "".join( country = "".join(
f"{demoji(country.text)} #{country.text.replace(' ', '_').replace('-', '_')}, " f"{demoji(country.text)} #{country.text.replace(' ', '_').replace('-', '_')}, "
for country in sop.select('li[data-testid="title-details-origin"]')[ 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")
0
].findAll(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)
) )
country = country[:-2] country = country[:-2]
res_str += f"<b>Negara:</b> {country}\n" res_str += f"<b>Negara:</b> {country}\n"
if sop.select('li[data-testid="title-details-languages"]'): if sop.select('li[data-testid="title-details-languages"]'):
language = "".join( language = "".join(
f"#{lang.text.replace(' ', '_').replace('-', '_')}, " f"#{lang.text.replace(' ', '_').replace('-', '_')}, "
for lang in sop.select('li[data-testid="title-details-languages"]')[ 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")
0
].findAll(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)
) )
language = language[:-2] language = language[:-2]
res_str += f"<b>Bahasa:</b> {language}\n" res_str += f"<b>Bahasa:</b> {language}\n"
@ -553,9 +468,7 @@ async def imdb_inl(_, query):
actors = actors[:-2] actors = actors[:-2]
res_str += f"<b>Pemeran:</b> {actors}\n\n" res_str += f"<b>Pemeran:</b> {actors}\n\n"
if r_json.get("description"): if r_json.get("description"):
summary = GoogleTranslator("auto", "id").translate( summary = GoogleTranslator("auto", "id").translate(r_json.get("description"))
r_json.get("description")
)
res_str += f"<b>📜 Plot: </b> <code>{summary}</code>\n\n" res_str += f"<b>📜 Plot: </b> <code>{summary}</code>\n\n"
if r_json.get("keywords"): if r_json.get("keywords"):
keywords = r_json["keywords"].split(",") keywords = r_json["keywords"].split(",")
@ -566,11 +479,7 @@ async def imdb_inl(_, query):
key_ = key_[:-2] key_ = key_[:-2]
res_str += f"<b>🔥 Kata Kunci:</b> {key_} \n" res_str += f"<b>🔥 Kata Kunci:</b> {key_} \n"
if sop.select('li[data-testid="award_information"]'): if sop.select('li[data-testid="award_information"]'):
awards = ( awards = sop.select('li[data-testid="award_information"]')[0].find(class_="ipc-metadata-list-item__list-content-item").text
sop.select('li[data-testid="award_information"]')[0]
.find(class_="ipc-metadata-list-item__list-content-item")
.text
)
res_str += f"<b>🏆 Penghargaan:</b> <code>{GoogleTranslator('auto', 'id').translate(awards)}</code>\n\n" res_str += f"<b>🏆 Penghargaan:</b> <code>{GoogleTranslator('auto', 'id').translate(awards)}</code>\n\n"
else: else:
res_str += "\n" res_str += "\n"

View file

@ -24,9 +24,7 @@ Give reputation to other people in group.
karma_positive_group = 3 karma_positive_group = 3
karma_negative_group = 4 karma_negative_group = 4
regex_upvote = ( regex_upvote = r"^(\+|\+\+|\+1|thx|tnx|ty|thank you|thanx|thanks|pro|cool|good|makasih|👍|\+\+ .+)$"
r"^(\+|\+\+|\+1|thx|tnx|ty|thank you|thanx|thanks|pro|cool|good|makasih|👍|\+\+ .+)$"
)
regex_downvote = r"^(-|--|-1|👎|-- .+)$" regex_downvote = r"^(-|--|-1|👎|-- .+)$"
n = "\n" n = "\n"
@ -47,30 +45,18 @@ def section(
text = (bold_ul(title) + n) if underline else bold(title) + n text = (bold_ul(title) + n) if underline else bold(title) + n
for key, value in body.items(): for key, value in body.items():
text += ( text += indent * w + bold(key) + ((value[0] + n) if isinstance(value, list) else mono(value))
indent * w
+ bold(key)
+ ((value[0] + n) if isinstance(value, list) else mono(value))
)
return text return text
async def get_user_id_and_usernames(client) -> dict: async def get_user_id_and_usernames(client) -> dict:
with client.storage.lock, client.storage.conn: with client.storage.lock, client.storage.conn:
users = client.storage.conn.execute( users = client.storage.conn.execute('SELECT * FROM peers WHERE type in ("user", "bot") AND username NOT null').fetchall()
'SELECT * FROM peers WHERE type in ("user", "bot") AND username NOT null'
).fetchall()
return {user[0]: user[3] for user in users} return {user[0]: user[3] for user in users}
@app.on_message( @app.on_message(
filters.text filters.text & filters.group & filters.incoming & filters.reply & filters.regex(regex_upvote, re.IGNORECASE) & ~filters.via_bot & ~filters.bot,
& filters.group
& filters.incoming
& filters.reply
& filters.regex(regex_upvote, re.IGNORECASE)
& ~filters.via_bot
& ~filters.bot,
group=karma_positive_group, group=karma_positive_group,
) )
@capture_err @capture_err
@ -94,19 +80,11 @@ async def upvote(_, message):
karma = 1 karma = 1
new_karma = {"karma": karma} new_karma = {"karma": karma}
await update_karma(chat_id, await int_to_alpha(user_id), new_karma) await update_karma(chat_id, await int_to_alpha(user_id), new_karma)
await message.reply_text( await message.reply_text(f"Incremented Karma of {user_mention} By 1 \nTotal Points: {karma}")
f"Incremented Karma of {user_mention} By 1 \nTotal Points: {karma}"
)
@app.on_message( @app.on_message(
filters.text filters.text & filters.group & filters.incoming & filters.reply & filters.regex(regex_downvote, re.IGNORECASE) & ~filters.via_bot & ~filters.bot,
& filters.group
& filters.incoming
& filters.reply
& filters.regex(regex_downvote, re.IGNORECASE)
& ~filters.via_bot
& ~filters.bot,
group=karma_negative_group, group=karma_negative_group,
) )
@capture_err @capture_err
@ -131,9 +109,7 @@ async def downvote(_, message):
karma = 1 karma = 1
new_karma = {"karma": karma} new_karma = {"karma": karma}
await update_karma(chat_id, await int_to_alpha(user_id), new_karma) await update_karma(chat_id, await int_to_alpha(user_id), new_karma)
await message.reply_text( await message.reply_text(f"Decremented Karma Of {user_mention} By 1 \nTotal Points: {karma}")
f"Decremented Karma Of {user_mention} By 1 \nTotal Points: {karma}"
)
@app.on_message(filters.command("karma") & filters.group) @app.on_message(filters.command("karma") & filters.group)

View file

@ -25,9 +25,7 @@ from misskaty.helper.pyro_progress import (
@capture_err @capture_err
async def mediainfo(client, message): async def mediainfo(client, message):
if message.reply_to_message and message.reply_to_message.media: if message.reply_to_message and message.reply_to_message.media:
process = await message.reply_text( process = await message.reply_text("`Sedang memproses, lama waktu tergantung ukuran file kamu...`", quote=True)
"`Sedang memproses, lama waktu tergantung ukuran file kamu...`", quote=True
)
file_info = get_file_id(message.reply_to_message) file_info = get_file_id(message.reply_to_message)
if file_info is None: if file_info is None:
await process.edit_text("Balas ke format media yang valid") await process.edit_text("Balas ke format media yang valid")
@ -63,22 +61,14 @@ async def mediainfo(client, message):
try: try:
link = message.text.split(" ", maxsplit=1)[1] link = message.text.split(" ", maxsplit=1)[1]
if link.startswith("https://file.yasirweb.my.id"): if link.startswith("https://file.yasirweb.my.id"):
link = link.replace( link = link.replace("https://file.yasirweb.my.id", "https://file.yasiraris.workers.dev")
"https://file.yasirweb.my.id", "https://file.yasiraris.workers.dev"
)
if link.startswith("https://link.yasirweb.my.id"): if link.startswith("https://link.yasirweb.my.id"):
link = link.replace( link = link.replace("https://link.yasirweb.my.id", "https://yasirrobot.herokuapp.com")
"https://link.yasirweb.my.id", "https://yasirrobot.herokuapp.com"
)
process = await message.reply_text("`Mohon tunggu sejenak...`") process = await message.reply_text("`Mohon tunggu sejenak...`")
try: try:
output = subprocess.check_output(["mediainfo", f"{link}"]).decode( output = subprocess.check_output(["mediainfo", f"{link}"]).decode("utf-8")
"utf-8"
)
except Exception: except Exception:
return await process.edit( return await process.edit("Sepertinya link yang kamu kirim tidak valid, pastikan direct link dan bisa di download.")
"Sepertinya link yang kamu kirim tidak valid, pastikan direct link dan bisa di download."
)
title = "MissKaty Bot Mediainfo" title = "MissKaty Bot Mediainfo"
body_text = f""" body_text = f"""
<img src='https://telegra.ph/file/72c99bbc89bbe4e178cc9.jpg' /> <img src='https://telegra.ph/file/72c99bbc89bbe4e178cc9.jpg' />
@ -89,9 +79,7 @@ async def mediainfo(client, message):
# response = await http.post(siteurl, data={"content": output, "extension": 'txt'} ) # response = await http.post(siteurl, data={"content": output, "extension": 'txt'} )
# response = response.json() # response = response.json()
# spacebin = "https://spaceb.in/"+response['payload']['id'] # spacebin = "https://spaceb.in/"+response['payload']['id']
markup = InlineKeyboardMarkup( markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="💬 Telegraph", url=tgraph)]])
[[InlineKeyboardButton(text="💬 Telegraph", url=tgraph)]]
)
with io.BytesIO(str.encode(output)) as out_file: with io.BytesIO(str.encode(output)) as out_file:
out_file.name = "MissKaty_Mediainfo.txt" out_file.name = "MissKaty_Mediainfo.txt"
await message.reply_document( await message.reply_document(
@ -101,6 +89,4 @@ async def mediainfo(client, message):
) )
await process.delete() await process.delete()
except IndexError: except IndexError:
return await message.reply_text( return await message.reply_text("Gunakan command /mediainfo [link], atau reply telegram media dengan /mediainfo.")
"Gunakan command /mediainfo [link], atau reply telegram media dengan /mediainfo."
)

View file

@ -133,9 +133,7 @@ async def draw_meme_text(image_path, text):
@app.on_message(filters.command(["mmf"], COMMAND_HANDLER)) @app.on_message(filters.command(["mmf"], COMMAND_HANDLER))
@capture_err @capture_err
async def memify(client, message): async def memify(client, message):
if message.reply_to_message and ( if message.reply_to_message and (message.reply_to_message.sticker or message.reply_to_message.photo):
message.reply_to_message.sticker or message.reply_to_message.photo
):
try: try:
file = await message.reply_to_message.download() file = await message.reply_to_message.download()
res = await draw_meme_text(file, message.text.split(None, 1)[1].strip()) res = await draw_meme_text(file, message.text.split(None, 1)[1].strip())
@ -145,10 +143,6 @@ async def memify(client, message):
except: except:
pass pass
except: except:
await message.reply( await message.reply("Gunakan command <b>/mmf <text></b> dengan reply ke sticker, pisahkan dengan ; untuk membuat posisi text dibawah.")
"Gunakan command <b>/mmf <text></b> dengan reply ke sticker, pisahkan dengan ; untuk membuat posisi text dibawah."
)
else: else:
await message.reply( await message.reply("Gunakan command <b>/mmf <text></b> dengan reply ke sticker, pisahkan dengan ; untuk membuat posisi text dibawah.")
"Gunakan command <b>/mmf <text></b> dengan reply ke sticker, pisahkan dengan ; untuk membuat posisi text dibawah."
)

View file

@ -52,20 +52,12 @@ def remove_html_tags(text):
async def stackoverflow(client, message): async def stackoverflow(client, message):
if len(message.command) == 1: if len(message.command) == 1:
return await message.reply("Give a query to search in StackOverflow!") return await message.reply("Give a query to search in StackOverflow!")
r = ( 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()
await http.get(
f"https://api.stackexchange.com/2.3/search/excerpts?order=asc&sort=relevance&q={message.command[1]}&accepted=True&migrated=False¬ice=False&wiki=False&site=stackoverflow"
)
).json()
hasil = "" hasil = ""
for count, data in enumerate(r["items"], start=1): for count, data in enumerate(r["items"], start=1):
question = data["question_id"] question = data["question_id"]
title = data["title"] title = data["title"]
snippet = ( 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(" ", "")
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}. <a href='https://stackoverflow.com/questions/{question}'>{title}</a>\n<code>{snippet}</code>\n" hasil += f"{count}. <a href='https://stackoverflow.com/questions/{question}'>{title}</a>\n<code>{snippet}</code>\n"
try: try:
await message.reply(hasil) await message.reply(hasil)
@ -84,10 +76,7 @@ async def gsearch(client, message):
query = message.text.split(" ", maxsplit=1)[1] query = message.text.split(" ", maxsplit=1)[1]
msg = await message.reply_text(f"**Googling** for `{query}` ...") msg = await message.reply_text(f"**Googling** for `{query}` ...")
try: try:
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"}
"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( html = await http.get(
f"https://www.google.com/search?q={query}&gl=id&hl=id&num=17", f"https://www.google.com/search?q={query}&gl=id&hl=id&num=17",
headers=headers, headers=headers,
@ -116,9 +105,7 @@ async def gsearch(client, message):
arr = json.dumps(data, indent=2, ensure_ascii=False) arr = json.dumps(data, indent=2, ensure_ascii=False)
parse = json.loads(arr) parse = json.loads(arr)
total = len(parse) total = len(parse)
res = "".join( res = "".join(f"<a href='{i['link']}'>{i['title']}</a>\n{i['snippet']}\n\n" for i in parse)
f"<a href='{i['link']}'>{i['title']}</a>\n{i['snippet']}\n\n" for i in parse
)
except Exception: except Exception:
exc = traceback.format_exc() exc = traceback.format_exc()
return await msg.edit(exc) return await msg.edit(exc)
@ -131,9 +118,7 @@ async def gsearch(client, message):
@app.on_message(filters.command(["tr", "trans", "translate"], COMMAND_HANDLER)) @app.on_message(filters.command(["tr", "trans", "translate"], COMMAND_HANDLER))
@capture_err @capture_err
async def translate(client, message): async def translate(client, message):
if message.reply_to_message and ( if message.reply_to_message and (message.reply_to_message.text or message.reply_to_message.caption):
message.reply_to_message.text or message.reply_to_message.caption
):
target_lang = "id" if len(message.command) == 1 else message.text.split()[1] 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 text = message.reply_to_message.text or message.reply_to_message.caption
else: else:
@ -145,28 +130,20 @@ async def translate(client, message):
text = message.text.split(None, 2)[2] text = message.text.split(None, 2)[2]
msg = await message.reply("Menerjemahkan...") msg = await message.reply("Menerjemahkan...")
try: try:
tekstr = ( tekstr = (await http.get(f"https://script.google.com/macros/s/AKfycbyhNk6uVgrtJLEFRUT6y5B2pxETQugCZ9pKvu01-bE1gKkDRsw/exec?q={text}&target={target_lang}")).json()["text"]
await http.get(
f"https://script.google.com/macros/s/AKfycbyhNk6uVgrtJLEFRUT6y5B2pxETQugCZ9pKvu01-bE1gKkDRsw/exec?q={text}&target={target_lang}"
)
).json()["text"]
except Exception as err: except Exception as err:
return await msg.edit(f"Error: <code>{str(err)}</code>") return await msg.edit(f"Error: <code>{str(err)}</code>")
try: try:
await msg.edit(f"<code>{tekstr}</code>") await msg.edit(f"<code>{tekstr}</code>")
except MessageTooLong: except MessageTooLong:
url = await rentry(tekstr.text) url = await rentry(tekstr.text)
await msg.edit( await msg.edit(f"Your translated text pasted to rentry because has long text:\n{url}")
f"Your translated text pasted to rentry because has long text:\n{url}"
)
@app.on_message(filters.command(["tts"], COMMAND_HANDLER)) @app.on_message(filters.command(["tts"], COMMAND_HANDLER))
@capture_err @capture_err
async def tts(_, message): async def tts(_, message):
if message.reply_to_message and ( if message.reply_to_message and (message.reply_to_message.text or message.reply_to_message.caption):
message.reply_to_message.text or message.reply_to_message.caption
):
if len(message.text.split()) == 1: if len(message.text.split()) == 1:
target_lang = "id" target_lang = "id"
else: else:
@ -218,16 +195,12 @@ async def topho(client, message):
if not message.reply_to_message or not message.reply_to_message.sticker: 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") return await message.reply_text("Reply ke sticker untuk mengubah ke foto")
if message.reply_to_message.sticker.is_animated: if message.reply_to_message.sticker.is_animated:
return await message.reply_text( return await message.reply_text("Ini sticker animasi, command ini hanya untuk sticker biasa.")
"Ini sticker animasi, command ini hanya untuk sticker biasa."
)
photo = await client.download_media( photo = await client.download_media(
message.reply_to_message.sticker.file_id, message.reply_to_message.sticker.file_id,
f"tostick_{message.from_user.id}.jpg", f"tostick_{message.from_user.id}.jpg",
) )
await message.reply_photo( await message.reply_photo(photo=photo, caption=f"Sticker -> Image\n@{BOT_USERNAME}")
photo=photo, caption=f"Sticker -> Image\n@{BOT_USERNAME}"
)
os.remove(photo) os.remove(photo)
except Exception as e: except Exception as e:
@ -260,16 +233,10 @@ async def showid(client, message):
) )
file_info = get_file_id(message.reply_to_message) file_info = get_file_id(message.reply_to_message)
else: else:
_id += ( _id += "<b>➲ User ID</b>: " f"<code>{message.from_user.id if message.from_user else 'Anonymous'}</code>\n"
"<b>➲ User ID</b>: "
f"<code>{message.from_user.id if message.from_user else 'Anonymous'}</code>\n"
)
file_info = get_file_id(message) file_info = get_file_id(message)
if file_info: if file_info:
_id += ( _id += f"<b>{file_info.message_type}</b>: " f"<code>{file_info.file_id}</code>\n"
f"<b>{file_info.message_type}</b>: "
f"<code>{file_info.file_id}</code>\n"
)
await message.reply_text(_id, quote=True) await message.reply_text(_id, quote=True)
@ -300,12 +267,8 @@ async def who_is(client, message):
if message.chat.type in (("supergroup", "channel")): if message.chat.type in (("supergroup", "channel")):
try: try:
chat_member_p = await message.chat.get_member(from_user.id) chat_member_p = await message.chat.get_member(from_user.id)
joined_date = datetime.fromtimestamp( joined_date = datetime.fromtimestamp(chat_member_p.joined_date or time.time()).strftime("%Y.%m.%d %H:%M:%S")
chat_member_p.joined_date or time.time() message_out_str += "<b>➲Joined this Chat on:</b> <code>" f"{joined_date}" "</code>\n"
).strftime("%Y.%m.%d %H:%M:%S")
message_out_str += (
"<b>➲Joined this Chat on:</b> <code>" f"{joined_date}" "</code>\n"
)
except UserNotParticipant: except UserNotParticipant:
pass pass
if chat_photo := from_user.photo: if chat_photo := from_user.photo:
@ -332,9 +295,7 @@ async def who_is(client, message):
await status_message.delete() await status_message.delete()
headers = { 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"}
"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): async def get_content(url):
@ -387,22 +348,16 @@ async def mdl_callback(bot: Client, query: CallbackQuery):
try: try:
res = (await http.get(f"https://kuryana.vercel.app/id/{slug}")).json() res = (await http.get(f"https://kuryana.vercel.app/id/{slug}")).json()
result += f"<b>Title:</b> <a href='{res['data']['link']}'>{res['data']['title']}</a>\n" result += f"<b>Title:</b> <a href='{res['data']['link']}'>{res['data']['title']}</a>\n"
result += ( result += f"<b>AKA:</b> <code>{res['data']['others']['also_known_as']}</code>\n\n"
f"<b>AKA:</b> <code>{res['data']['others']['also_known_as']}</code>\n\n"
)
result += f"<b>Rating:</b> <code>{res['data']['details']['score']}</code>\n" result += f"<b>Rating:</b> <code>{res['data']['details']['score']}</code>\n"
result += f"<b>Content Rating:</b> <code>{res['data']['details']['content_rating']}</code>\n" result += f"<b>Content Rating:</b> <code>{res['data']['details']['content_rating']}</code>\n"
result += f"<b>Type:</b> <code>{res['data']['details']['type']}</code>\n" result += f"<b>Type:</b> <code>{res['data']['details']['type']}</code>\n"
result += ( result += f"<b>Country:</b> <code>{res['data']['details']['country']}</code>\n"
f"<b>Country:</b> <code>{res['data']['details']['country']}</code>\n"
)
if res["data"]["details"]["type"] == "Movie": if res["data"]["details"]["type"] == "Movie":
result += f"<b>Release Date:</b> <code>{res['data']['details']['release_date']}</code>\n" result += f"<b>Release Date:</b> <code>{res['data']['details']['release_date']}</code>\n"
elif res["data"]["details"]["type"] == "Drama": elif res["data"]["details"]["type"] == "Drama":
result += f"<b>Episode:</b> {res['data']['details']['episodes']}\n" result += f"<b>Episode:</b> {res['data']['details']['episodes']}\n"
result += ( result += f"<b>Aired:</b> <code>{res['data']['details']['aired']}</code>\n"
f"<b>Aired:</b> <code>{res['data']['details']['aired']}</code>\n"
)
try: try:
result += f"<b>Aired on:</b> <code>{res['data']['details']['aired_on']}</code>\n" result += f"<b>Aired on:</b> <code>{res['data']['details']['aired_on']}</code>\n"
except: except:
@ -411,17 +366,11 @@ async def mdl_callback(bot: Client, query: CallbackQuery):
result += f"<b>Original Network:</b> <code>{res['data']['details']['original_network']}</code>\n" result += f"<b>Original Network:</b> <code>{res['data']['details']['original_network']}</code>\n"
except: except:
pass pass
result += ( result += f"<b>Duration:</b> <code>{res['data']['details']['duration']}</code>\n"
f"<b>Duration:</b> <code>{res['data']['details']['duration']}</code>\n" result += f"<b>Genre:</b> <code>{res['data']['others']['genres']}</code>\n\n"
)
result += (
f"<b>Genre:</b> <code>{res['data']['others']['genres']}</code>\n\n"
)
result += f"<b>Synopsis:</b> <code>{res['data']['synopsis']}</code>\n" result += f"<b>Synopsis:</b> <code>{res['data']['synopsis']}</code>\n"
result += f"<b>Tags:</b> <code>{res['data']['others']['tags']}</code>\n" result += f"<b>Tags:</b> <code>{res['data']['others']['tags']}</code>\n"
btn = InlineKeyboardMarkup( btn = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Open MyDramaList", url=res["data"]["link"])]])
[[InlineKeyboardButton("🎬 Open MyDramaList", url=res["data"]["link"])]]
)
await query.message.edit_text(result, reply_markup=btn) await query.message.edit_text(result, reply_markup=btn)
except Exception as e: except Exception as e:
await query.message.edit_text(f"<b>ERROR:</b>\n<code>{e}</code>") await query.message.edit_text(f"<b>ERROR:</b>\n<code>{e}</code>")
@ -435,13 +384,9 @@ async def mdl_callback(bot: Client, query: CallbackQuery):
async def imdb1_search(client, message): async def imdb1_search(client, message):
BTN = [] BTN = []
if message.sender_chat: if message.sender_chat:
return await message.reply( return await message.reply("Mohon maaf fitur tidak tersedia untuk akun channel, harap ganti ke akun biasa..")
"Mohon maaf fitur tidak tersedia untuk akun channel, harap ganti ke akun biasa.."
)
if len(message.command) == 1: if len(message.command) == 1:
return await message.reply( return await message.reply("Berikan aku nama series atau movie yang ingin dicari. 🤷🏻‍♂️", quote=True)
"Berikan aku nama series atau movie yang ingin dicari. 🤷🏻‍♂️", quote=True
)
r, judul = message.text.split(None, 1) r, judul = message.text.split(None, 1)
k = await message.reply("🔎 Sedang mencari di Database IMDB..", quote=True) k = await message.reply("🔎 Sedang mencari di Database IMDB..", quote=True)
msg = "" msg = ""
@ -458,11 +403,7 @@ async def imdb1_search(client, message):
type = movie.get("q").replace("feature", "movie").capitalize() type = movie.get("q").replace("feature", "movie").capitalize()
movieID = re.findall(r"tt(\d+)", movie.get("id"))[0] movieID = re.findall(r"tt(\d+)", movie.get("id"))[0]
msg += f"{count}. {title} {year} ~ {type}\n" msg += f"{count}. {title} {year} ~ {type}\n"
BTN.append( BTN.append(InlineKeyboardButton(text=count, callback_data=f"imdbid#{message.from_user.id}#{movieID}"))
InlineKeyboardButton(
text=count, callback_data=f"imdbid#{message.from_user.id}#{movieID}"
)
)
buttons.add(*BTN) buttons.add(*BTN)
await k.edit(msg, reply_markup=buttons) await k.edit(msg, reply_markup=buttons)
except Exception as err: except Exception as err:
@ -480,18 +421,12 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery):
url = f"https://www.imdb.com/title/tt{movie}/" url = f"https://www.imdb.com/title/tt{movie}/"
resp = await get_content(url) resp = await get_content(url)
sop = BeautifulSoup(resp, "lxml") sop = BeautifulSoup(resp, "lxml")
r_json = json.loads( r_json = json.loads(sop.find("script", attrs={"type": "application/ld+json"}).contents[0])
sop.find("script", attrs={"type": "application/ld+json"}).contents[0]
)
res_str = "" res_str = ""
type = f"<code>{r_json['@type']}</code>" if r_json.get("@type") else "" type = f"<code>{r_json['@type']}</code>" if r_json.get("@type") else ""
if r_json.get("name"): if r_json.get("name"):
try: try:
tahun = ( tahun = sop.select('ul[data-testid="hero-title-block__metadata"]')[0].find(class_="sc-8c396aa2-2 itZqyK").text
sop.select('ul[data-testid="hero-title-block__metadata"]')[0]
.find(class_="sc-8c396aa2-2 itZqyK")
.text
)
except: except:
tahun = "-" tahun = "-"
res_str += f"<b>📹 Judul:</b> <a href='{url}'>{r_json['name']} [{tahun}]</a> (<code>{type}</code>)\n" res_str += f"<b>📹 Judul:</b> <a href='{url}'>{r_json['name']} [{tahun}]</a> (<code>{type}</code>)\n"
@ -500,63 +435,31 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery):
else: else:
res_str += "\n" res_str += "\n"
if sop.select('li[data-testid="title-techspec_runtime"]'): if sop.select('li[data-testid="title-techspec_runtime"]'):
durasi = ( durasi = sop.select('li[data-testid="title-techspec_runtime"]')[0].find(class_="ipc-metadata-list-item__content-container").text
sop.select('li[data-testid="title-techspec_runtime"]')[0]
.find(class_="ipc-metadata-list-item__content-container")
.text
)
res_str += f"<b>Durasi:</b> <code>{GoogleTranslator('auto', 'id').translate(durasi)}</code>\n" res_str += f"<b>Durasi:</b> <code>{GoogleTranslator('auto', 'id').translate(durasi)}</code>\n"
if r_json.get("contentRating"): if r_json.get("contentRating"):
res_str += f"<b>Kategori:</b> <code>{r_json['contentRating']}</code> \n" res_str += f"<b>Kategori:</b> <code>{r_json['contentRating']}</code> \n"
if r_json.get("aggregateRating"): if r_json.get("aggregateRating"):
res_str += f"<b>Peringkat:</b> <code>{r_json['aggregateRating']['ratingValue']}⭐️ dari {r_json['aggregateRating']['ratingCount']} pengguna</code> \n" res_str += f"<b>Peringkat:</b> <code>{r_json['aggregateRating']['ratingValue']}⭐️ dari {r_json['aggregateRating']['ratingCount']} pengguna</code> \n"
if sop.select('li[data-testid="title-details-releasedate"]'): if sop.select('li[data-testid="title-details-releasedate"]'):
rilis = ( 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
sop.select('li[data-testid="title-details-releasedate"]')[0] 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"]
.find( res_str += f"<b>Rilis:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n"
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"<b>Rilis:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n"
)
if r_json.get("genre"): if r_json.get("genre"):
genre = "".join( 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"])
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] genre = genre[:-2]
res_str += f"<b>Genre:</b> {genre}\n" res_str += f"<b>Genre:</b> {genre}\n"
if sop.select('li[data-testid="title-details-origin"]'): if sop.select('li[data-testid="title-details-origin"]'):
country = "".join( country = "".join(
f"{demoji(country.text)} #{country.text.replace(' ', '_').replace('-', '_')}, " f"{demoji(country.text)} #{country.text.replace(' ', '_').replace('-', '_')}, "
for country in sop.select('li[data-testid="title-details-origin"]')[ 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")
0
].findAll(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)
) )
country = country[:-2] country = country[:-2]
res_str += f"<b>Negara:</b> {country}\n" res_str += f"<b>Negara:</b> {country}\n"
if sop.select('li[data-testid="title-details-languages"]'): if sop.select('li[data-testid="title-details-languages"]'):
language = "".join( language = "".join(
f"#{lang.text.replace(' ', '_').replace('-', '_')}, " 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] language = language[:-2]
res_str += f"<b>Bahasa:</b> {language}\n" res_str += f"<b>Bahasa:</b> {language}\n"
@ -587,9 +490,7 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery):
actors = actors[:-2] actors = actors[:-2]
res_str += f"<b>Pemeran:</b> {actors}\n\n" res_str += f"<b>Pemeran:</b> {actors}\n\n"
if r_json.get("description"): if r_json.get("description"):
summary = GoogleTranslator("auto", "id").translate( summary = GoogleTranslator("auto", "id").translate(r_json.get("description"))
r_json.get("description")
)
res_str += f"<b>📜 Plot: </b> <code>{summary}</code>\n\n" res_str += f"<b>📜 Plot: </b> <code>{summary}</code>\n\n"
if r_json.get("keywords"): if r_json.get("keywords"):
keywords = r_json["keywords"].split(",") keywords = r_json["keywords"].split(",")
@ -600,11 +501,7 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery):
key_ = key_[:-2] key_ = key_[:-2]
res_str += f"<b>🔥 Kata Kunci:</b> {key_} \n" res_str += f"<b>🔥 Kata Kunci:</b> {key_} \n"
if sop.select('li[data-testid="award_information"]'): if sop.select('li[data-testid="award_information"]'):
awards = ( awards = sop.select('li[data-testid="award_information"]')[0].find(class_="ipc-metadata-list-item__list-content-item").text
sop.select('li[data-testid="award_information"]')[0]
.find(class_="ipc-metadata-list-item__list-content-item")
.text
)
res_str += f"<b>🏆 Penghargaan:</b> <code>{GoogleTranslator('auto', 'id').translate(awards)}</code>\n\n" res_str += f"<b>🏆 Penghargaan:</b> <code>{GoogleTranslator('auto', 'id').translate(awards)}</code>\n\n"
else: else:
res_str += "\n" res_str += "\n"
@ -614,23 +511,13 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery):
markup = InlineKeyboardMarkup( markup = InlineKeyboardMarkup(
[ [
[ [
InlineKeyboardButton( InlineKeyboardButton("🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}"),
"🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}"
),
InlineKeyboardButton("▶️ Trailer", url=trailer_url), InlineKeyboardButton("▶️ Trailer", url=trailer_url),
] ]
] ]
) )
else: else:
markup = InlineKeyboardMarkup( 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']}"
)
]
]
)
if thumb := r_json.get("image"): if thumb := r_json.get("image"):
try: try:
await query.message.reply_photo( await query.message.reply_photo(
@ -657,9 +544,7 @@ async def imdbcb_backup(bot: Client, query: CallbackQuery):
) )
await query.message.delete() await query.message.delete()
else: else:
await query.message.edit( await query.message.edit(res_str, reply_markup=markup, disable_web_page_preview=False)
res_str, reply_markup=markup, disable_web_page_preview=False
)
await query.answer() await query.answer()
except MessageNotModified: except MessageNotModified:
pass pass
@ -696,11 +581,7 @@ async def imdb_en_search(client, message):
type = movie.get("qid").replace("feature", "movie").capitalize() type = movie.get("qid").replace("feature", "movie").capitalize()
movieID = re.findall(r"tt(\d+)", movie.get("id"))[0] movieID = re.findall(r"tt(\d+)", movie.get("id"))[0]
msg += f"{count}. {titles} {year} ~ {type}\n" msg += f"{count}. {titles} {year} ~ {type}\n"
BTN.append( BTN.append(InlineKeyboardButton(text=count, callback_data=f"imdben#{message.from_user.id}#{movieID}"))
InlineKeyboardButton(
text=count, callback_data=f"imdben#{message.from_user.id}#{movieID}"
)
)
buttons.add(*BTN) buttons.add(*BTN)
await k.edit(msg, reply_markup=buttons) await k.edit(msg, reply_markup=buttons)
except Exception as err: except Exception as err:
@ -719,18 +600,12 @@ async def imdb_en_callback(bot: Client, query: CallbackQuery):
url = f"https://www.imdb.com/title/tt{movie}/" url = f"https://www.imdb.com/title/tt{movie}/"
resp = await get_content(url) resp = await get_content(url)
sop = BeautifulSoup(resp, "lxml") sop = BeautifulSoup(resp, "lxml")
r_json = json.loads( r_json = json.loads(sop.find("script", attrs={"type": "application/ld+json"}).contents[0])
sop.find("script", attrs={"type": "application/ld+json"}).contents[0]
)
res_str = "" res_str = ""
type = f"<code>{r_json['@type']}</code>" if r_json.get("@type") else "" type = f"<code>{r_json['@type']}</code>" if r_json.get("@type") else ""
if r_json.get("name"): if r_json.get("name"):
try: try:
tahun = ( tahun = sop.select('ul[data-testid="hero-title-block__metadata"]')[0].find(class_="sc-8c396aa2-2 itZqyK").text
sop.select('ul[data-testid="hero-title-block__metadata"]')[0]
.find(class_="sc-8c396aa2-2 itZqyK")
.text
)
except: except:
tahun = "-" tahun = "-"
res_str += f"<b>📹 Title:</b> <a href='{url}'>{r_json['name']} [{tahun}]</a> (<code>{type}</code>)\n" res_str += f"<b>📹 Title:</b> <a href='{url}'>{r_json['name']} [{tahun}]</a> (<code>{type}</code>)\n"
@ -739,61 +614,31 @@ async def imdb_en_callback(bot: Client, query: CallbackQuery):
else: else:
res_str += "\n" res_str += "\n"
if sop.select('li[data-testid="title-techspec_runtime"]'): if sop.select('li[data-testid="title-techspec_runtime"]'):
durasi = ( durasi = sop.select('li[data-testid="title-techspec_runtime"]')[0].find(class_="ipc-metadata-list-item__content-container").text
sop.select('li[data-testid="title-techspec_runtime"]')[0]
.find(class_="ipc-metadata-list-item__content-container")
.text
)
res_str += f"<b>Duration:</b> <code>{durasi}</code>\n" res_str += f"<b>Duration:</b> <code>{durasi}</code>\n"
if r_json.get("contentRating"): if r_json.get("contentRating"):
res_str += f"<b>Category:</b> <code>{r_json['contentRating']}</code> \n" res_str += f"<b>Category:</b> <code>{r_json['contentRating']}</code> \n"
if r_json.get("aggregateRating"): if r_json.get("aggregateRating"):
res_str += f"<b>Rating:</b> <code>{r_json['aggregateRating']['ratingValue']}⭐️ from {r_json['aggregateRating']['ratingCount']} user</code> \n" res_str += f"<b>Rating:</b> <code>{r_json['aggregateRating']['ratingValue']}⭐️ from {r_json['aggregateRating']['ratingCount']} user</code> \n"
if sop.select('li[data-testid="title-details-releasedate"]'): if sop.select('li[data-testid="title-details-releasedate"]'):
rilis = ( 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
sop.select('li[data-testid="title-details-releasedate"]')[0] 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"]
.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"<b>Release Data:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n" res_str += f"<b>Release Data:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n"
if r_json.get("genre"): if r_json.get("genre"):
genre = "".join( 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"])
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] genre = genre[:-2]
res_str += f"<b>Genre:</b> {genre}\n" res_str += f"<b>Genre:</b> {genre}\n"
if sop.select('li[data-testid="title-details-origin"]'): if sop.select('li[data-testid="title-details-origin"]'):
country = "".join( country = "".join(
f"{demoji(country.text)} #{country.text.replace(' ', '_').replace('-', '_')}, " f"{demoji(country.text)} #{country.text.replace(' ', '_').replace('-', '_')}, "
for country in sop.select('li[data-testid="title-details-origin"]')[ 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")
0
].findAll(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)
) )
country = country[:-2] country = country[:-2]
res_str += f"<b>Country:</b> {country}\n" res_str += f"<b>Country:</b> {country}\n"
if sop.select('li[data-testid="title-details-languages"]'): if sop.select('li[data-testid="title-details-languages"]'):
language = "".join( language = "".join(
f"#{lang.text.replace(' ', '_').replace('-', '_')}, " 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] language = language[:-2]
res_str += f"<b>Language:</b> {language}\n" res_str += f"<b>Language:</b> {language}\n"
@ -834,11 +679,7 @@ async def imdb_en_callback(bot: Client, query: CallbackQuery):
key_ = key_[:-2] key_ = key_[:-2]
res_str += f"<b>🔥 Keywords:</b> {key_} \n" res_str += f"<b>🔥 Keywords:</b> {key_} \n"
if sop.select('li[data-testid="award_information"]'): if sop.select('li[data-testid="award_information"]'):
awards = ( awards = sop.select('li[data-testid="award_information"]')[0].find(class_="ipc-metadata-list-item__list-content-item").text
sop.select('li[data-testid="award_information"]')[0]
.find(class_="ipc-metadata-list-item__list-content-item")
.text
)
res_str += f"<b>🏆 Awards:</b> <code>{awards}</code>\n\n" res_str += f"<b>🏆 Awards:</b> <code>{awards}</code>\n\n"
else: else:
res_str += "\n" res_str += "\n"
@ -848,23 +689,13 @@ async def imdb_en_callback(bot: Client, query: CallbackQuery):
markup = InlineKeyboardMarkup( markup = InlineKeyboardMarkup(
[ [
[ [
InlineKeyboardButton( InlineKeyboardButton("🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}"),
"🎬 Open IMDB", url=f"https://www.imdb.com{r_json['url']}"
),
InlineKeyboardButton("▶️ Trailer", url=trailer_url), InlineKeyboardButton("▶️ Trailer", url=trailer_url),
] ]
] ]
) )
else: else:
markup = InlineKeyboardMarkup( 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']}"
)
]
]
)
if thumb := r_json.get("image"): if thumb := r_json.get("image"):
try: try:
await query.message.reply_photo( await query.message.reply_photo(
@ -891,9 +722,7 @@ async def imdb_en_callback(bot: Client, query: CallbackQuery):
) )
await query.message.delete() await query.message.delete()
else: else:
await query.message.edit( await query.message.edit(res_str, reply_markup=markup, disable_web_page_preview=False)
res_str, reply_markup=markup, disable_web_page_preview=False
)
await query.answer() await query.answer()
except Exception: except Exception:
exc = traceback.format_exc() exc = traceback.format_exc()

View file

@ -47,9 +47,7 @@ async def job_close():
jam = now.strftime("%H:%M") jam = now.strftime("%H:%M")
try: try:
# version = check_output(["git log -1 --date=format:v%y.%m%d.%H%M --pretty=format:%cd"], shell=True).decode() # version = check_output(["git log -1 --date=format:v%y.%m%d.%H%M --pretty=format:%cd"], shell=True).decode()
reply_markup = InlineKeyboardMarkup( reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="❤️", callback_data="nightmd")]])
[[InlineKeyboardButton(text="❤️", callback_data="nightmd")]]
)
await app.set_chat_permissions( await app.set_chat_permissions(
-1001128045651, -1001128045651,
ChatPermissions(can_send_messages=False, can_invite_users=True), ChatPermissions(can_send_messages=False, can_invite_users=True),
@ -87,9 +85,7 @@ async def job_close_ymoviez():
jam = now.strftime("%H:%M") jam = now.strftime("%H:%M")
try: try:
# version = check_output(["git log -1 --date=format:v%y.%m%d.%H%M --pretty=format:%cd"], shell=True).decode() # version = check_output(["git log -1 --date=format:v%y.%m%d.%H%M --pretty=format:%cd"], shell=True).decode()
reply_markup = InlineKeyboardMarkup( reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="❤️", callback_data="nightmd")]])
[[InlineKeyboardButton(text="❤️", callback_data="nightmd")]]
)
await app.set_chat_permissions( await app.set_chat_permissions(
-1001255283935, -1001255283935,
ChatPermissions(can_send_messages=False, can_invite_users=True), ChatPermissions(can_send_messages=False, can_invite_users=True),
@ -126,9 +122,7 @@ async def job_open():
jam = now.strftime("%H:%M") jam = now.strftime("%H:%M")
try: try:
# version = check_output(["git log -1 --date=format:v%y.%m%d.%H%M --pretty=format:%cd"], shell=True).decode() # version = check_output(["git log -1 --date=format:v%y.%m%d.%H%M --pretty=format:%cd"], shell=True).decode()
reply_markup = InlineKeyboardMarkup( reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="❤️", callback_data="nightmd")]])
[[InlineKeyboardButton(text="❤️", callback_data="nightmd")]]
)
await app.set_chat_permissions( await app.set_chat_permissions(
-1001128045651, -1001128045651,
ChatPermissions( ChatPermissions(
@ -172,9 +166,7 @@ async def job_open_ymoviez():
jam = now.strftime("%H:%M") jam = now.strftime("%H:%M")
try: try:
# version = check_output(["git log -1 --date=format:v%y.%m%d.%H%M --pretty=format:%cd"], shell=True).decode() # version = check_output(["git log -1 --date=format:v%y.%m%d.%H%M --pretty=format:%cd"], shell=True).decode()
reply_markup = InlineKeyboardMarkup( reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="❤️", callback_data="nightmd")]])
[[InlineKeyboardButton(text="❤️", callback_data="nightmd")]]
)
await app.set_chat_permissions( await app.set_chat_permissions(
-1001255283935, -1001255283935,
ChatPermissions( ChatPermissions(

View file

@ -24,7 +24,6 @@ SOFTWARE.
from re import findall from re import findall
from pyrogram import filters from pyrogram import filters
from misskaty import app from misskaty import app
from misskaty.vars import COMMAND_HANDLER
from misskaty.core.decorator.errors import capture_err from misskaty.core.decorator.errors import capture_err
from misskaty.core.decorator.permissions import adminsOnly from misskaty.core.decorator.permissions import adminsOnly
from misskaty.core.keyboard import ikb from misskaty.core.keyboard import ikb
@ -64,11 +63,9 @@ async def save_notee(_, message):
_type = "text" if message.reply_to_message.text else "sticker" _type = "text" if message.reply_to_message.text else "sticker"
note = { note = {
"type": _type, "type": _type,
"data": message.reply_to_message.text.markdown "data": message.reply_to_message.text.markdown if _type == "text" else message.reply_to_message.sticker.file_id,
if _type == "text"
else message.reply_to_message.sticker.file_id,
} }
prefix = message.text.split()[0][0] message.text.split()[0][0]
chat_id = message.chat.id chat_id = message.chat.id
await save_note(chat_id, name, note) await save_note(chat_id, name, note)
await message.reply(f"__**Saved note {name}.**__") await message.reply(f"__**Saved note {name}.**__")
@ -77,7 +74,7 @@ async def save_notee(_, message):
@app.on_message(filters.command("notes") & ~filters.private) @app.on_message(filters.command("notes") & ~filters.private)
@capture_err @capture_err
async def get_notes(_, message): async def get_notes(_, message):
prefix = message.text.split()[0][0] message.text.split()[0][0]
chat_id = message.chat.id chat_id = message.chat.id
_notes = await get_note_names(chat_id) _notes = await get_note_names(chat_id)
@ -104,8 +101,7 @@ async def get_one_note(_, message):
data = _note["data"] data = _note["data"]
keyb = None keyb = None
if findall(r"\[.+\,.+\]", data): if findall(r"\[.+\,.+\]", data):
keyboard = extract_text_and_keyb(ikb, data) if keyboard := extract_text_and_keyb(ikb, data):
if keyboard:
data, keyb = keyboard data, keyb = keyboard
await message.reply_text( await message.reply_text(
data, data,
@ -125,7 +121,7 @@ async def del_note(_, message):
if not name: if not name:
return await message.reply("**Usage**\n__/delete [NOTE_NAME]__") return await message.reply("**Usage**\n__/delete [NOTE_NAME]__")
prefix = message.text.split()[0][0] message.text.split()[0][0]
chat_id = message.chat.id chat_id = message.chat.id
deleted = await delete_note(chat_id, name) deleted = await delete_note(chat_id, name)

View file

@ -22,9 +22,7 @@ __HELP__ = "/ocr [reply to photo] - Read Text From Image"
async def ocr(_, message): async def ocr(_, message):
reply = message.reply_to_message reply = message.reply_to_message
if not reply or not reply.photo and not reply.sticker: if not reply or not reply.photo and not reply.sticker:
return await message.reply_text( return await message.reply_text(f"Reply photo with /{message.command[0]} command")
f"Reply photo with /{message.command[0]} command"
)
msg = await message.reply("Reading image...") msg = await message.reply("Reading image...")
try: try:
file_path = await reply.download() file_path = await reply.download()

View file

@ -64,18 +64,14 @@ async def create(_, message):
reply = message.reply_to_message reply = message.reply_to_message
target = str(message.command[0]).split("@", maxsplit=1)[0] target = str(message.command[0]).split("@", maxsplit=1)[0]
if not reply and len(message.command) < 2: if not reply and len(message.command) < 2:
return await message.reply_text( return await message.reply_text(f"**Reply To A Message With /{target} or with command**")
f"**Reply To A Message With /{target} or with command**"
)
msg = await message.reply_text("`Pasting to Rentry...`") msg = await message.reply_text("`Pasting to Rentry...`")
data = "" data = ""
limit = 1024 * 1024 limit = 1024 * 1024
if reply and reply.document: if reply and reply.document:
if reply.document.file_size > limit: if reply.document.file_size > limit:
return await msg.edit( return await msg.edit(f"**You can only paste files smaller than {humanbytes(limit)}.**")
f"**You can only paste files smaller than {humanbytes(limit)}.**"
)
if not pattern.search(reply.document.mime_type): if not pattern.search(reply.document.mime_type):
return await msg.edit("**Only text files can be pasted.**") return await msg.edit("**Only text files can be pasted.**")
file = await reply.download() file = await reply.download()
@ -98,9 +94,7 @@ async def create(_, message):
if message.from_user.username: if message.from_user.username:
uname = f"@{message.from_user.username}" uname = f"@{message.from_user.username}"
else: else:
uname = ( uname = f"[{message.from_user.first_name}](tg://user?id={message.from_user.id})"
f"[{message.from_user.first_name}](tg://user?id={message.from_user.id})"
)
else: else:
uname = message.sender_chat.title uname = message.sender_chat.title
@ -113,13 +107,7 @@ async def create(_, message):
if not url: if not url:
return await msg.edit("Text Too Short Or File Problems") return await msg.edit("Text Too Short Or File Problems")
button = [[InlineKeyboardButton("Open Link", url=url)]] button = [[InlineKeyboardButton("Open Link", url=url)]]
button.append( button.append([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<a href='{url}'>.</a>\n\nPaste by {uname}**" pasted = f"**Successfully pasted your data to Rentry<a href='{url}'>.</a>\n\nPaste by {uname}**"
await msg.edit(pasted, reply_markup=InlineKeyboardMarkup(button)) await msg.edit(pasted, reply_markup=InlineKeyboardMarkup(button))
@ -130,18 +118,14 @@ async def create(_, message):
reply = message.reply_to_message reply = message.reply_to_message
target = str(message.command[0]).split("@", maxsplit=1)[0] target = str(message.command[0]).split("@", maxsplit=1)[0]
if not reply and len(message.command) < 2: if not reply and len(message.command) < 2:
return await message.reply_text( return await message.reply_text(f"**Reply To A Message With /{target} or with command**")
f"**Reply To A Message With /{target} or with command**"
)
msg = await message.reply_text("`Pasting to TempPaste...`") msg = await message.reply_text("`Pasting to TempPaste...`")
data = "" data = ""
limit = 1024 * 1024 limit = 1024 * 1024
if reply and reply.document: if reply and reply.document:
if reply.document.file_size > limit: if reply.document.file_size > limit:
return await msg.edit( return await msg.edit(f"**You can only paste files smaller than {humanbytes(limit)}.**")
f"**You can only paste files smaller than {humanbytes(limit)}.**"
)
if not pattern.search(reply.document.mime_type): if not pattern.search(reply.document.mime_type):
return await msg.edit("**Only text files can be pasted.**") return await msg.edit("**Only text files can be pasted.**")
file = await reply.download() file = await reply.download()
@ -164,9 +148,7 @@ async def create(_, message):
if message.from_user.username: if message.from_user.username:
uname = f"@{message.from_user.username}" uname = f"@{message.from_user.username}"
else: else:
uname = ( uname = f"[{message.from_user.first_name}](tg://user?id={message.from_user.id})"
f"[{message.from_user.first_name}](tg://user?id={message.from_user.id})"
)
else: else:
uname = message.sender_chat.title uname = message.sender_chat.title
@ -190,13 +172,7 @@ async def create(_, message):
if not url: if not url:
return await msg.edit("Text Too Short Or File Problems") return await msg.edit("Text Too Short Or File Problems")
button = [[InlineKeyboardButton("Open Link", url=url)]] button = [[InlineKeyboardButton("Open Link", url=url)]]
button.append( button.append([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<a href='{url}'>.</a>\n\nPaste by {uname}**" pasted = f"**Successfully pasted your data to Tempaste<a href='{url}'>.</a>\n\nPaste by {uname}**"
await msg.edit(pasted, reply_markup=InlineKeyboardMarkup(button)) await msg.edit(pasted, reply_markup=InlineKeyboardMarkup(button))

View file

@ -23,9 +23,7 @@ async def ping(_, message):
end_t = time.time() end_t = time.time()
time_taken_s = round(end_t - start_t, 3) time_taken_s = round(end_t - start_t, 3)
try: try:
await rm.edit( await rm.edit(f"<b>🐈 MissKatyBot online.</b>\n\n<b>Ping:</b> <code>{time_taken_s} detik</code>\n<b>Uptime:</b> <code>{currentTime}</code>")
f"<b>🐈 MissKatyBot online.</b>\n\n<b>Ping:</b> <code>{time_taken_s} detik</code>\n<b>Uptime:</b> <code>{currentTime}</code>"
)
except Exception: except Exception:
pass pass
@ -51,9 +49,7 @@ async def ping_handler(_, message):
check=True, check=True,
capture_output=True, capture_output=True,
) )
resp_time = findall(r"time=.+m?s", shell.stdout, MULTILINE)[0].replace( resp_time = findall(r"time=.+m?s", shell.stdout, MULTILINE)[0].replace("time=", "")
"time=", ""
)
text += f" **{dc.upper()}:** {resp_time}\n" text += f" **{dc.upper()}:** {resp_time}\n"
except Exception: except Exception:

View file

@ -38,11 +38,7 @@ async def get_message_sender_name(m: Message):
if m.forward_sender_name: if m.forward_sender_name:
return m.forward_sender_name return m.forward_sender_name
elif m.forward_from: elif m.forward_from:
return ( return f"{m.forward_from.first_name} {m.forward_from.last_name}" if m.forward_from.last_name else m.forward_from.first_name
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: elif m.forward_from_chat:
return m.forward_from_chat.title return m.forward_from_chat.title
@ -61,42 +57,22 @@ async def get_message_sender_name(m: Message):
async def get_custom_emoji(m: Message): async def get_custom_emoji(m: Message):
if m.forward_date: if m.forward_date:
return ( 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
""
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 "" return m.from_user.emoji_status.custom_emoji_id if m.from_user else ""
async def get_message_sender_username(m: Message): async def get_message_sender_username(m: Message):
if m.forward_date: if m.forward_date:
if ( if not m.forward_sender_name and not m.forward_from and m.forward_from_chat and m.forward_from_chat.username:
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 return m.forward_from_chat.username
elif ( 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:
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 "" return ""
else: else:
return m.forward_from.username or "" return m.forward_from.username or ""
elif m.from_user and m.from_user.username: elif m.from_user and m.from_user.username:
return m.from_user.username return m.from_user.username
elif ( elif m.from_user or m.sender_chat and not m.sender_chat.username or not m.sender_chat:
m.from_user or m.sender_chat and not m.sender_chat.username or not m.sender_chat
):
return "" return ""
else: else:
return m.sender_chat.username return m.sender_chat.username
@ -104,25 +80,14 @@ async def get_message_sender_username(m: Message):
async def get_message_sender_photo(m: Message): async def get_message_sender_photo(m: Message):
if m.forward_date: if m.forward_date:
if ( if not m.forward_sender_name and not m.forward_from and m.forward_from_chat and m.forward_from_chat.photo:
not m.forward_sender_name
and not m.forward_from
and m.forward_from_chat
and m.forward_from_chat.photo
):
return { return {
"small_file_id": m.forward_from_chat.photo.small_file_id, "small_file_id": m.forward_from_chat.photo.small_file_id,
"small_photo_unique_id": m.forward_from_chat.photo.small_photo_unique_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_file_id": m.forward_from_chat.photo.big_file_id,
"big_photo_unique_id": m.forward_from_chat.photo.big_photo_unique_id, "big_photo_unique_id": m.forward_from_chat.photo.big_photo_unique_id,
} }
elif ( 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:
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 "" return ""
else: else:
return ( return (
@ -200,16 +165,10 @@ async def pyrogram_to_quotly(messages):
the_message_dict_to_append["avatar"] = True the_message_dict_to_append["avatar"] = True
the_message_dict_to_append["from"] = {} 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"]["id"] = await get_message_sender_id(message)
the_message_dict_to_append["from"]["name"] = await get_message_sender_name( the_message_dict_to_append["from"]["name"] = await get_message_sender_name(message)
message the_message_dict_to_append["from"]["username"] = await get_message_sender_username(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"]["type"] = message.chat.type.name.lower()
the_message_dict_to_append["from"]["photo"] = await get_message_sender_photo( the_message_dict_to_append["from"]["photo"] = await get_message_sender_photo(message)
message
)
if message.reply_to_message: if message.reply_to_message:
the_message_dict_to_append["replyMessage"] = { the_message_dict_to_append["replyMessage"] = {
"name": await get_message_sender_name(message.reply_to_message), "name": await get_message_sender_name(message.reply_to_message),
@ -265,9 +224,7 @@ async def msg_quotly_cmd(c: Client, m: Message):
except Exception: except Exception:
return await m.reply_text("🤷🏻‍♂️") return await m.reply_text("🤷🏻‍♂️")
try: try:
messages_one = await c.get_messages( messages_one = await c.get_messages(chat_id=m.chat.id, message_ids=m.reply_to_message.id, replies=-1)
chat_id=m.chat.id, message_ids=m.reply_to_message.id, replies=-1
)
messages = [messages_one] messages = [messages_one]
except Exception: except Exception:
return await m.reply_text("🤷🏻‍♂️") return await m.reply_text("🤷🏻‍♂️")

View file

@ -8,7 +8,6 @@
# This plugin to scrape from melongmovie, and lk21 # This plugin to scrape from melongmovie, and lk21
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
import aiohttp
import re import re
import traceback import traceback
from misskaty import app, BOT_USERNAME from misskaty import app, BOT_USERNAME
@ -41,9 +40,7 @@ async def nodrakor(_, message):
msg = await message.reply("Sedang proses scrap, mohon tunggu..") msg = await message.reply("Sedang proses scrap, mohon tunggu..")
try: try:
headers = { 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"}
"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(f"https://109.234.34.246/?s={judul}", headers=headers) html = await http.get(f"https://109.234.34.246/?s={judul}", headers=headers)
soup = BeautifulSoup(html.text, "lxml") soup = BeautifulSoup(html.text, "lxml")
res = soup.find_all(class_="content-thumbnail text-center") res = soup.find_all(class_="content-thumbnail text-center")
@ -55,9 +52,7 @@ async def nodrakor(_, message):
if not data: if not data:
return await msg.edit("Oops, data film tidak ditemukan.") return await msg.edit("Oops, data film tidak ditemukan.")
res = "".join(f"<b>{i['judul']}</b>\n{i['link']}\n\n" for i in data) res = "".join(f"<b>{i['judul']}</b>\n{i['link']}\n\n" for i in data)
await msg.edit( await msg.edit(f"<b>Hasil Pencarian di Nodrakor:</b>\n{res}\nScraped by @{BOT_USERNAME}")
f"<b>Hasil Pencarian di Nodrakor:</b>\n{res}\nScraped by @{BOT_USERNAME}"
)
except Exception as e: except Exception as e:
await msg.edit(f"ERROR: {str(e)}") await msg.edit(f"ERROR: {str(e)}")
@ -72,13 +67,9 @@ async def ngefilm21(_, message):
msg = await message.reply("Sedang proses scrap, mohon tunggu..") msg = await message.reply("Sedang proses scrap, mohon tunggu..")
try: try:
headers = { 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"}
"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( html = await http.get(f"http://185.237.253.209/search?q={title}", headers=headers)
f"http://185.237.253.209/search?q={title}", headers=headers
)
soup = BeautifulSoup(html.text, "lxml") soup = BeautifulSoup(html.text, "lxml")
res = soup.find_all("h2") res = soup.find_all("h2")
data = [] data = []
@ -105,19 +96,12 @@ async def movikucc(_, message):
judul = message.text.split(" ", maxsplit=1)[1] judul = message.text.split(" ", maxsplit=1)[1]
msg = await message.reply("Sedang proses scrap, mohon tunggu..") msg = await message.reply("Sedang proses scrap, mohon tunggu..")
try: try:
headers = { 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"}
"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(f"https://107.152.39.187/?s={judul}", headers=headers) html = await http.get(f"https://107.152.39.187/?s={judul}", headers=headers)
soup = BeautifulSoup(html.text, "lxml") soup = BeautifulSoup(html.text, "lxml")
data = soup.find_all(class_="bx") data = soup.find_all(class_="bx")
res = "".join( res = "".join(f"<b>Judul: {i.find_all('a')[0]['title']}</b>\nLink: {i.find_all('a')[0]['href']}\n\n" for i in data)
f"<b>Judul: {i.find_all('a')[0]['title']}</b>\nLink: {i.find_all('a')[0]['href']}\n\n" await msg.edit(f"<b>Hasil Scrap di Movieku.cc:</b>\n{res} ⚠️ Gunakan command /movieku_scrap <b>[link]</b> untuk mengambil link download (hanya untuk movie).")
for i in data
)
await msg.edit(
f"<b>Hasil Scrap di Movieku.cc:</b>\n{res} ⚠️ Gunakan command /movieku_scrap <b>[link]</b> untuk mengambil link download (hanya untuk movie)."
)
except Exception as e: except Exception as e:
await msg.edit(f"ERROR: {str(e)}") await msg.edit(f"ERROR: {str(e)}")
@ -131,13 +115,9 @@ async def savefilm21(_, message):
judul = "" judul = ""
msg = await message.reply("Sedang proses scrap, mohon tunggu..") msg = await message.reply("Sedang proses scrap, mohon tunggu..")
try: try:
headers = { 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"}
"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( html = await http.get(f"http://185.99.135.215/?s={judul}", headers=headers, follow_redirects=False)
f"http://185.99.135.215/?s={judul}", headers=headers, follow_redirects=False
)
soup = BeautifulSoup(html.text, "lxml") soup = BeautifulSoup(html.text, "lxml")
res = soup.find_all(class_="entry-title") res = soup.find_all(class_="entry-title")
data = [] data = []
@ -148,12 +128,8 @@ async def savefilm21(_, message):
data.append({"judul": judul, "link": link}) data.append({"judul": judul, "link": link})
if not data: if not data:
return await msg.edit("Oops, data film tidak ditemukan") return await msg.edit("Oops, data film tidak ditemukan")
res = "".join( res = "".join(f"<b>Judul: {i['judul']}</b>\nLink: {i['link']}\n\n" for i in data)
f"<b>Judul: {i['judul']}</b>\nLink: {i['link']}\n\n" for i in data await msg.edit(f"Hasil Scrap <code>{judul}</code> dari Savefilm21:\n{res}\n\n⚠️ Gunakan /savefilm21_scrap <b>[link]</b> untuk mengambil link downloadnya.")
)
await msg.edit(
f"Hasil Scrap <code>{judul}</code> dari Savefilm21:\n{res}\n\n⚠️ Gunakan /savefilm21_scrap <b>[link]</b> untuk mengambil link downloadnya."
)
except Exception as e: except Exception as e:
await msg.edit(f"ERROR: {str(e)}") await msg.edit(f"ERROR: {str(e)}")
@ -168,9 +144,7 @@ async def melongmovie(_, message):
msg = await message.reply("Sedang proses scrap, mohon tunggu..") msg = await message.reply("Sedang proses scrap, mohon tunggu..")
try: try:
headers = { 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"}
"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(f"http://167.99.31.48/?s={judul}", headers=headers) html = await http.get(f"http://167.99.31.48/?s={judul}", headers=headers)
soup = BeautifulSoup(html.text, "lxml") soup = BeautifulSoup(html.text, "lxml")
@ -186,10 +160,7 @@ async def melongmovie(_, message):
data.append({"judul": title, "link": url, "kualitas": kualitas}) data.append({"judul": title, "link": url, "kualitas": kualitas})
if not data: if not data:
return await msg.edit("Oops, data film tidak ditemukan di melongmovie") return await msg.edit("Oops, data film tidak ditemukan di melongmovie")
res = "".join( res = "".join(f"<b>Judul: {i['judul']}</b>\n<b>Kualitas:</b> {i['kualitas']}\n<b>Link</b>: {i['link']}\n\n" for i in data)
f"<b>Judul: {i['judul']}</b>\n<b>Kualitas:</b> {i['kualitas']}\n<b>Link</b>: {i['link']}\n\n"
for i in data
)
# return await message.reply(json.dumps(data, indent=2, ensure_ascii=False)) # return await message.reply(json.dumps(data, indent=2, ensure_ascii=False))
return await msg.edit(res) return await msg.edit(res)
except Exception as e: except Exception as e:
@ -202,10 +173,7 @@ async def terbit21_scrap(_, message):
if len(message.command) == 1: if len(message.command) == 1:
r = await http.get("https://yasirapi.eu.org/terbit21") r = await http.get("https://yasirapi.eu.org/terbit21")
res = r.json() res = r.json()
data = "".join( data = "".join(f"**Judul: {i['judul']}**\n`{i['kategori']}`\n{i['link']}\n**Download:** [Klik Disini]({i['dl']})\n\n" for i in res["result"])
f"**Judul: {i['judul']}**\n`{i['kategori']}`\n{i['link']}\n**Download:** [Klik Disini]({i['dl']})\n\n"
for i in res["result"]
)
try: try:
return await message.reply( return await message.reply(
f"**Daftar rilis movie terbaru di web Terbit21**:\n{data}", f"**Daftar rilis movie terbaru di web Terbit21**:\n{data}",
@ -213,17 +181,12 @@ async def terbit21_scrap(_, message):
) )
except MessageTooLong: except MessageTooLong:
msg = await rentry(data) msg = await rentry(data)
return await message.reply( return await message.reply(f"Karena hasil scrape terlalu panjang, maka hasil scrape di post ke rentry.\n\n{msg}")
f"Karena hasil scrape terlalu panjang, maka hasil scrape di post ke rentry.\n\n{msg}"
)
judul = message.text.split(" ", maxsplit=1)[1] judul = message.text.split(" ", maxsplit=1)[1]
msg = await message.reply(f"Mencari film di Terbit21 dg keyword {judul}..") msg = await message.reply(f"Mencari film di Terbit21 dg keyword {judul}..")
r = await http.get(f"https://yasirapi.eu.org/terbit21?q={judul}") r = await http.get(f"https://yasirapi.eu.org/terbit21?q={judul}")
res = r.json() res = r.json()
data = "".join( data = "".join(f"**Judul: {i['judul']}**\n`{i['kategori']}`\n{i['link']}\n**Download:** [Klik Disini]({i['dl']})\n\n" for i in res["result"])
f"**Judul: {i['judul']}**\n`{i['kategori']}`\n{i['link']}\n**Download:** [Klik Disini]({i['dl']})\n\n"
for i in res["result"]
)
if not res["result"]: if not res["result"]:
return await msg.edit("Yahh, ga ada hasil ditemukan") return await msg.edit("Yahh, ga ada hasil ditemukan")
try: try:
@ -233,9 +196,7 @@ async def terbit21_scrap(_, message):
) )
except MessageTooLong: except MessageTooLong:
pesan = await rentry(data) pesan = await rentry(data)
await msg.edit( await msg.edit(f"Karena hasil scrape terlalu panjang, maka hasil scrape di post ke rentry.\n\n{pesan}")
f"Karena hasil scrape terlalu panjang, maka hasil scrape di post ke rentry.\n\n{pesan}"
)
@app.on_message(filters.command(["lk21"], COMMAND_HANDLER)) @app.on_message(filters.command(["lk21"], COMMAND_HANDLER))
@ -247,10 +208,7 @@ async def lk21_scrap(_, message):
res = r.json() res = r.json()
if res.get("detail", None): if res.get("detail", None):
return await msg.edit(f"ERROR: {res['detail']}") return await msg.edit(f"ERROR: {res['detail']}")
data = "".join( data = "".join(f"**Judul: {i['judul']}**\n`{i['kategori']}`\n{i['link']}\n**Download:** [Klik Disini]({i['dl']})\n\n" for i in res["result"])
f"**Judul: {i['judul']}**\n`{i['kategori']}`\n{i['link']}\n**Download:** [Klik Disini]({i['dl']})\n\n"
for i in res["result"]
)
try: try:
return await msg.edit( return await msg.edit(
f"**Daftar rilis movie terbaru di web LK21**:\n{data}", f"**Daftar rilis movie terbaru di web LK21**:\n{data}",
@ -258,19 +216,14 @@ async def lk21_scrap(_, message):
) )
except MessageTooLong: except MessageTooLong:
msg = await rentry(data) msg = await rentry(data)
await msg.edit( await msg.edit(f"Karena hasil scrape terlalu panjang, maka hasil scrape di post ke rentry.\n\n{msg}")
f"Karena hasil scrape terlalu panjang, maka hasil scrape di post ke rentry.\n\n{msg}"
)
judul = message.text.split(" ", maxsplit=1)[1] judul = message.text.split(" ", maxsplit=1)[1]
msg = await message.reply(f"Mencari film di lk21 dg keyword {judul}..") msg = await message.reply(f"Mencari film di lk21 dg keyword {judul}..")
r = await http.get(f"https://yasirapi.eu.org/lk21?q={judul}") r = await http.get(f"https://yasirapi.eu.org/lk21?q={judul}")
res = r.json() res = r.json()
if res.get("detail", None): if res.get("detail", None):
return await msg.edit(f"ERROR: {res['detail']}") return await msg.edit(f"ERROR: {res['detail']}")
data = "".join( data = "".join(f"**Judul: {i['judul']}**\n`{i['kategori']}`\n{i['link']}\n**Download:** [Klik Disini]({i['dl']})\n\n" for i in res["result"])
f"**Judul: {i['judul']}**\n`{i['kategori']}`\n{i['link']}\n**Download:** [Klik Disini]({i['dl']})\n\n"
for i in res["result"]
)
if not res["result"]: if not res["result"]:
return await msg.edit("Yahh, ga ada hasil ditemukan") return await msg.edit("Yahh, ga ada hasil ditemukan")
try: try:
@ -280,9 +233,7 @@ async def lk21_scrap(_, message):
) )
except MessageTooLong: except MessageTooLong:
pesan = await rentry(data) pesan = await rentry(data)
return await msg.edit( return await msg.edit(f"Karena hasil scrape terlalu panjang, maka hasil scrape di post ke rentry.\n\n{pesan}")
f"Karena hasil scrape terlalu panjang, maka hasil scrape di post ke rentry.\n\n{pesan}"
)
@app.on_message(filters.command(["gomov"], COMMAND_HANDLER)) @app.on_message(filters.command(["gomov"], COMMAND_HANDLER))
@ -295,9 +246,7 @@ async def gomov_scrap(_, message):
msg = await message.reply("Scraping GoMov Website..") msg = await message.reply("Scraping GoMov Website..")
try: try:
headers = { 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"}
"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(f"https://185.173.38.216/?s={judul}", headers=headers) html = await http.get(f"https://185.173.38.216/?s={judul}", headers=headers)
soup = BeautifulSoup(html.text, "lxml") soup = BeautifulSoup(html.text, "lxml")
@ -310,9 +259,7 @@ async def gomov_scrap(_, message):
if not DATA: if not DATA:
return await msg.edit("Oops, data film tidak ditemukan di GoMov") return await msg.edit("Oops, data film tidak ditemukan di GoMov")
res = "".join(f"<b>Judul: {i['judul']}</b>\n{i['link']}\n\n" for i in DATA) res = "".join(f"<b>Judul: {i['judul']}</b>\n{i['link']}\n\n" for i in DATA)
await msg.edit( await msg.edit(f"<b>Hasil Pencarian di website GoMov:</b>\n{res}\nScraped by @{BOT_USERNAME}")
f"<b>Hasil Pencarian di website GoMov:</b>\n{res}\nScraped by @{BOT_USERNAME}"
)
except Exception: except Exception:
exc = traceback.format_exc() exc = traceback.format_exc()
await msg.edit(f"ERROR: <code>{exc}</code>") await msg.edit(f"ERROR: <code>{exc}</code>")
@ -323,9 +270,7 @@ async def gomov_scrap(_, message):
async def savefilm21_scrap(_, message): async def savefilm21_scrap(_, message):
try: try:
link = message.text.split(" ", maxsplit=1)[1] link = message.text.split(" ", maxsplit=1)[1]
headers = { 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"}
"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, follow_redirects=False) html = await http.get(link, headers=headers, follow_redirects=False)
soup = BeautifulSoup(html.text, "lxml") soup = BeautifulSoup(html.text, "lxml")
@ -333,9 +278,7 @@ async def savefilm21_scrap(_, message):
res = "".join(f"{i.text}\n{i['href']}\n\n" for i in res) res = "".join(f"{i.text}\n{i['href']}\n\n" for i in res)
await message.reply(f"<b>Hasil Scrap dari {link}</b>:\n\n{res}") await message.reply(f"<b>Hasil Scrap dari {link}</b>:\n\n{res}")
except IndexError: except IndexError:
return await message.reply( return await message.reply("Gunakan command /savefilm21_scrap <b>[link]</b> untuk scrap link download")
"Gunakan command /savefilm21_scrap <b>[link]</b> untuk scrap link download"
)
except Exception as e: except Exception as e:
await message.reply(f"ERROR: {str(e)}") await message.reply(f"ERROR: {str(e)}")
@ -345,18 +288,14 @@ async def savefilm21_scrap(_, message):
async def nodrakor_scrap(_, message): async def nodrakor_scrap(_, message):
try: try:
link = message.text.split(" ", maxsplit=1)[1] link = message.text.split(" ", maxsplit=1)[1]
headers = { 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"}
"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, follow_redirects=False) html = await http.get(link, headers=headers, follow_redirects=False)
soup = BeautifulSoup(html.text, "lxml") soup = BeautifulSoup(html.text, "lxml")
hasil = soup.find_all(class_="gmr-download-wrap clearfix")[0] hasil = soup.find_all(class_="gmr-download-wrap clearfix")[0]
await message.reply(f"<b>Hasil Scrap dari {link}</b>:\n{hasil}") await message.reply(f"<b>Hasil Scrap dari {link}</b>:\n{hasil}")
except IndexError: except IndexError:
return await message.reply( return await message.reply("Gunakan command /nodrakor_scrap <b>[link]</b> untuk scrap link download")
"Gunakan command /nodrakor_scrap <b>[link]</b> untuk scrap link download"
)
except Exception as e: except Exception as e:
await message.reply(f"ERROR: {str(e)}") await message.reply(f"ERROR: {str(e)}")
@ -367,9 +306,7 @@ async def nodrakor_scrap(_, message):
async def muviku_scrap(_, message): async def muviku_scrap(_, message):
try: try:
link = message.text.split(" ", maxsplit=1)[1] link = message.text.split(" ", maxsplit=1)[1]
headers = { 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"}
"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) html = await http.get(link, headers=headers)
soup = BeautifulSoup(html.text, "lxml") soup = BeautifulSoup(html.text, "lxml")
@ -386,24 +323,17 @@ async def muviku_scrap(_, message):
res = "".join(f"<b>Host: {i['kualitas']}</b>\n{i['link']}\n\n" for i in data) res = "".join(f"<b>Host: {i['kualitas']}</b>\n{i['link']}\n\n" for i in data)
await message.reply(res) await message.reply(res)
except IndexError: except IndexError:
return await message.reply( return await message.reply("Gunakan command /movieku_scrap <b>[link]</b> untuk scrap link download")
"Gunakan command /movieku_scrap <b>[link]</b> untuk scrap link download"
)
except Exception as e: except Exception as e:
await message.reply(f"ERROR: {str(e)}") await message.reply(f"ERROR: {str(e)}")
@app.on_message( @app.on_message(filters.command(["melong"], COMMAND_HANDLER) & filters.user([617426792, 1985689491, 1172699512, 2024984460]))
filters.command(["melong"], COMMAND_HANDLER)
& filters.user([617426792, 1985689491, 1172699512, 2024984460])
)
@capture_err @capture_err
async def melong_scrap(_, message): async def melong_scrap(_, message):
try: try:
link = message.text.split(" ", maxsplit=1)[1] link = message.text.split(" ", maxsplit=1)[1]
headers = { 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"}
"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) html = await http.get(link, headers=headers)
soup = BeautifulSoup(html.text, "lxml") soup = BeautifulSoup(html.text, "lxml")
@ -413,6 +343,4 @@ async def melong_scrap(_, message):
rep = f"{hardsub}\n{softsub}" rep = f"{hardsub}\n{softsub}"
await message.reply(rep) await message.reply(rep)
except IndexError: except IndexError:
await message.reply( await message.reply("Gunakan command /melong <b>[link]</b> untuk scrap link download")
"Gunakan command /melong <b>[link]</b> untuk scrap link download"
)

View file

@ -33,9 +33,7 @@ async def sed(c: app, m: Message):
return return
try: try:
res = regex.sub( res = regex.sub(pattern, replace_with, text, count=count, flags=rflags, timeout=1)
pattern, replace_with, text, count=count, flags=rflags, timeout=1
)
except TimeoutError: except TimeoutError:
return await m.reply_text("Oops, your regex pattern has run for too long.") return await m.reply_text("Oops, your regex pattern has run for too long.")
except regex.error as e: except regex.error as e:

View file

@ -46,18 +46,12 @@ def get_subname(url, format):
async def ceksub(_, m): async def ceksub(_, m):
cmd = m.text.split(" ", 1) cmd = m.text.split(" ", 1)
if len(cmd) == 1: if len(cmd) == 1:
return await m.reply( return await m.reply(f"Gunakan command /{m.command[0]} [link] untuk mengecek subtitle dan audio didalam video.")
f"Gunakan command /{m.command[0]} [link] untuk mengecek subtitle dan audio didalam video."
)
link = cmd[1] link = cmd[1]
start_time = perf_counter() start_time = perf_counter()
pesan = await m.reply("Sedang memproses perintah..", quote=True) pesan = await m.reply("Sedang memproses perintah..", quote=True)
try: try:
res = ( res = (await shell_exec(f"ffprobe -loglevel 0 -print_format json -show_format -show_streams {link}"))[0]
await shell_exec(
f"ffprobe -loglevel 0 -print_format json -show_format -show_streams {link}"
)
)[0]
details = json.loads(res) details = json.loads(res)
buttons = [] buttons = []
for stream in details["streams"]: for stream in details["streams"]:
@ -101,15 +95,11 @@ ALLOWED_USER = [978550890, 617426792, 2024984460, 1533008300, 1985689491]
async def convertsrt(_, m): async def convertsrt(_, m):
reply = m.reply_to_message reply = m.reply_to_message
if not reply and reply.document: if not reply and reply.document:
return await m.reply( return await m.reply(f"Gunakan command /{m.command[0]} dengan mereply ke file ass untuk convert subtitle ke srt.")
f"Gunakan command /{m.command[0]} dengan mereply ke file ass untuk convert subtitle ke srt."
)
msg = await m.reply("Sedang memproses perintah...") msg = await m.reply("Sedang memproses perintah...")
dl = await reply.download() dl = await reply.download()
(await shell_exec(f"mediaextract -i {dl} {os.path.basename(dl)}.srt"))[0] (await shell_exec(f"mediaextract -i {dl} {os.path.basename(dl)}.srt"))[0]
await m.reply_document( await m.reply_document(f"{os.path.basename(dl)}.srt", caption=f"{os.path.basename(dl)}.srt")
f"{os.path.basename(dl)}.srt", caption=f"{os.path.basename(dl)}.srt"
)
await msg.delete() await msg.delete()
try: try:
os.remove(dl) os.remove(dl)
@ -143,9 +133,7 @@ async def stream_extract(bot, update):
format == "ass" format == "ass"
start_time = perf_counter() start_time = perf_counter()
namafile = get_subname(link, format) namafile = get_subname(link, format)
extract = (await shell_exec(f"mediaextract -i {link} -map 0:{map} {namafile}"))[ extract = (await shell_exec(f"mediaextract -i {link} -map 0:{map} {namafile}"))[0]
0
]
end_time = perf_counter() end_time = perf_counter()
timelog = "{:.2f}".format(end_time - start_time) + " second" timelog = "{:.2f}".format(end_time - start_time) + " second"
await update.message.reply_document( await update.message.reply_document(

View file

@ -39,22 +39,12 @@ async def add_keep(_, message: Message):
# @user.on_deleted_messages(filters.chat([-1001455886928, -1001255283935])) # @user.on_deleted_messages(filters.chat([-1001455886928, -1001255283935]))
async def del_msg(client, message): async def del_msg(client, message):
async for a in user.get_chat_event_log( async for a in user.get_chat_event_log(message[0].chat.id, limit=1, filters=ChatEventFilter(deleted_messages=True)):
message[0].chat.id, limit=1, filters=ChatEventFilter(deleted_messages=True)
):
try: try:
ustat = ( ustat = (await user.get_chat_member(message[0].chat.id, a.deleted_message.from_user.id)).status
await user.get_chat_member(
message[0].chat.id, a.deleted_message.from_user.id
)
).status
except: except:
ustat = enums.ChatMemberStatus.MEMBER ustat = enums.ChatMemberStatus.MEMBER
if ( if ustat in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER] or a.deleted_message.from_user.is_bot:
ustat
in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]
or a.deleted_message.from_user.is_bot
):
return return
if a.user.id == a.deleted_message.from_user.id: if a.user.id == a.deleted_message.from_user.id:
if a.deleted_message.text: if a.deleted_message.text:
@ -72,9 +62,7 @@ async def del_msg(client, message):
# @user.on_edited_message(filters.text & filters.chat(-1001455886928)) # @user.on_edited_message(filters.text & filters.chat(-1001455886928))
async def edit_msg(client, message): async def edit_msg(client, message):
try: try:
ustat = ( ustat = (await user.get_chat_member(message.chat.id, message.from_user.id)).status
await user.get_chat_member(message.chat.id, message.from_user.id)
).status
except: except:
ustat = enums.ChatMemberStatus.MEMBER ustat = enums.ChatMemberStatus.MEMBER
if message.from_user.is_bot or ustat in [ if message.from_user.is_bot or ustat in [
@ -82,12 +70,8 @@ async def edit_msg(client, message):
enums.ChatMemberStatus.OWNER, enums.ChatMemberStatus.OWNER,
]: ]:
return return
async for a in user.get_chat_event_log( async for a in user.get_chat_event_log(message.chat.id, limit=1, filters=ChatEventFilter(edited_messages=True)):
message.chat.id, limit=1, filters=ChatEventFilter(edited_messages=True) if a.old_message.text.startswith(("/mirror", "/leech", "/unzipmirror", "/unzipleech")):
):
if a.old_message.text.startswith(
("/mirror", "/leech", "/unzipmirror", "/unzipleech")
):
await app.send_message( await app.send_message(
message.chat.id, message.chat.id,
f"#EDITED_MESSAGE\n\n<a href='tg://user?id={a.user.id}'>{a.user.first_name}</a> mengedit pesannya 🧐.\n<b>Pesan:</b> {a.old_message.text}", f"#EDITED_MESSAGE\n\n<a href='tg://user?id={a.user.id}'>{a.user.first_name}</a> mengedit pesannya 🧐.\n<b>Pesan:</b> {a.old_message.text}",
@ -139,10 +123,7 @@ async def join_date(app, message: Message):
with open("joined_date.txt", "w", encoding="utf8") as f: with open("joined_date.txt", "w", encoding="utf8") as f:
f.write("Join Date First Name\n") f.write("Join Date First Name\n")
for member in members: for member in members:
f.write( f.write(str(datetime.fromtimestamp(member[1]).strftime("%y-%m-%d %H:%M")) + f" {member[0]}\n")
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") await user.send_document(message.chat.id, "joined_date.txt")
os.remove("joined_date.txt") os.remove("joined_date.txt")
@ -169,9 +150,7 @@ async def recent_act(client, message):
limit=0, limit=0,
) )
) )
with open( with open(f"recent_actions_{message.chat.id}.txt", "w", encoding="utf8") as log_file:
f"recent_actions_{message.chat.id}.txt", "w", encoding="utf8"
) as log_file:
log_file.write(str(full_log)) log_file.write(str(full_log))
await message.reply_document(f"recent_actions_{message.chat.id}.txt") await message.reply_document(f"recent_actions_{message.chat.id}.txt")

View file

@ -5,7 +5,6 @@ from pyrogram import filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from misskaty.vars import COMMAND_HANDLER from misskaty.vars import COMMAND_HANDLER
from datetime import datetime from datetime import datetime
from logging import getLogger
from hachoir.metadata import extractMetadata from hachoir.metadata import extractMetadata
from hachoir.parser import createParser from hachoir.parser import createParser
from misskaty.helper.ytdl_helper import random_char, DownLoadFile from misskaty.helper.ytdl_helper import random_char, DownLoadFile
@ -21,15 +20,11 @@ user_time = {}
@capture_err @capture_err
async def ytdown(_, message): async def ytdown(_, message):
if len(message.command) == 1: if len(message.command) == 1:
return await message.reply( return await message.reply(f"Gunakan command /{message.command[0]} YT_LINK untuk download video dengan YT-DLP.")
f"Gunakan command /{message.command[0]} YT_LINK untuk download video dengan YT-DLP."
)
userLastDownloadTime = user_time.get(message.chat.id) userLastDownloadTime = user_time.get(message.chat.id)
try: try:
if userLastDownloadTime > datetime.now(): if userLastDownloadTime > datetime.now():
wait_time = round( wait_time = round((userLastDownloadTime - datetime.now()).total_seconds() / 60, 2)
(userLastDownloadTime - datetime.now()).total_seconds() / 60, 2
)
await message.reply_text(f"Wait {wait_time} Minutes before next request..") await message.reply_text(f"Wait {wait_time} Minutes before next request..")
return return
except: except:
@ -53,9 +48,7 @@ async def ytdown(_, message):
save_ytdl_json_path = f"YT_Down/{str(message.from_user.id)}{randem}.json" save_ytdl_json_path = f"YT_Down/{str(message.from_user.id)}{randem}.json"
with open(save_ytdl_json_path, "w", encoding="utf8") as outfile: with open(save_ytdl_json_path, "w", encoding="utf8") as outfile:
json.dump(response_json, outfile, ensure_ascii=False) json.dump(response_json, outfile, ensure_ascii=False)
duration = None duration = response_json["duration"] if "duration" in response_json else None
if "duration" in response_json:
duration = response_json["duration"]
if "formats" in response_json: if "formats" in response_json:
for formats in response_json["formats"]: for formats in response_json["formats"]:
format_id = formats.get("format_id") format_id = formats.get("format_id")
@ -129,27 +122,19 @@ async def ytdown(_, message):
format_id = response_json["format_id"] format_id = response_json["format_id"]
format_ext = response_json["ext"] format_ext = response_json["ext"]
cb_string_file = f"ytdl|file|{format_id}|{format_ext}|{randem}" cb_string_file = f"ytdl|file|{format_id}|{format_ext}|{randem}"
cb_string_video = f'ytdl|{"video"}|{format_id}|{format_ext}|{randem}' cb_string_video = f"ytdl|video|{format_id}|{format_ext}|{randem}"
inline_keyboard.append( inline_keyboard.append(
[ [
InlineKeyboardButton( InlineKeyboardButton("SVideo", callback_data=(cb_string_video).encode("UTF-8")),
"SVideo", callback_data=(cb_string_video).encode("UTF-8") InlineKeyboardButton("DFile", callback_data=(cb_string_file).encode("UTF-8")),
),
InlineKeyboardButton(
"DFile", callback_data=(cb_string_file).encode("UTF-8")
),
] ]
) )
cb_string_file = f'{"file"}={format_id}={format_ext}' cb_string_file = f"file={format_id}={format_ext}"
cb_string_video = f'{"video"}={format_id}={format_ext}' cb_string_video = f"video={format_id}={format_ext}"
inline_keyboard.append( inline_keyboard.append(
[ [
InlineKeyboardButton( InlineKeyboardButton("video", callback_data=(cb_string_video).encode("UTF-8")),
"video", callback_data=(cb_string_video).encode("UTF-8") InlineKeyboardButton("file", callback_data=(cb_string_file).encode("UTF-8")),
),
InlineKeyboardButton(
"file", callback_data=(cb_string_file).encode("UTF-8")
),
] ]
) )
reply_markup = InlineKeyboardMarkup(inline_keyboard) reply_markup = InlineKeyboardMarkup(inline_keyboard)
@ -175,23 +160,19 @@ async def ytdown(_, message):
) )
else: else:
cb_string_file = f'{"file"}={"LFO"}={"NONE"}' cb_string_file = "file=LFO=NONE"
cb_string_video = f'{"video"}={"OFL"}={"ENON"}' cb_string_video = "video=OFL=ENON"
inline_keyboard.append( inline_keyboard.append(
[ [
InlineKeyboardButton( InlineKeyboardButton("SVideo", callback_data=(cb_string_video).encode("UTF-8")),
"SVideo", callback_data=(cb_string_video).encode("UTF-8") InlineKeyboardButton("DFile", callback_data=(cb_string_file).encode("UTF-8")),
),
InlineKeyboardButton(
"DFile", callback_data=(cb_string_file).encode("UTF-8")
),
] ]
) )
reply_markup = InlineKeyboardMarkup(inline_keyboard) reply_markup = InlineKeyboardMarkup(inline_keyboard)
await message.reply_photo( await message.reply_photo(
photo="https://telegra.ph/file/ce37f8203e1903feed544.png", photo="https://telegra.ph/file/ce37f8203e1903feed544.png",
quote=True, quote=True,
caption=f"""Select the desired format: <a href='{""}'>file size might be approximate</a>""", caption="Select the desired format: <a href=''>file size might be approximate</a>",
reply_markup=reply_markup, reply_markup=reply_markup,
reply_to_message_id=message.id, reply_to_message_id=message.id,
) )
@ -214,15 +195,11 @@ async def youtube_dl_call_back(bot, update):
await update.message.delete() await update.message.delete()
return False return False
custom_file_name = ( custom_file_name = f"{str(response_json.get('title'))}_{youtube_dl_format}.{youtube_dl_ext}"
f"{str(response_json.get('title'))}_{youtube_dl_format}.{youtube_dl_ext}"
)
custom_file_name = "%(title,fulltitle,alt_title)s %(height& |)s%(height|)s%(height&p|)s%(fps|)s%(fps&fps|)s%(tbr& |)s%(tbr|)d.%(ext)s" custom_file_name = "%(title,fulltitle,alt_title)s %(height& |)s%(height|)s%(height&p|)s%(fps|)s%(fps&fps|)s%(tbr& |)s%(tbr|)d.%(ext)s"
youtube_dl_url = update.message.reply_to_message.text.split(" ", 1)[1] youtube_dl_url = update.message.reply_to_message.text.split(" ", 1)[1]
await update.message.edit_caption("Trying to download media...") await update.message.edit_caption("Trying to download media...")
tmp_directory_for_each_user = os.path.join( tmp_directory_for_each_user = os.path.join(f"downloads/{str(update.from_user.id)}{random_char(5)}")
f"downloads/{str(update.from_user.id)}{random_char(5)}"
)
if not os.path.isdir(tmp_directory_for_each_user): if not os.path.isdir(tmp_directory_for_each_user):
os.makedirs(tmp_directory_for_each_user) os.makedirs(tmp_directory_for_each_user)
download_directory = os.path.join(tmp_directory_for_each_user, custom_file_name) download_directory = os.path.join(tmp_directory_for_each_user, custom_file_name)
@ -243,9 +220,7 @@ async def youtube_dl_call_back(bot, update):
download_directory_dirname = os.path.dirname(download_directory) download_directory_dirname = os.path.dirname(download_directory)
download_directory_contents = os.listdir(download_directory_dirname) download_directory_contents = os.listdir(download_directory_dirname)
for download_directory_c in download_directory_contents: for download_directory_c in download_directory_contents:
current_file_name = os.path.join( current_file_name = os.path.join(download_directory_dirname, download_directory_c)
download_directory_dirname, download_directory_c
)
file_size = os.stat(current_file_name).st_size file_size = os.stat(current_file_name).st_size
if file_size == 0: if file_size == 0:
@ -254,11 +229,7 @@ async def youtube_dl_call_back(bot, update):
return return
if file_size > 2097152000: if file_size > 2097152000:
await update.message.edit_caption( await update.message.edit_caption(caption=f"I cannot upload files greater than 1.95GB due to Telegram API limitations. This file has size {get_readable_file_size(file_size)}.")
caption="I cannot upload files greater than 1.95GB due to Telegram API limitations. This file has size {}.".format(
get_readable_file_size(file_size)
)
)
asyncio.create_task(clendir(thumb_image_path)) asyncio.create_task(clendir(thumb_image_path))
asyncio.create_task(clendir(tmp_directory_for_each_user)) asyncio.create_task(clendir(tmp_directory_for_each_user))
return return
@ -353,11 +324,7 @@ async def youtube_dl_call_back(bot, update):
LOGGER.info("Did this happen? :\\") LOGGER.info("Did this happen? :\\")
end_two = datetime.now() end_two = datetime.now()
time_taken_for_upload = (end_two - end_one).seconds time_taken_for_upload = (end_two - end_one).seconds
await update.message.edit_caption( await update.message.edit_caption(caption=f"Downloaded in {time_taken_for_download} seconds.\nUploaded in {time_taken_for_upload} seconds.")
caption="Downloaded in {} seconds.\nUploaded in {} seconds.".format(
time_taken_for_download, time_taken_for_upload
)
)
asyncio.create_task(clendir(thumb_image_path)) asyncio.create_task(clendir(thumb_image_path))
asyncio.create_task(clendir(tmp_directory_for_each_user)) asyncio.create_task(clendir(tmp_directory_for_each_user))
await asyncio.sleep(5) await asyncio.sleep(5)

View file

@ -52,13 +52,9 @@ FORWARD_FROM_CHAT_ID = list(
} }
) )
# Forward To Chat ID # Forward To Chat ID
FORWARD_TO_CHAT_ID = list( FORWARD_TO_CHAT_ID = list({int(x) for x in environ.get("FORWARD_TO_CHAT_ID", "-1001210537567").split()})
{int(x) for x in environ.get("FORWARD_TO_CHAT_ID", "-1001210537567").split()}
)
FORWARD_FILTERS = list(set(environ.get("FORWARD_FILTERS", "video document").split())) FORWARD_FILTERS = list(set(environ.get("FORWARD_FILTERS", "video document").split()))
BLOCK_FILES_WITHOUT_EXTENSIONS = bool( BLOCK_FILES_WITHOUT_EXTENSIONS = bool(environ.get("BLOCK_FILES_WITHOUT_EXTENSIONS", True))
environ.get("BLOCK_FILES_WITHOUT_EXTENSIONS", True)
)
BLOCKED_EXTENSIONS = list( BLOCKED_EXTENSIONS = list(
set( set(
environ.get( environ.get(

View file

@ -39,14 +39,13 @@ async def auto_clean():
if not await is_cleanmode_on(chat_id): if not await is_cleanmode_on(chat_id):
continue continue
for x in cleanmode[chat_id]: for x in cleanmode[chat_id]:
if datetime.now() > x["timer_after"]: if datetime.now() <= x["timer_after"]:
try: continue
await app.delete_messages(chat_id, x["msg_id"]) try:
except FloodWait as e: await app.delete_messages(chat_id, x["msg_id"])
await asyncio.sleep(e.value) except FloodWait as e:
except: await asyncio.sleep(e.value)
continue except:
else:
continue continue
except: except:
continue continue