reformating: code

This commit is contained in:
yasirarism 2023-01-09 06:01:38 +00:00
parent 2c42dd6445
commit 972fcdcac7
13 changed files with 213 additions and 815 deletions

View file

@ -56,7 +56,7 @@ def capture_err(func):
try: try:
await app.send_message(LOG_CHANNEL, x) await app.send_message(LOG_CHANNEL, x)
await message.reply(x) await message.reply(x)
except FloodWait as e: except FloodWait:
await asyncio.sleep(x.value) await asyncio.sleep(x.value)
raise err raise err

View file

@ -60,12 +60,7 @@ async def admin_cache_func(_, cmu):
try: try:
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}]")
except: except:
@ -155,9 +150,7 @@ async def kickFunc(client, 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(client, message): async def banFunc(client, 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)
@ -169,23 +162,14 @@ async def banFunc(client, 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":
@ -233,33 +217,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 == c.me.id: if userid == c.me.id:
@ -268,9 +244,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)
@ -299,17 +273,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")
@ -359,9 +327,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(client, message): async def promoteFunc(client, message):
try: try:
@ -471,15 +437,10 @@ async def mute(client, 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]
@ -555,9 +516,7 @@ async def warn_user(client, 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)),
@ -590,8 +549,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]
@ -616,8 +574,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]
@ -636,8 +593,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]
@ -654,9 +610,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
@ -687,13 +641,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:
@ -708,28 +656,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

@ -50,9 +50,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()
@ -66,9 +64,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(_, m): async def shell(_, m):
cmd = m.text.split(" ", 1) cmd = m.text.split(" ", 1)
if len(cmd) == 1: if len(cmd) == 1:
@ -81,15 +77,7 @@ async def shell(_, m):
await m.reply_document( await m.reply_document(
document=doc, document=doc,
file_name=doc.name, file_name=doc.name,
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="❌ Close", callback_data=f"close#{m.from_user.id}")]]),
[
[
InlineKeyboardButton(
text="❌ Close", callback_data=f"close#{m.from_user.id}"
)
]
]
),
) )
try: try:
os.remove("shell_output.txt") os.remove("shell_output.txt")
@ -99,15 +87,7 @@ async def shell(_, m):
await m.reply( await m.reply(
shell, shell,
parse_mode=enums.ParseMode.HTML, parse_mode=enums.ParseMode.HTML,
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="❌ Close", callback_data=f"close#{m.from_user.id}")]]),
[
[
InlineKeyboardButton(
text="❌ Close", callback_data=f"close#{m.from_user.id}"
)
]
]
),
) )
else: else:
await m.reply("No Reply") await m.reply("No Reply")
@ -157,15 +137,7 @@ async def evaluation_cmd_t(_, m):
document="MissKatyEval.txt", document="MissKatyEval.txt",
caption=f"<code>{cmd[: 4096 // 4 - 1]}</code>", caption=f"<code>{cmd[: 4096 // 4 - 1]}</code>",
disable_notification=True, disable_notification=True,
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="❌ Close", callback_data=f"close#{m.from_user.id}")]]),
[
[
InlineKeyboardButton(
text="❌ Close", callback_data=f"close#{m.from_user.id}"
)
]
]
),
) )
os.remove("MissKatyEval.txt") os.remove("MissKatyEval.txt")
await status_message.delete() await status_message.delete()
@ -173,32 +145,17 @@ async def evaluation_cmd_t(_, m):
await status_message.edit( await status_message.edit(
final_output, final_output,
parse_mode=enums.ParseMode.MARKDOWN, parse_mode=enums.ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="❌ Close", callback_data=f"close#{m.from_user.id}")]]),
[
[
InlineKeyboardButton(
text="❌ Close", callback_data=f"close#{m.from_user.id}"
)
]
]
),
) )
async def aexec(code, c, m): async def aexec(code, c, m):
exec( exec("async def __aexec(c, m): " + "\n p = print" + "\n replied = m.reply_to_message" + "".join(f"\n {l_}" for l_ in code.split("\n")))
"async def __aexec(c, m): "
+ "\n p = print"
+ "\n replied = m.reply_to_message"
+ "".join(f"\n {l_}" for l_ in code.split("\n"))
)
return await locals()["__aexec"](c, m) return await locals()["__aexec"](c, m)
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

@ -40,9 +40,7 @@ async def genss(client, message):
media = v media = v
break break
if media is None: if media is None:
return await message.reply( return await message.reply("Reply to a Telegram Video or document as video to generate screenshoot!")
"Reply to a Telegram Video or document as video to generate screenshoot!"
)
process = await message.reply_text("`Processing, please wait..`") process = await message.reply_text("`Processing, please wait..`")
c_time = time.time() c_time = time.time()
the_real_download_location = await client.download_media( the_real_download_location = await client.download_media(
@ -64,16 +62,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),
] ]
) )
@ -81,9 +75,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),
] ]
) )
@ -115,13 +107,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):
@ -133,9 +121,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,23 +67,15 @@ 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))
@capture_err @capture_err
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:
@ -108,21 +94,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,
@ -131,30 +111,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}")
@ -183,9 +151,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>",
@ -200,9 +166,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"),
] ]
] ]
@ -215,14 +179,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()
@ -253,9 +213,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,
@ -287,16 +245,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_,
@ -341,9 +295,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}")
@ -356,15 +308,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)}")
@ -382,9 +330,7 @@ async def kickme(_, message):
await message.reply_text(txt) await message.reply_text(txt)
await message.chat.unban_member(message.from_user.id) await message.chat.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)}"
)
except Exception as err: except Exception as err:
await message.reply(f"ERROR: {err}") await message.reply(f"ERROR: {err}")

View file

@ -9,7 +9,7 @@ from pyrogram.types import (
from misskaty import app, BOT_USERNAME from misskaty import app, BOT_USERNAME
from misskaty.vars import COMMAND_HANDLER from misskaty.vars import COMMAND_HANDLER
from misskaty.core.decorator.errors import capture_err from misskaty.core.decorator.errors import capture_err
from misskaty.helper.tools import rentry, get_random_string, GENRES_EMOJI from misskaty.helper.tools import GENRES_EMOJI
LOGGER = getLogger(__name__) LOGGER = getLogger(__name__)
@ -55,9 +55,7 @@ async def imdbcari_id(client, query: CallbackQuery):
r = await ambil_source(f"https://yasirapi.eu.org/imdb-search?q={kueri}") r = await ambil_source(f"https://yasirapi.eu.org/imdb-search?q={kueri}")
res = json.loads(r).get("result") res = json.loads(r).get("result")
if not res: if not res:
return await query.message.edit_caption( return await query.message.edit_caption(f"⛔️ Tidak ditemukan hasil untuk kueri: <code>{kueri}</code>")
f"⛔️ Tidak ditemukan hasil untuk kueri: <code>{kueri}</code>"
)
msg += f"🎬 Ditemukan ({len(res)}) hasil dari: <code>{kueri}</code> ~ {query.from_user.mention}\n\n" msg += f"🎬 Ditemukan ({len(res)}) hasil dari: <code>{kueri}</code> ~ {query.from_user.mention}\n\n"
for num, movie in enumerate(res, start=1): for num, movie in enumerate(res, start=1):
title = movie.get("l") title = movie.get("l")
@ -65,18 +63,12 @@ async def imdbcari_id(client, query: CallbackQuery):
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"{num}. {title} {year} - {type}\n" msg += f"{num}. {title} {year} - {type}\n"
BTN.append( BTN.append(InlineKeyboardButton(text=num, callback_data=f"imdbres_id#{uid}#{movieID}"))
InlineKeyboardButton(
text=num, callback_data=f"imdbres_id#{uid}#{movieID}"
)
)
BTN.append(InlineKeyboardButton(text="❌ Close", callback_data=f"close#{uid}")) BTN.append(InlineKeyboardButton(text="❌ Close", callback_data=f"close#{uid}"))
buttons.add(*BTN) buttons.add(*BTN)
await query.message.edit_caption(msg, reply_markup=buttons) await query.message.edit_caption(msg, reply_markup=buttons)
except Exception as err: except Exception as err:
await query.message.edit_caption( await query.message.edit_caption(f"Ooppss, gagal mendapatkan daftar judul di IMDb.\n\n<b>ERROR:</b> <code>{err}</code>")
f"Ooppss, gagal mendapatkan daftar judul di IMDb.\n\n<b>ERROR:</b> <code>{err}</code>"
)
@app.on_callback_query(filters.regex("^imdbcari_en")) @app.on_callback_query(filters.regex("^imdbcari_en"))
@ -94,9 +86,7 @@ async def imdbcari_en(client, query: CallbackQuery):
r = await ambil_source(f"https://yasirapi.eu.org/imdb-search?q={kueri}") r = await ambil_source(f"https://yasirapi.eu.org/imdb-search?q={kueri}")
res = json.loads(r).get("result") res = json.loads(r).get("result")
if not res: if not res:
return await query.message.edit_caption( return await query.message.edit_caption(f"⛔️ Result not found for keywords: <code>{kueri}</code>")
f"⛔️ Result not found for keywords: <code>{kueri}</code>"
)
msg += f"🎬 Found ({len(res)}) result for keywords: <code>{kueri}</code> ~ {query.from_user.mention}\n\n" msg += f"🎬 Found ({len(res)}) result for keywords: <code>{kueri}</code> ~ {query.from_user.mention}\n\n"
for num, movie in enumerate(res, start=1): for num, movie in enumerate(res, start=1):
title = movie.get("l") title = movie.get("l")
@ -104,22 +94,12 @@ async def imdbcari_en(client, query: CallbackQuery):
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"{num}. {title} {year} - {type}\n" msg += f"{num}. {title} {year} - {type}\n"
BTN.append( BTN.append(InlineKeyboardButton(text=num, callback_data=f"imdbres_en#{query.from_user.id}#{movieID}"))
InlineKeyboardButton( BTN.append(InlineKeyboardButton(text="❌ Close", callback_data=f"close#{query.from_user.id}"))
text=num, callback_data=f"imdbres_en#{query.from_user.id}#{movieID}"
)
)
BTN.append(
InlineKeyboardButton(
text="❌ Close", callback_data=f"close#{query.from_user.id}"
)
)
buttons.add(*BTN) buttons.add(*BTN)
await query.message.edit_caption(msg, reply_markup=buttons) await query.message.edit_caption(msg, reply_markup=buttons)
except Exception as err: except Exception as err:
await query.message.edit_caption( await query.message.edit_caption(f"Failed when requesting movies title @ IMDb\n\n<b>ERROR:</b> <code>{err}</code>")
f"Failed when requesting movies title @ IMDb\n\n<b>ERROR:</b> <code>{err}</code>"
)
@app.on_callback_query(filters.regex("^imdbres_id")) @app.on_callback_query(filters.regex("^imdbres_id"))
@ -132,18 +112,12 @@ async def imdb_id_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>📹 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"
@ -152,41 +126,21 @@ async def imdb_id_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>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 = "" genre = ""
for i in r_json["genre"]: for i in r_json["genre"]:
if i in GENRES_EMOJI: if i in GENRES_EMOJI:
genre += ( genre += f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, "
f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, "
)
else: else:
genre += f"#{i.replace('-', '_').replace(' ', '_')}, " genre += f"#{i.replace('-', '_').replace(' ', '_')}, "
genre = genre[:-2] genre = genre[:-2]
@ -194,22 +148,13 @@ async def imdb_id_callback(bot: Client, query: CallbackQuery):
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"
@ -240,9 +185,7 @@ async def imdb_id_callback(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(",")
@ -253,11 +196,7 @@ async def imdb_id_callback(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"
@ -267,33 +206,19 @@ async def imdb_id_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.edit_media( await query.message.edit_media(InputMediaPhoto(thumb, caption=res_str), reply_markup=markup)
InputMediaPhoto(thumb, caption=res_str), reply_markup=markup
)
except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty): except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty):
poster = thumb.replace(".jpg", "._V1_UX360.jpg") poster = thumb.replace(".jpg", "._V1_UX360.jpg")
await query.message.edit_media( await query.message.edit_media(InputMediaPhoto(poster, caption=res_str), reply_markup=markup)
InputMediaPhoto(poster, caption=res_str), reply_markup=markup
)
except Exception: except Exception:
await query.message.edit_caption(res_str, reply_markup=markup) await query.message.edit_caption(res_str, reply_markup=markup)
else: else:
@ -315,18 +240,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"
@ -335,39 +254,21 @@ 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 = "" genre = ""
for i in r_json["genre"]: for i in r_json["genre"]:
if i in GENRES_EMOJI: if i in GENRES_EMOJI:
genre += ( genre += f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, "
f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, "
)
else: else:
genre += f"#{i.replace('-', '_').replace(' ', '_')}, " genre += f"#{i.replace('-', '_').replace(' ', '_')}, "
genre = genre[:-2] genre = genre[:-2]
@ -375,22 +276,13 @@ async def imdb_en_callback(bot: Client, query: CallbackQuery):
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"
@ -431,11 +323,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"
@ -445,33 +333,19 @@ 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.edit_media( await query.message.edit_media(InputMediaPhoto(thumb, caption=res_str), reply_markup=markup)
InputMediaPhoto(thumb, caption=res_str), reply_markup=markup
)
except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty): except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty):
poster = thumb.replace(".jpg", "._V1_UX360.jpg") poster = thumb.replace(".jpg", "._V1_UX360.jpg")
await query.message.edit_media( await query.message.edit_media(InputMediaPhoto(poster, caption=res_str), reply_markup=markup)
InputMediaPhoto(poster, caption=res_str), reply_markup=markup
)
except Exception: except Exception:
await query.message.edit_caption(res_str, reply_markup=markup) await query.message.edit_caption(res_str, reply_markup=markup)
else: else:

View file

@ -39,12 +39,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 = "Dead" if not await app.get_me() else "Alive" bot_state = "Dead" if not await app.get_me() else "Alive"
@ -68,27 +63,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,
), ),
] ]
@ -101,13 +90,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"):
@ -130,9 +114,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(
@ -156,9 +138,7 @@ async def inline_menu(_, inline_query: InlineQuery):
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
inline_query.stop_propagation() inline_query.stop_propagation()
return return
namanya = ( namanya = f"{diaa.first_name} {diaa.last_name}" if diaa.last_name else diaa.first_name
f"{diaa.first_name} {diaa.last_name}" if diaa.last_name else diaa.first_name
)
msg = f"<b>🏷 Name:</b> {namanya}\n<b>🆔 ID:</b> <code>{diaa.id}</code>\n" msg = f"<b>🏷 Name:</b> {namanya}\n<b>🆔 ID:</b> <code>{diaa.id}</code>\n"
if diaa.username: if diaa.username:
msg += f"<b>🌐 Username:</b> <code>@{diaa.username}</code>\n" msg += f"<b>🌐 Username:</b> <code>@{diaa.username}</code>\n"
@ -206,11 +186,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",
@ -219,14 +195,8 @@ async def inline_menu(_, inline_query: InlineQuery):
], ],
] ]
) )
mention = ( mention = f"<a href='tg://user?id={penerima.id}'>{penerima.first_name}</a>" if not penerima.username else f"@{penerima.username}"
f"<a href='tg://user?id={penerima.id}'>{penerima.first_name}</a>" msg_c = f"🔒 A <b>private message</b> to {mention} [<code>{penerima.id}</code>], "
if not penerima.username
else f"@{penerima.username}"
)
msg_c = (
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(
@ -246,9 +216,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 = []
@ -271,9 +239,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(
@ -292,9 +258,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:
@ -315,9 +279,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(
@ -336,9 +298,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 = []
@ -350,9 +310,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"
@ -371,9 +329,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(
@ -392,9 +348,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:
@ -403,11 +357,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(
@ -482,53 +432,29 @@ 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 = "" genre = ""
@ -542,22 +468,14 @@ async def imdb_inl(_, query):
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"
@ -588,9 +506,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(",")
@ -601,11 +517,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

@ -23,15 +23,7 @@ async def jsonify(_, message):
try: try:
await message.reply_text( await message.reply_text(
f"<code>{the_real_message}</code>", f"<code>{the_real_message}</code>",
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="❌ Close", callback_data=f"close#{msg.from_user.id}")]]),
[
[
InlineKeyboardButton(
text="❌ Close", callback_data=f"close#{msg.from_user.id}"
)
]
]
),
) )
except Exception as e: except Exception as e:
with open("json.text", "w+", encoding="utf8") as out_file: with open("json.text", "w+", encoding="utf8") as out_file:
@ -41,14 +33,6 @@ async def jsonify(_, message):
caption=f"<code>{str(e)}</code>", caption=f"<code>{str(e)}</code>",
disable_notification=True, disable_notification=True,
reply_to_message_id=reply_to_id, reply_to_message_id=reply_to_id,
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="❌ Close", callback_data=f"close#{msg.from_user.id}")]]),
[
[
InlineKeyboardButton(
text="❌ Close", callback_data=f"close#{msg.from_user.id}"
)
]
]
),
) )
os.remove("json.text") os.remove("json.text")

View file

@ -6,7 +6,7 @@
* Copyright @YasirPedia All rights reserved * Copyright @YasirPedia All rights reserved
""" """
import os, re import os
import aiohttp import aiohttp
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
import json import json
@ -15,26 +15,20 @@ from pyrogram import Client, filters
from deep_translator import GoogleTranslator from deep_translator import GoogleTranslator
from gtts import gTTS from gtts import gTTS
from pyrogram.errors import ( from pyrogram.errors import (
MediaEmpty,
MessageNotModified,
PhotoInvalidDimensions,
UserNotParticipant, UserNotParticipant,
WebpageMediaEmpty,
MessageTooLong, MessageTooLong,
) )
from utils import extract_user, get_file_id, demoji from utils import extract_user, get_file_id
import time import time
from datetime import datetime from datetime import datetime
from logging import getLogger from logging import getLogger
from pykeyboard import InlineKeyboard
from pyrogram.types import ( from pyrogram.types import (
InlineKeyboardMarkup, InlineKeyboardMarkup,
InlineKeyboardButton, InlineKeyboardButton,
CallbackQuery, CallbackQuery,
InputMediaPhoto,
) )
from misskaty.core.decorator.errors import capture_err from misskaty.core.decorator.errors import capture_err
from misskaty.helper.tools import rentry, get_random_string, GENRES_EMOJI from misskaty.helper.tools import rentry
from misskaty.vars import COMMAND_HANDLER from misskaty.vars import COMMAND_HANDLER
from misskaty.helper.http import http from misskaty.helper.http import http
from misskaty import app, BOT_USERNAME from misskaty import app, BOT_USERNAME
@ -52,6 +46,7 @@ __HELP__ = """
LIST_CARI = {} LIST_CARI = {}
def remove_html_tags(text): def remove_html_tags(text):
"""Remove html tags from a string""" """Remove html tags from a string"""
import re import re
@ -65,21 +60,13 @@ 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()
msg = await message.reply("Getting data..") msg = await message.reply("Getting data..")
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 msg.edit(hasil) await msg.edit(hasil)
@ -98,10 +85,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,
@ -130,9 +114,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)
@ -145,9 +127,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:
@ -161,14 +141,10 @@ async def translate(client, message):
try: try:
my_translator = GoogleTranslator(source="auto", target=target_lang) my_translator = GoogleTranslator(source="auto", target=target_lang)
result = my_translator.translate(text=text) result = my_translator.translate(text=text)
await msg.edit( await msg.edit(f"Translation using source = {my_translator.source} and target = {my_translator.target}\n\n-> {result}")
f"Translation using source = {my_translator.source} and target = {my_translator.target}\n\n-> {result}"
)
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}"
)
except Exception as err: except Exception as err:
await msg.edit(f"Error: <code>{str(err)}</code>") await msg.edit(f"Error: <code>{str(err)}</code>")
@ -176,9 +152,7 @@ async def translate(client, message):
@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:
@ -230,16 +204,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@{client.me.username}")
photo=photo, caption=f"Sticker -> Image\n@{client.me.username}"
)
os.remove(photo) os.remove(photo)
except Exception as e: except Exception as e:
@ -272,16 +242,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)
@ -314,23 +278,13 @@ 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:
local_user_photo = await client.download_media(message=chat_photo.big_file_id) local_user_photo = await client.download_media(message=chat_photo.big_file_id)
buttons = [ buttons = [[InlineKeyboardButton("🔐 Close", callback_data=f"close#{message.from_user.id}")]]
[
InlineKeyboardButton(
"🔐 Close", callback_data=f"close#{message.from_user.id}"
)
]
]
reply_markup = InlineKeyboardMarkup(buttons) reply_markup = InlineKeyboardMarkup(buttons)
await message.reply_photo( await message.reply_photo(
photo=local_user_photo, photo=local_user_photo,
@ -341,13 +295,7 @@ async def who_is(client, message):
) )
os.remove(local_user_photo) os.remove(local_user_photo)
else: else:
buttons = [ buttons = [[InlineKeyboardButton("🔐 Close", callback_data=f"close#{message.from_user.id}")]]
[
InlineKeyboardButton(
"🔐 Close", callback_data=f"close#{message.from_user.id}"
)
]
]
reply_markup = InlineKeyboardMarkup(buttons) reply_markup = InlineKeyboardMarkup(buttons)
await message.reply_text( await message.reply_text(
text=message_out_str, text=message_out_str,
@ -366,9 +314,7 @@ async def close_callback(bot: Client, query: CallbackQuery):
await query.message.delete() await query.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):
@ -421,22 +367,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:
@ -445,19 +385,13 @@ 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>")
else: else:
await query.answer("Tombol ini bukan untukmu", show_alert=True) await query.answer("Tombol ini bukan untukmu", show_alert=True)

View file

@ -11,9 +11,8 @@ from bs4 import BeautifulSoup
import re import re
import asyncio import asyncio
from logging import getLogger from logging import getLogger
from misskaty import app, BOT_USERNAME from misskaty import app
from pyrogram import filters from pyrogram import filters
from pyrogram.errors import MessageTooLong
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from misskaty.vars import COMMAND_HANDLER from misskaty.vars import COMMAND_HANDLER
from misskaty.core.decorator.errors import capture_err from misskaty.core.decorator.errors import capture_err
@ -34,9 +33,7 @@ __HELP__ = """
LOGGER = getLogger(__name__) LOGGER = getLogger(__name__)
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"
}
@app.on_message(filters.command(["zonafilm"], COMMAND_HANDLER)) @app.on_message(filters.command(["zonafilm"], COMMAND_HANDLER))
@ -73,11 +70,7 @@ async def zonafilm(_, msg):
await m.delete() await m.delete()
for c, i in enumerate(data, start=1): for c, i in enumerate(data, start=1):
msgs += f"<b>{c}. <a href='{i['link']}'>{i['judul']}</a></b>\n<b>Genre:</b> <code>{i['genre']}</code>\n" msgs += f"<b>{c}. <a href='{i['link']}'>{i['judul']}</a></b>\n<b>Genre:</b> <code>{i['genre']}</code>\n"
msgs += ( msgs += f"<b>Extract:</b> <code>/{msg.command[0]}_scrap {i['link']}</code>\n\n" if not "/tv/" in i["link"] else "\n"
f"<b>Extract:</b> <code>/{msg.command[0]}_scrap {i['link']}</code>\n\n"
if not "/tv/" in i["link"]
else "\n"
)
if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000: if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
await msg.reply( await msg.reply(
head + msgs, head + msgs,
@ -594,11 +587,7 @@ async def pahe_scrap(_, msg):
if not res["result"]: if not res["result"]:
await m.delete() await m.delete()
return await msg.reply("404 Result not FOUND!", True) return await msg.reply("404 Result not FOUND!", True)
head = ( head = f"<b>#Pahe Results For:</b> <code>{title}</code>\n\n" if title else f"<b>#Pahe Latest:</b>\n🌀 Use /{msg.command[0]} [title] to start search with title.\n\n"
f"<b>#Pahe Results For:</b> <code>{title}</code>\n\n"
if title
else f"<b>#Pahe Latest:</b>\n🌀 Use /{msg.command[0]} [title] to start search with title.\n\n"
)
await m.delete() await m.delete()
msgs = "" msgs = ""
for c, i in enumerate(res["result"], start=1): for c, i in enumerate(res["result"], start=1):
@ -659,11 +648,7 @@ async def terbit21_scrap(_, msg):
msgs = "" msgs = ""
for c, i in enumerate(res["result"], start=1): for c, i in enumerate(res["result"], start=1):
msgs += f"<b>{c}. <a href='{i['link']}'>{i['judul']}</a></b>\n<b>Category:</b> <code>{i['kategori']}</code>\n" msgs += f"<b>{c}. <a href='{i['link']}'>{i['judul']}</a></b>\n<b>Category:</b> <code>{i['kategori']}</code>\n"
msgs += ( msgs += f"💠 <b><a href='{i['dl']}'>Download</a></b>\n\n" if not re.search(r"Complete|Ongoing", i["kategori"]) else "\n"
f"💠 <b><a href='{i['dl']}'>Download</a></b>\n\n"
if not re.search(r"Complete|Ongoing", i["kategori"])
else "\n"
)
if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000: if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
await msg.reply( await msg.reply(
head + msgs, head + msgs,
@ -715,11 +700,7 @@ async def terbit21_scrap(_, msg):
msgs = "" msgs = ""
for c, i in enumerate(res["result"], start=1): for c, i in enumerate(res["result"], start=1):
msgs += f"<b>{c}. <a href='{i['link']}'>{i['judul']}</a></b>\n<b>Category:</b> <code>{i['kategori']}</code>\n" msgs += f"<b>{c}. <a href='{i['link']}'>{i['judul']}</a></b>\n<b>Category:</b> <code>{i['kategori']}</code>\n"
msgs += ( msgs += f"💠 <b><a href='{i['dl']}'>Download</a></b>\n\n" if not re.search(r"Complete|Ongoing", i["kategori"]) else "\n"
f"💠 <b><a href='{i['dl']}'>Download</a></b>\n\n"
if not re.search(r"Complete|Ongoing", i["kategori"])
else "\n"
)
if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000: if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
await msg.reply( await msg.reply(
head + msgs, head + msgs,
@ -779,11 +760,7 @@ async def lk21_scrap(_, msg):
msgs = "" msgs = ""
for c, i in enumerate(res["result"], start=1): for c, i in enumerate(res["result"], start=1):
msgs += f"<b>{c}. <a href='{i['link']}'>{i['judul']}</a></b>\n<b>Category:</b> <code>{i['kategori']}</code>\n" msgs += f"<b>{c}. <a href='{i['link']}'>{i['judul']}</a></b>\n<b>Category:</b> <code>{i['kategori']}</code>\n"
msgs += ( msgs += f"💠 <b><a href='{i['dl']}'>Download</a></b>\n\n" if not re.search(r"Complete|Ongoing", i["kategori"]) else "\n"
f"💠 <b><a href='{i['dl']}'>Download</a></b>\n\n"
if not re.search(r"Complete|Ongoing", i["kategori"])
else "\n"
)
if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000: if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
await msg.reply( await msg.reply(
head + msgs, head + msgs,
@ -838,11 +815,7 @@ async def lk21_scrap(_, msg):
msgs = "" msgs = ""
for c, i in enumerate(res["result"], start=1): for c, i in enumerate(res["result"], start=1):
msgs += f"<b>{c}. <a href='{i['link']}'>{i['judul']}</a></b>\n<b>Category:</b> <code>{i['kategori']}</code>\n" msgs += f"<b>{c}. <a href='{i['link']}'>{i['judul']}</a></b>\n<b>Category:</b> <code>{i['kategori']}</code>\n"
msgs += ( msgs += f"💠 <b><a href='{i['dl']}'>Download</a></b>\n\n" if not re.search(r"Complete|Ongoing", i["kategori"]) else "\n"
f"💠 <b><a href='{i['dl']}'>Download</a></b>\n\n"
if not re.search(r"Complete|Ongoing", i["kategori"])
else "\n"
)
if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000: if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
await msg.reply( await msg.reply(
head + msgs, head + msgs,
@ -917,11 +890,7 @@ async def gomov_scrap(_, msg):
await m.delete() await m.delete()
for c, i in enumerate(data, start=1): for c, i in enumerate(data, start=1):
msgs += f"<b>{c}. <a href='{i['link']}'>{i['judul']}</a></b>\n<b>Genre:</b> <code>{i['genre']}</code>\n" msgs += f"<b>{c}. <a href='{i['link']}'>{i['judul']}</a></b>\n<b>Genre:</b> <code>{i['genre']}</code>\n"
msgs += ( msgs += f"<b>Extract:</b> <code>/{msg.command[0]}_scrap {i['link']}</code>\n\n" if not re.search(r"Series", i["genre"]) else "\n"
f"<b>Extract:</b> <code>/{msg.command[0]}_scrap {i['link']}</code>\n\n"
if not re.search(r"Series", i["genre"])
else "\n"
)
if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000: if len(head.encode("utf-8") + msgs.encode("utf-8")) >= 4000:
await msg.reply( await msg.reply(
head + msgs, head + msgs,
@ -967,9 +936,7 @@ async def gomov_scrap(_, msg):
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) html = await http.get(link, headers=headers)
soup = BeautifulSoup(html.text, "lxml") soup = BeautifulSoup(html.text, "lxml")
@ -990,9 +957,7 @@ async def savefilm21_scrap(_, message):
), ),
) )
except IndexError: except IndexError:
return await message.reply( return await message.reply(f"Gunakan command /{message.command[0]} <b>[link]</b> untuk scrap link download")
f"Gunakan command /{message.command[0]} <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)}")
@ -1002,18 +967,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) html = await http.get(link, headers=headers)
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(f"Gunakan command /{message.command[0]} <b>[link]</b> untuk scrap link download")
f"Gunakan command /{message.command[0]} <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)}")
@ -1024,9 +985,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")
@ -1043,9 +1002,7 @@ 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(f"Gunakan command /{message.command[0]} <b>[link]</b> untuk scrap link download")
f"Gunakan command /{message.command[0]} <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)}")
@ -1055,9 +1012,7 @@ async def muviku_scrap(_, message):
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")
@ -1067,9 +1022,7 @@ 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(f"Gunakan command /{message.command[0]} <b>[link]</b> untuk scrap link download")
f"Gunakan command /{message.command[0]} <b>[link]</b> untuk scrap link download"
)
@app.on_message(filters.command(["gomov_scrap", "zonafilm_scrap"], COMMAND_HANDLER)) @app.on_message(filters.command(["gomov_scrap", "zonafilm_scrap"], COMMAND_HANDLER))
@ -1077,9 +1030,7 @@ async def melong_scrap(_, message):
async def gomov_zonafilm_dl(_, message): async def gomov_zonafilm_dl(_, 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")
@ -1103,6 +1054,4 @@ async def gomov_zonafilm_dl(_, message):
), ),
) )
except IndexError: except IndexError:
await message.reply( await message.reply(f"Gunakan command /{message.command[0]} <b>[link]</b> untuk scrap link download")
f"Gunakan command /{message.command[0]} <b>[link]</b> untuk scrap link download"
)

View file

@ -36,11 +36,7 @@ __HELP__ = """
def get_emoji_regex(): def get_emoji_regex():
e_list = [ e_list = [getattr(emoji, e).encode("unicode-escape").decode("ASCII") for e in dir(emoji) if not e.startswith("_")]
getattr(emoji, e).encode("unicode-escape").decode("ASCII")
for e in dir(emoji)
if not e.startswith("_")
]
# to avoid re.error excluding char that start with '*' # to avoid re.error excluding char that start with '*'
e_sort = sorted([x for x in e_list if not x.startswith("*")], reverse=True) e_sort = sorted([x for x in e_list if not x.startswith("*")], reverse=True)
# Sort emojis by length to make sure multi-character emojis are # Sort emojis by length to make sure multi-character emojis are
@ -69,11 +65,7 @@ async def getsticker_(c, m):
) )
await m.reply_to_message.reply_document( await m.reply_to_message.reply_document(
document=sticker_file, document=sticker_file,
caption=( caption=(f"<b>Emoji:</b> {sticker.emoji}\n" f"<b>Sticker ID:</b> <code>{sticker.file_id}</code>\n\n" f"<b>Send by:</b> @{BOT_USERNAME}"),
f"<b>Emoji:</b> {sticker.emoji}\n"
f"<b>Sticker ID:</b> <code>{sticker.file_id}</code>\n\n"
f"<b>Send by:</b> @{BOT_USERNAME}"
),
) )
shutil.rmtree(tempdir, ignore_errors=True) shutil.rmtree(tempdir, ignore_errors=True)
else: else:
@ -83,11 +75,7 @@ async def getsticker_(c, m):
@app.on_message(filters.command("stickerid", COMMAND_HANDLER) & filters.reply) @app.on_message(filters.command("stickerid", COMMAND_HANDLER) & filters.reply)
async def getstickerid(c, m): async def getstickerid(c, m):
if m.reply_to_message.sticker: if m.reply_to_message.sticker:
await m.reply_text( await m.reply_text("The ID of this sticker is: <code>{stickerid}</code>".format(stickerid=m.reply_to_message.sticker.file_id))
"The ID of this sticker is: <code>{stickerid}</code>".format(
stickerid=m.reply_to_message.sticker.file_id
)
)
@app.on_message(filters.command("unkang", COMMAND_HANDLER) & filters.reply) @app.on_message(filters.command("unkang", COMMAND_HANDLER) & filters.reply)
@ -106,9 +94,7 @@ async def getstickerid(c, m):
except Exception as e: except Exception as e:
await pp.edit(f"Failed remove sticker from your pack.\n\nERR: {e}") await pp.edit(f"Failed remove sticker from your pack.\n\nERR: {e}")
else: else:
await m.reply_text( await m.reply_text(f"Please reply sticker that created by {c.me.username} to remove sticker from your pack.")
f"Please reply sticker that created by {c.me.username} to remove sticker from your pack."
)
@app.on_message(filters.command(["curi", "kang"], COMMAND_HANDLER)) @app.on_message(filters.command(["curi", "kang"], COMMAND_HANDLER))
@ -139,10 +125,7 @@ async def kang_sticker(c, m):
if "image" in reply.document.mime_type: if "image" in reply.document.mime_type:
# mime_type: image/webp # mime_type: image/webp
resize = True resize = True
elif ( elif MessageMediaType.VIDEO == reply.document.mime_type or MessageMediaType.ANIMATION == reply.document.mime_type:
MessageMediaType.VIDEO == reply.document.mime_type
or MessageMediaType.ANIMATION == reply.document.mime_type
):
# mime_type: application/video # mime_type: application/video
videos = True videos = True
convert = True convert = True
@ -172,10 +155,7 @@ async def kang_sticker(c, m):
packname = f"{pack_prefix}{packnum}_{m.from_user.id}_by_{c.me.username}" packname = f"{pack_prefix}{packnum}_{m.from_user.id}_by_{c.me.username}"
if len(m.command) > 1: if len(m.command) > 1:
# matches all valid emojis in input # matches all valid emojis in input
sticker_emoji = ( sticker_emoji = "".join(set(EMOJI_PATTERN.findall("".join(m.command[1:])))) or sticker_emoji
"".join(set(EMOJI_PATTERN.findall("".join(m.command[1:]))))
or sticker_emoji
)
filename = await c.download_media(m.reply_to_message) filename = await c.download_media(m.reply_to_message)
if not filename: if not filename:
# Failed to download # Failed to download
@ -186,11 +166,7 @@ async def kang_sticker(c, m):
filename = "sticker.png" filename = "sticker.png"
packname = f"c{m.from_user.id}_by_{c.me.username}" packname = f"c{m.from_user.id}_by_{c.me.username}"
img_url = next( img_url = next(
( (m.text[y.offset : (y.offset + y.length)] for y in m.entities if y.type == "url"),
m.text[y.offset : (y.offset + y.length)]
for y in m.entities
if y.type == "url"
),
None, None,
) )
@ -210,15 +186,10 @@ async def kang_sticker(c, m):
packnum = m.command.pop(2) packnum = m.command.pop(2)
packname = f"a{packnum}_{m.from_user.id}_by_{c.me.username}" packname = f"a{packnum}_{m.from_user.id}_by_{c.me.username}"
if len(m.command) > 2: if len(m.command) > 2:
sticker_emoji = ( sticker_emoji = "".join(set(EMOJI_PATTERN.findall("".join(m.command[2:])))) or sticker_emoji
"".join(set(EMOJI_PATTERN.findall("".join(m.command[2:]))))
or sticker_emoji
)
resize = True resize = True
else: else:
return await prog_msg.edit_text( return await prog_msg.edit_text("Want me to guess the sticker? Please tag a sticker.")
"Want me to guess the sticker? Please tag a sticker."
)
try: try:
if resize: if resize:
filename = resize_image(filename) filename = resize_image(filename)
@ -237,9 +208,7 @@ async def kang_sticker(c, m):
) )
if stickerset.set.count >= max_stickers: if stickerset.set.count >= max_stickers:
packnum += 1 packnum += 1
packname = ( packname = f"{pack_prefix}_{packnum}_{m.from_user.id}_by_{c.me.username}"
f"{pack_prefix}_{packnum}_{m.from_user.id}_by_{c.me.username}"
)
else: else:
packname_found = True packname_found = True
except StickersetInvalid: except StickersetInvalid:
@ -319,9 +288,7 @@ async def kang_sticker(c, m):
) )
except BadRequest: except BadRequest:
return await prog_msg.edit_text( return await prog_msg.edit_text("Your Sticker Pack is full if your pack is not in v1 Type /kang 1, if it is not in v2 Type /kang 2 and so on.")
"Your Sticker Pack is full if your pack is not in v1 Type /kang 1, if it is not in v2 Type /kang 2 and so on."
)
except Exception as all_e: except Exception as all_e:
await prog_msg.edit_text(f"{all_e.__class__.__name__} : {all_e}") await prog_msg.edit_text(f"{all_e.__class__.__name__} : {all_e}")
else: else:

View file

@ -4,7 +4,7 @@
* @projectName MissKatyPyro * @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved * Copyright @YasirPedia All rights reserved
""" """
from misskaty import app, BOT_USERNAME from misskaty import app
from logging import getLogger from logging import getLogger
from pyrogram import filters from pyrogram import filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
@ -59,18 +59,12 @@ def get_subname(lang, 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"]:
@ -102,33 +96,20 @@ async def ceksub(_, m):
reply_markup=InlineKeyboardMarkup(buttons), reply_markup=InlineKeyboardMarkup(buttons),
) )
except Exception: except Exception:
err = traceback.format_exc() traceback.format_exc()
await pesan.edit( await pesan.edit(f"Failed extract media, make sure your link is not protected by WAF or maybe inaccessible for bot.")
f"Failed extract media, make sure your link is not protected by WAF or maybe inaccessible for bot."
)
@app.on_message(filters.command(["converttosrt"], COMMAND_HANDLER)) @app.on_message(filters.command(["converttosrt"], COMMAND_HANDLER))
@capture_err @capture_err
async def convertsrt(c, m): async def convertsrt(c, m):
reply = m.reply_to_message reply = m.reply_to_message
if ( if not reply and reply.document and (reply.document.file_name.endswith(".vtt") or reply.document.file_name.endswith(".ass")):
not reply return await m.reply(f"Use command /{m.command[0]} by reply to .ass or .vtt file, to convert subtitle from .ass or .vtt to srt.")
and reply.document
and (
reply.document.file_name.endswith(".vtt")
or reply.document.file_name.endswith(".ass")
)
):
return await m.reply(
f"Use command /{m.command[0]} by reply to .ass or .vtt file, to convert subtitle from .ass or .vtt to srt."
)
msg = await m.reply("⏳ Converting...") msg = await m.reply("⏳ Converting...")
dl = await reply.download() dl = await reply.download()
filename = dl.split("/", 3)[3] filename = dl.split("/", 3)[3]
LOGGER.info( LOGGER.info(f"ConvertSub: {filename} by {m.from_user.first_name} [{m.from_user.id}]")
f"ConvertSub: {filename} by {m.from_user.first_name} [{m.from_user.id}]"
)
(await shell_exec(f"mediaextract -i '{dl}' '{filename}.srt'"))[0] (await shell_exec(f"mediaextract -i '{dl}' '{filename}.srt'"))[0]
c_time = time() c_time = time()
await m.reply_document( await m.reply_document(
@ -168,12 +149,8 @@ async def stream_extract(bot, update):
format = "srt" format = "srt"
start_time = perf_counter() start_time = perf_counter()
namafile = get_subname(lang, link, format) namafile = get_subname(lang, link, format)
LOGGER.info( LOGGER.info(f"ExtractSub: {namafile} by {update.from_user.first_name} [{update.from_user.id}]")
f"ExtractSub: {namafile} by {update.from_user.first_name} [{update.from_user.id}]" extract = (await shell_exec(f"mediaextract -i {link} -map {map} '{namafile}'"))[0]
)
extract = (await shell_exec(f"mediaextract -i {link} -map {map} '{namafile}'"))[
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"
c_time = time() c_time = time()

View file

@ -15,9 +15,7 @@ from iytdl import iYTDL, main
from uuid import uuid4 from uuid import uuid4
LOGGER = getLogger(__name__) LOGGER = getLogger(__name__)
regex = recompile( regex = recompile(r"(https?://)?(www\.)?(youtube|youtu|youtube-nocookie)\.(com|be)/(watch\?v=|embed/|v/|.+\?v=)?(?P<id>[A-Za-z0-9\-=_]{11})")
r"(https?://)?(www\.)?(youtube|youtu|youtube-nocookie)\.(com|be)/(watch\?v=|embed/|v/|.+\?v=)?(?P<id>[A-Za-z0-9\-=_]{11})"
)
YT_DB = {} YT_DB = {}
@ -65,9 +63,7 @@ async def ytdownv2(_, message):
if len(message.command) == 1: if len(message.command) == 1:
return await message.reply("Please input a valid YT-DLP Supported URL") return await message.reply("Please input a valid YT-DLP Supported URL")
url = message.text.split(" ", maxsplit=1)[1] url = message.text.split(" ", maxsplit=1)[1]
async with iYTDL( async with iYTDL(log_group_id=0, cache_path="cache", ffmpeg_location="/usr/bin/mediaextract") as ytdl:
log_group_id=0, cache_path="cache", ffmpeg_location="/usr/bin/mediaextract"
) as ytdl:
x = await ytdl.parse(url) x = await ytdl.parse(url)
if x is None: if x is None:
return await message.reply("Failed parse URL, check logs..") return await message.reply("Failed parse URL, check logs..")
@ -82,13 +78,9 @@ async def ytdl_listall_callback(_, cq: CallbackQuery):
if cq.from_user.id != cq.message.reply_to_message.from_user.id: if cq.from_user.id != cq.message.reply_to_message.from_user.id:
return await cq.answer("Not your task", True) return await cq.answer("Not your task", True)
callback = cq.data.split("|") callback = cq.data.split("|")
async with iYTDL( async with iYTDL(log_group_id=0, cache_path="cache", ffmpeg_location="/usr/bin/mediaextract") as ytdl:
log_group_id=0, cache_path="cache", ffmpeg_location="/usr/bin/mediaextract"
) as ytdl:
media, buttons = await ytdl.listview(callback[1]) media, buttons = await ytdl.listview(callback[1])
await cq.edit_message_media( await cq.edit_message_media(media=media, reply_markup=buttons.add(cq.from_user.id))
media=media, reply_markup=buttons.add(cq.from_user.id)
)
@app.on_callback_query(filters.regex(r"^yt_extract_info")) @app.on_callback_query(filters.regex(r"^yt_extract_info"))
@ -97,9 +89,7 @@ async def ytdl_extractinfo_callback(_, cq: CallbackQuery):
return await cq.answer("Not your task", True) return await cq.answer("Not your task", True)
await cq.answer("Please Wait...") await cq.answer("Please Wait...")
callback = cq.data.split("|") callback = cq.data.split("|")
async with iYTDL( async with iYTDL(log_group_id=0, cache_path="cache", ffmpeg_location="/usr/bin/mediaextract") as ytdl:
log_group_id=0, cache_path="cache", ffmpeg_location="/usr/bin/mediaextract"
) as ytdl:
if data := await ytdl.extract_info_from_key(callback[1]): if data := await ytdl.extract_info_from_key(callback[1]):
if len(key) == 11: if len(key) == 11:
await cq.edit_message_text( await cq.edit_message_text(
@ -125,10 +115,7 @@ async def ytdl_gendl_callback(_, cq: CallbackQuery):
callback = cq.data.split("|") callback = cq.data.split("|")
key = callback[1] key = callback[1]
if callback[0] == "yt_gen": if callback[0] == "yt_gen":
if ( if match := regex.match(cq.message.reply_to_message.command[1]) or len(callback) == 2:
match := regex.match(cq.message.reply_to_message.command[1])
or len(callback) == 2
):
x = await main.Extractor().get_download_button(key) x = await main.Extractor().get_download_button(key)
await cq.edit_message_caption(caption=x.caption, reply_markup=x.buttons) await cq.edit_message_caption(caption=x.caption, reply_markup=x.buttons)
else: else:
@ -144,9 +131,7 @@ async def ytdl_gendl_callback(_, cq: CallbackQuery):
ffmpeg_location="/usr/bin/mediaextract", ffmpeg_location="/usr/bin/mediaextract",
delete_media=True, delete_media=True,
) as ytdl: ) as ytdl:
upload_key = await ytdl.download( upload_key = await ytdl.download(cq.message.reply_to_message.command[1], uid, format_, cq, True, 3)
cq.message.reply_to_message.command[1], uid, format_, cq, True, 3
)
await ytdl.upload(app, upload_key, format_, cq, True) await ytdl.upload(app, upload_key, format_, cq, True)
else: else:
uid = callback[2] uid = callback[2]
@ -161,9 +146,7 @@ async def ytdl_gendl_callback(_, cq: CallbackQuery):
ffmpeg_location="/usr/bin/mediaextract", ffmpeg_location="/usr/bin/mediaextract",
delete_media=True, delete_media=True,
) as ytdl: ) as ytdl:
upload_key = await ytdl.download( upload_key = await ytdl.download("https://www.youtube.com/watch?v=" + key, uid, format_, cq, True, 3)
"https://www.youtube.com/watch?v=" + key, uid, format_, cq, True, 3
)
await ytdl.upload(app, upload_key, format_, cq, True) await ytdl.upload(app, upload_key, format_, cq, True)
@ -184,9 +167,7 @@ async def ytdl_scroll_callback(_, cq: CallbackQuery):
out += f"\n<b> Uploader:</b> <a href={i['channel']['link']}>{i['channel']['name']}</a>\n\n" out += f"\n<b> Uploader:</b> <a href={i['channel']['link']}>{i['channel']['name']}</a>\n\n"
scroll_btn = [ scroll_btn = [
[ [
InlineKeyboardButton( InlineKeyboardButton(f"Back", callback_data=f"ytdl_scroll|{search_key}|{page-1}"),
f"Back", callback_data=f"ytdl_scroll|{search_key}|{page-1}"
),
InlineKeyboardButton( InlineKeyboardButton(
f"{page+1}/{len(search['result'])}", f"{page+1}/{len(search['result'])}",
callback_data=f"ytdl_scroll|{search_key}|{page+1}", callback_data=f"ytdl_scroll|{search_key}|{page+1}",
@ -201,9 +182,7 @@ async def ytdl_scroll_callback(_, cq: CallbackQuery):
scroll_btn = [[scroll_btn.pop().pop(0)]] scroll_btn = [[scroll_btn.pop().pop(0)]]
btn = [[InlineKeyboardButton("Download", callback_data=f"yt_gen|{i['id']}")]] btn = [[InlineKeyboardButton("Download", callback_data=f"yt_gen|{i['id']}")]]
btn = InlineKeyboardMarkup(scroll_btn + btn) btn = InlineKeyboardMarkup(scroll_btn + btn)
await cq.edit_message_media( await cq.edit_message_media(InputMediaPhoto(await get_ytthumb(i["id"]), caption=out), reply_markup=btn)
InputMediaPhoto(await get_ytthumb(i["id"]), caption=out), reply_markup=btn
)
async def get_ytthumb(videoid: str): async def get_ytthumb(videoid: str):