Reformat using black (#120)

* ci: Update .deepsource.toml

* ci: Update .deepsource.toml

* style: format code with black and isort

Format code with black and isort

This commit fixes the style issues introduced in 0fb651a according to the output
from Black and isort.

Details: https://app.deepsource.com/gh/yasirarism/MissKatyPyro/transform/d8f2f66e-b496-4686-aca6-9830236eda12/

---------

Co-authored-by: deepsource-io[bot] <42547082+deepsource-io[bot]@users.noreply.github.com>
Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
This commit is contained in:
yasirarism 2023-06-27 04:07:42 +00:00 committed by GitHub
parent 469ed1ee12
commit a7008c664e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
58 changed files with 977 additions and 277 deletions

View file

@ -2,12 +2,12 @@ version = 1
[[analyzers]]
name = "python"
enabled = true
dependency_file_paths = ["requirements.txt"]
[analyzers.meta]
runtime_version = "3.x.x"
max_line_length = 100
[[transformers]]
name = "isort"
name = "isort"
[[transformers]]
name = "black"

View file

@ -5,7 +5,8 @@
* Copyright @YasirPedia All rights reserved
"""
from async_pymongo import AsyncClient
from misskaty.vars import DATABASE_URI, DATABASE_NAME
from misskaty.vars import DATABASE_NAME, DATABASE_URI
mongo = AsyncClient(DATABASE_URI)
dbname = mongo[DATABASE_NAME]

View file

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

View file

@ -9,7 +9,9 @@ async def is_imdbset(user_id: int) -> bool:
async def add_imdbset(user_id: int, lang):
await imbd_db.update_one({"user_id": user_id}, {"$set": {"lang": lang}}, upsert=True)
await imbd_db.update_one(
{"user_id": user_id}, {"$set": {"lang": lang}}, upsert=True
)
async def remove_imdbset(user_id: int):

View file

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

View file

@ -39,4 +39,6 @@ async def save_note(chat_id: int, name: str, note: dict):
_notes = await _get_notes(chat_id)
_notes[name] = note
await notesdb.update_one({"chat_id": chat_id}, {"$set": {"notes": _notes}}, upsert=True)
await notesdb.update_one(
{"chat_id": chat_id}, {"$set": {"notes": _notes}}, upsert=True
)

View file

@ -1,4 +1,5 @@
from async_pymongo import AsyncClient
from misskaty.vars import DATABASE_NAME, DATABASE_URI

View file

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

View file

@ -1,8 +1,10 @@
import asyncio, logging
import asyncio
import logging
from functools import wraps
LOGGER = logging.getLogger(__name__)
def asyncify(func):
async def inner(*args, **kwargs):
loop = asyncio.get_running_loop()
@ -19,6 +21,8 @@ def new_task(func):
loop = asyncio.get_running_loop()
return loop.create_task(func(*args, **kwargs))
except Exception as e:
LOGGER.error(f"Failed to create task for {func.__name__} : {e}") # skipcq: PYL-E0602
LOGGER.error(
f"Failed to create task for {func.__name__} : {e}"
) # skipcq: PYL-E0602
return wrapper

View file

@ -12,7 +12,9 @@ async def task(msg, warn=False, sec=None):
pass
if warn:
user = msg.from_user
ids = await msg.reply_msg(f"Sorry {user.mention} [<code>{user.id}</code>], you must wait for {sec}s before using command again..")
ids = await msg.reply_msg(
f"Sorry {user.mention} [<code>{user.id}</code>], you must wait for {sec}s before using command again.."
)
await asyncio.sleep(sec)
await ids.edit_msg(
f"Alright {user.mention} [<code>{user.id}</code>], your cooldown is over you can command again.",
@ -30,7 +32,9 @@ def wait(sec):
else:
if not data[user_id]["warned"]:
data[user_id]["warned"] = True
asyncio.ensure_future(task(msg, True, flt.data)) # for super accuracy use (future - time.time())
asyncio.ensure_future(
task(msg, True, flt.data)
) # for super accuracy use (future - time.time())
return False # cause we dont need delete again
asyncio.ensure_future(task(msg))

View file

@ -12,7 +12,12 @@ def keyboard(buttons_list, row_width: int = 2):
if theres, a url, it will make url button, else callback button
"""
buttons = InlineKeyboard(row_width=row_width)
data = [Ikb(text=str(i[0]), url=str(i[1])) if is_url(i[1]) else Ikb(text=str(i[0]), callback_data=str(i[1])) for i in buttons_list]
data = [
Ikb(text=str(i[0]), url=str(i[1]))
if is_url(i[1])
else Ikb(text=str(i[0]), callback_data=str(i[1]))
for i in buttons_list
]
buttons.add(*data)
return buttons

View file

@ -25,7 +25,9 @@ async def kirimPesan(msg, text, **kwargs):
await asyncio.sleep(e.value)
return await kirimPesan(msg, text, **kwargs)
except (ChatWriteForbidden, ChatAdminRequired):
LOGGER.info(f"Leaving from {msg.chat.title} [{msg.chat.id}] because doesn't have admin permission.")
LOGGER.info(
f"Leaving from {msg.chat.title} [{msg.chat.id}] because doesn't have admin permission."
)
return await msg.chat.leave()
except Exception as e:
LOGGER.error(str(e))
@ -43,7 +45,9 @@ async def editPesan(msg, text, **kwargs):
except (MessageNotModified, MessageIdInvalid, MessageEmpty):
return
except (ChatWriteForbidden, ChatAdminRequired):
LOGGER.info(f"Leaving from {msg.chat.title} [{msg.chat.id}] because doesn't have admin permission.")
LOGGER.info(
f"Leaving from {msg.chat.title} [{msg.chat.id}] because doesn't have admin permission."
)
return await msg.chat.leave()
except Exception as e:
LOGGER.error(str(e))

View file

@ -19,10 +19,16 @@ from pyrogram.types import Message
LOGGER = getLogger(__name__)
Message.input = property(lambda m: m.text[m.text.find(m.command[0]) + len(m.command[0]) + 1 :] if len(m.command) > 1 else None)
Message.input = property(
lambda m: m.text[m.text.find(m.command[0]) + len(m.command[0]) + 1 :]
if len(m.command) > 1
else None
)
async def reply_text(self: Message, text: str, as_raw: bool = False, del_in: int = 0, *args, **kwargs) -> Union["Message", bool]:
async def reply_text(
self: Message, text: str, as_raw: bool = False, del_in: int = 0, *args, **kwargs
) -> Union["Message", bool]:
"""\nExample:
message.reply_msg("hello")
Parameters:
@ -70,7 +76,9 @@ async def reply_text(self: Message, text: str, as_raw: bool = False, del_in: int
"""
try:
if as_raw:
msg = await self.reply_text(text=f"<code>{html.escape(text.html)}</code>", *args, **kwargs)
msg = await self.reply_text(
text=f"<code>{html.escape(text.html)}</code>", *args, **kwargs
)
else:
msg = await self.reply_text(text=text, *args, **kwargs)
if del_in == 0:
@ -81,11 +89,15 @@ async def reply_text(self: Message, text: str, as_raw: bool = False, del_in: int
await asleep(e.value)
return await reply_text(self, text, *args, **kwargs)
except (ChatWriteForbidden, ChatAdminRequired):
LOGGER.info(f"Leaving from {self.chat.title} [{self.chat.id}] because doesn't have admin permission.")
LOGGER.info(
f"Leaving from {self.chat.title} [{self.chat.id}] because doesn't have admin permission."
)
return await self.chat.leave()
async def edit_text(self, text: str, del_in: int = 0, *args, **kwargs) -> Union["Message", bool]:
async def edit_text(
self, text: str, del_in: int = 0, *args, **kwargs
) -> Union["Message", bool]:
"""\nExample:
message.edit_msg("hello")
Parameters:
@ -124,13 +136,17 @@ async def edit_text(self, text: str, del_in: int = 0, *args, **kwargs) -> Union[
except MessageNotModified:
return False
except (ChatWriteForbidden, ChatAdminRequired):
LOGGER.info(f"Leaving from {self.chat.title} [{self.chat.id}] because doesn't have admin permission.")
LOGGER.info(
f"Leaving from {self.chat.title} [{self.chat.id}] because doesn't have admin permission."
)
return await self.chat.leave()
except (MessageAuthorRequired, MessageIdInvalid):
return await reply_text(self, text=text, *args, **kwargs)
async def edit_or_send_as_file(self, text: str, del_in: int = 0, as_raw: bool = False, *args, **kwargs) -> Union["Message", bool]:
async def edit_or_send_as_file(
self, text: str, del_in: int = 0, as_raw: bool = False, *args, **kwargs
) -> Union["Message", bool]:
"""\nThis will first try to message.edit.
If it raises MessageTooLong error,
run message.send_as_file.
@ -180,7 +196,9 @@ async def edit_or_send_as_file(self, text: str, del_in: int = 0, as_raw: bool =
return await reply_as_file(self, text=text, *args, **kwargs)
async def reply_or_send_as_file(self, text: str, as_raw: bool = False, del_in: int = 0, *args, **kwargs) -> Union["Message", bool]:
async def reply_or_send_as_file(
self, text: str, as_raw: bool = False, del_in: int = 0, *args, **kwargs
) -> Union["Message", bool]:
"""\nThis will first try to message.reply.
If it raise MessageTooLong error,
run message.send_as_file.

View file

@ -45,7 +45,9 @@ async def meval(code, globs, **kwargs):
if not any(isinstance(node, ast.Return) for node in code):
for i in range(len(code)):
if isinstance(code[i], ast.Expr) and (i == len(code) - 1 or not isinstance(code[i].value, ast.Call)):
if isinstance(code[i], ast.Expr) and (
i == len(code) - 1 or not isinstance(code[i].value, ast.Call)
):
code[i] = ast.copy_location(
ast.Expr(
ast.Call(
@ -65,18 +67,26 @@ async def meval(code, globs, **kwargs):
if isinstance(node, ast.Return):
node.value = ast.List(elts=[node.value], ctx=ast.Load())
code.append(ast.copy_location(ast.Return(value=ast.Name(id=ret_name, ctx=ast.Load())), code[-1]))
code.append(
ast.copy_location(
ast.Return(value=ast.Name(id=ret_name, ctx=ast.Load())), code[-1]
)
)
# globals().update(**<global_args>)
glob_copy = ast.Expr(
ast.Call(
func=ast.Attribute(
value=ast.Call(func=ast.Name(id="globals", ctx=ast.Load()), args=[], keywords=[]),
value=ast.Call(
func=ast.Name(id="globals", ctx=ast.Load()), args=[], keywords=[]
),
attr="update",
ctx=ast.Load(),
),
args=[],
keywords=[ast.keyword(arg=None, value=ast.Name(id=global_args, ctx=ast.Load()))],
keywords=[
ast.keyword(arg=None, value=ast.Name(id=global_args, ctx=ast.Load()))
],
)
)
ast.fix_missing_locations(glob_copy)
@ -100,7 +110,9 @@ async def meval(code, globs, **kwargs):
kw_defaults=[None for _ in range(len(args))],
)
args.posonlyargs = []
fun = ast.AsyncFunctionDef(name="tmp", args=args, body=code, decorator_list=[], returns=None)
fun = ast.AsyncFunctionDef(
name="tmp", args=args, body=code, decorator_list=[], returns=None
)
ast.fix_missing_locations(fun)
mod = ast.parse("")
mod.body = [fun]
@ -125,7 +137,9 @@ async def meval(code, globs, **kwargs):
return r
def format_exception(exp: BaseException, tb: Optional[List[traceback.FrameSummary]] = None) -> str:
def format_exception(
exp: BaseException, tb: Optional[List[traceback.FrameSummary]] = None
) -> str:
"""Formats an exception traceback as a string, similar to the Python interpreter."""
if tb is None:

View file

@ -33,7 +33,9 @@ async def ssgen_link(video, output_directory, ttl):
"image2",
out_put_file_name,
]
process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
process = await asyncio.create_subprocess_exec(
*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
stderr.decode().strip()
@ -42,7 +44,11 @@ async def ssgen_link(video, output_directory, ttl):
async def genss_link(msg, video_link, output_directory, min_duration, no_of_photos):
metadata = (await shell_exec(f"ffprobe -i {video_link} -show_entries format=duration -v quiet -of csv='p=0'"))[0]
metadata = (
await shell_exec(
f"ffprobe -i {video_link} -show_entries format=duration -v quiet -of csv='p=0'"
)
)[0]
duration = round(float(metadata))
if duration > min_duration:
images = []
@ -50,12 +56,20 @@ async def genss_link(msg, video_link, output_directory, min_duration, no_of_phot
current_ttl = ttl_step
for looper in range(no_of_photos):
ss_img = await ssgen_link(video_link, output_directory, current_ttl)
images.append(InputMediaPhoto(media=ss_img, caption=f"Screenshot at {hhmmss(current_ttl)}"))
images.append(
InputMediaPhoto(
media=ss_img, caption=f"Screenshot at {hhmmss(current_ttl)}"
)
)
try:
await msg.edit(f"📸 <b>Take Screenshoot:</b>\n<code>{looper+1} of {no_of_photos} screenshot generated..</code>")
await msg.edit(
f"📸 <b>Take Screenshoot:</b>\n<code>{looper+1} of {no_of_photos} screenshot generated..</code>"
)
except FloodWait as e:
await asyncio.sleep(e.value)
await msg.edit(f"📸 <b>Take Screenshoot:</b>\n<code>{looper+1} of {no_of_photos} screenshot generated..</code>")
await msg.edit(
f"📸 <b>Take Screenshoot:</b>\n<code>{looper+1} of {no_of_photos} screenshot generated..</code>"
)
current_ttl = current_ttl + ttl_step
await asyncio.sleep(2)
return images

View file

@ -53,14 +53,20 @@ async def resize_file_to_sticker_size(file_path: str) -> str:
im.save(file_path)
async def upload_document(client: Client, file_path: str, chat_id: int) -> raw.base.InputDocument:
async def upload_document(
client: Client, file_path: str, chat_id: int
) -> raw.base.InputDocument:
media = await client.send(
raw.functions.messages.UploadMedia(
peer=await client.resolve_peer(chat_id),
media=raw.types.InputMediaUploadedDocument(
mime_type=client.guess_mime_type(file_path) or "application/zip",
file=await client.save_file(file_path),
attributes=[raw.types.DocumentAttributeFilename(file_name=os.path.basename(file_path))],
attributes=[
raw.types.DocumentAttributeFilename(
file_name=os.path.basename(file_path)
)
],
),
)
)

View file

@ -34,7 +34,11 @@ def get_readable_time(seconds: int) -> str:
def get_readable_bitrate(bitrate_kbps):
return f"{str(round(bitrate_kbps / 1000, 2))} Mb/s" if bitrate_kbps > 10000 else f"{str(round(bitrate_kbps, 2))} kb/s"
return (
f"{str(round(bitrate_kbps / 1000, 2))} Mb/s"
if bitrate_kbps > 10000
else f"{str(round(bitrate_kbps, 2))} kb/s"
)
def get_readable_time2(seconds: int) -> str:

View file

@ -39,11 +39,15 @@ for locale in enabled_locales:
langdict = cache_localizations(jsons)
def get_locale_string(dic: dict, language: str, default_context: str, key: str, context: str = None) -> str:
def get_locale_string(
dic: dict, language: str, default_context: str, key: str, context: str = None
) -> str:
if context:
default_context = context
dic = langdict[language].get(context, langdict[default_language][context])
res: str = dic.get(key) or langdict[default_language][default_context].get(key) or key
res: str = (
dic.get(key) or langdict[default_language][default_context].get(key) or key
)
return res

View file

@ -27,7 +27,9 @@ async def post_to_telegraph(is_media: bool, title=None, content=None, media=None
async def run_subprocess(cmd):
process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
process = await asyncio.create_subprocess_exec(
*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
return await process.communicate()
@ -54,7 +56,9 @@ async def get_media_info(file_link):
async def runcmd(cmd: str) -> Tuple[str, str, int, int]:
"""run command in terminal"""
args = shlex.split(cmd)
process = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
process = await asyncio.create_subprocess_exec(
*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
return (
stdout.decode("utf-8", "replace").strip(),

View file

@ -169,25 +169,37 @@ def html_builder(title: str, text: str) -> str:
if "Text #" in line:
if bool(re.search("Text #1$", line)):
subtitle_count = len(re.findall("Text #", text))
html_msg += icon.format(icon_url="https://te.legra.ph/file/9d4a676445544d0f2d6db.png")
html_msg += subheading.format(content=f"Subtitles ({subtitle_count} subtitle)")
html_msg += icon.format(
icon_url="https://te.legra.ph/file/9d4a676445544d0f2d6db.png"
)
html_msg += subheading.format(
content=f"Subtitles ({subtitle_count} subtitle)"
)
html_msg += "<span style='padding: 10px 0vw;' class='subtitle'>"
elif "General" in line:
html_msg += icon.format(icon_url="https://te.legra.ph/file/638fb0416f2600e7c5aa3.png")
html_msg += icon.format(
icon_url="https://te.legra.ph/file/638fb0416f2600e7c5aa3.png"
)
html_msg += subheading.format(content="General")
elif "Video" in line:
html_msg += icon.format(icon_url="https://te.legra.ph/file/fbc30d71cf71c9a54e59d.png")
html_msg += icon.format(
icon_url="https://te.legra.ph/file/fbc30d71cf71c9a54e59d.png"
)
html_msg += subheading.format(content="Video")
elif "Audio" in line:
html_msg += icon.format(icon_url="https://te.legra.ph/file/a3c431be457fedbae2286.png")
html_msg += icon.format(
icon_url="https://te.legra.ph/file/a3c431be457fedbae2286.png"
)
html_msg += subheading.format(content=f"{line.strip()}")
elif "Menu" in line:
html_msg += "</span>"
html_msg += icon.format(icon_url="https://te.legra.ph/file/3023b0c2bc202ec9d6d0d.png")
html_msg += icon.format(
icon_url="https://te.legra.ph/file/3023b0c2bc202ec9d6d0d.png"
)
html_msg += subheading.format(content="Chapters")
else:
@ -209,4 +221,6 @@ async def mediainfo_paste(text: str, title: str) -> str:
html_content = html_builder(title, text)
URL = "https://mediainfo-1-y5870653.deta.app/api"
response = await http.post(URL, json={"content": html_content})
return f"https://mediainfo-1-y5870653.deta.app/{json.loads(response.content)['key']}"
return (
f"https://mediainfo-1-y5870653.deta.app/{json.loads(response.content)['key']}"
)

View file

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

View file

@ -32,12 +32,15 @@ async def progress_for_pyrogram(current, total, ud_type, message, start, dc_id):
round(percentage, 2),
)
tmp = progress + "{0} <b>of</b> {1}\n<b>Speed:</b> {2}/s\n<b>DC ID:</b> {3}\n<b>ETA:</b> {4}</b>\n".format(
humanbytes(current),
humanbytes(total),
humanbytes(speed),
dc_id,
estimated_total_time if estimated_total_time != "" else "0 s",
tmp = (
progress
+ "{0} <b>of</b> {1}\n<b>Speed:</b> {2}/s\n<b>DC ID:</b> {3}\n<b>ETA:</b> {4}</b>\n".format(
humanbytes(current),
humanbytes(total),
humanbytes(speed),
dc_id,
estimated_total_time if estimated_total_time != "" else "0 s",
)
)
try:
await message.edit(f"{ud_type}\n {tmp}")

View file

@ -22,7 +22,9 @@ from typing import List
from pyrogram import Client, errors, raw
async def get_sticker_set_by_name(client: Client, name: str) -> raw.base.messages.StickerSet:
async def get_sticker_set_by_name(
client: Client, name: str
) -> raw.base.messages.StickerSet:
try:
return await client.invoke(
raw.functions.messages.GetStickerSet(
@ -63,11 +65,15 @@ async def add_sticker_to_set(
) -> raw.base.messages.StickerSet:
return await client.invoke(
raw.functions.stickers.AddStickerToSet(
stickerset=raw.types.InputStickerSetShortName(short_name=stickerset.set.short_name),
stickerset=raw.types.InputStickerSetShortName(
short_name=stickerset.set.short_name
),
sticker=sticker,
)
)
async def create_sticker(sticker: raw.base.InputDocument, emoji: str) -> raw.base.InputStickerSetItem:
async def create_sticker(
sticker: raw.base.InputDocument, emoji: str
) -> raw.base.InputStickerSetItem:
return raw.types.InputStickerSetItem(document=sticker, emoji=emoji)

View file

@ -17,7 +17,11 @@ async def down_page(url):
except:
poster = ""
try:
author_name = maindiv.find("div", class_="header").ul.find("li", class_="author").a.text.strip()
author_name = (
maindiv.find("div", class_="header")
.ul.find("li", class_="author")
.a.text.strip()
)
author_link = f"https://subscene.com{maindiv.find('div', class_='header').ul.find('li', class_='author').a['href']}"
except:
author_link = ""
@ -26,11 +30,20 @@ async def down_page(url):
download_url = f"https://subscene.com{maindiv.find('div', class_='header').ul.find('li', class_='clearfix').find('div', class_='download').a['href']}"
try:
comments = maindiv.find("div", class_="header").ul.find("li", class_="comment-wrapper").find("div", class_="comment").text
comments = (
maindiv.find("div", class_="header")
.ul.find("li", class_="comment-wrapper")
.find("div", class_="comment")
.text
)
except:
comments = ""
try:
release = maindiv.find("div", class_="header").ul.find("li", class_="release").find_all("div")
release = (
maindiv.find("div", class_="header")
.ul.find("li", class_="release")
.find_all("div")
)
releases = ""
for i in range(2):
r = release[i].text.strip()

View file

@ -77,7 +77,10 @@ def remove_N(seq):
def get_random_string(length: int = 5):
text_str = "".join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length))
text_str = "".join(
random.SystemRandom().choice(string.ascii_letters + string.digits)
for _ in range(length)
)
return text_str.upper()
@ -124,7 +127,11 @@ def get_provider(url):
async def search_jw(movie_name: str, locale: str):
m_t_ = ""
try:
response = (await http.get(f"https://yasirapi.eu.org/justwatch?q={movie_name}&locale={locale}")).json()
response = (
await http.get(
f"https://yasirapi.eu.org/justwatch?q={movie_name}&locale={locale}"
)
).json()
except:
return m_t_
if not response.get("results"):

View file

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

View file

@ -157,7 +157,12 @@ def shorten(description, info="anilist.co"):
ms_g += f'\n<strong>Description:</strong> <em>{description}</em><a href="{info}">More info</a>'
else:
ms_g += f"\n<strong>Description:</strong> <em>{description}</em>"
return ms_g.replace("<br>", "").replace("</br>", "").replace("<i>", "").replace("</i>", "")
return (
ms_g.replace("<br>", "")
.replace("</br>", "")
.replace("<i>", "")
.replace("</i>", "")
)
@app.on_message(filters.command("anime", COMMAND_HANDLER))
@ -171,7 +176,11 @@ async def anime_search(_, mesg):
variables = {"search": search}
if not (res := json.loads(await get_anime(variables))["data"].get("Media", None)):
return await reply.edit("💢 No Resource Anime found! [404]")
durasi = get_readable_time(int(res.get("duration") * 60)) if res.get("duration") is not None else "0"
durasi = (
get_readable_time(int(res.get("duration") * 60))
if res.get("duration") is not None
else "0"
)
msg = f"<b>{res['title']['romaji']}</b> (<code>{res['title']['native']}</code>)\n<b>Type</b>: {res['format']}\n<b>Status</b>: {res['status']}\n<b>Episodes</b>: {res.get('episodes', 'N/A')}\n<b>Duration </b>: {durasi} Per Eps.\n<b>Score</b>: {res['averageScore']}%\n<b>Category</b>: <code>"
for x in res["genres"]:
msg += f"{x}, "
@ -199,7 +208,14 @@ async def anime_search(_, mesg):
site = trailer.get("site", None)
if site == "youtube":
trailer = f"https://youtu.be/{trailer_id}"
description = res.get("description").replace("<i>", "").replace("</i>", "").replace("<br>", "") if res.get("description") is not None else "N/A"
description = (
res.get("description")
.replace("<i>", "")
.replace("</i>", "")
.replace("<br>", "")
if res.get("description") is not None
else "N/A"
)
msg += shorten(description, info)
image = info.replace("anilist.co/anime/", "img.anili.st/media/")
btn = (
@ -215,7 +231,9 @@ async def anime_search(_, mesg):
if image:
try:
await mesg.reply_photo(image, caption=msg, reply_markup=InlineKeyboardMarkup(btn))
await mesg.reply_photo(
image, caption=msg, reply_markup=InlineKeyboardMarkup(btn)
)
except:
msg += f" [〽️]({image})"
await reply.edit(msg)

View file

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

View file

@ -38,6 +38,10 @@ async def broadcast(self: Client, ctx: Message):
done += 1
await asyncio.sleep(2)
if not done % 20:
await sts.edit_msg(f"Broadcast in progress:\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}")
await sts.edit_msg(
f"Broadcast in progress:\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}"
)
time_taken = datetime.timedelta(seconds=int(time.time() - start_time))
await sts.edit_msg(f"Broadcast Completed:\nCompleted in {time_taken} seconds.\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}")
await sts.edit_msg(
f"Broadcast Completed:\nCompleted in {time_taken} seconds.\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}"
)

View file

@ -46,7 +46,10 @@ async def pling_bypass(url):
res = await http.get(link)
json_dic_files = res.json().pop("files")
msg = f"\n**Source Link** :\n`{url}`\n**Direct Link :**\n"
msg += "\n".join(f'**→ [{i["name"]}]({unquote(i["url"])}) ({get_readable_file_size(int(i["size"]))})**' for i in json_dic_files)
msg += "\n".join(
f'**→ [{i["name"]}]({unquote(i["url"])}) ({get_readable_file_size(int(i["size"]))})**'
for i in json_dic_files
)
return msg
except Exception as e:
return e
@ -78,7 +81,9 @@ def wetransfer_bypass(url: str) -> str:
r = s.get("https://wetransfer.com/")
m = re.search('name="csrf-token" content="([^"]+)"', r.text)
s.headers.update({"x-csrf-token": m[1], "x-requested-with": "XMLHttpRequest"})
r = s.post(f"https://wetransfer.com/api/v4/transfers/{transfer_id}/download", json=j)
r = s.post(
f"https://wetransfer.com/api/v4/transfers/{transfer_id}/download", json=j
)
j = r.json()
dl_url = j["direct_link"]
@ -92,7 +97,9 @@ def wetransfer_bypass(url: str) -> str:
@ratelimiter
async def bypass(self: Client, ctx: Message):
if len(ctx.command) == 1:
return await ctx.reply_msg(f"Gunakan perintah /{ctx.command[0]} untuk bypass url", del_in=6)
return await ctx.reply_msg(
f"Gunakan perintah /{ctx.command[0]} untuk bypass url", del_in=6
)
url = ctx.command[1]
msg = await ctx.reply_msg("Bypassing URL..", quote=True)
mention = f"**Bypasser:** {ctx.from_user.mention} ({ctx.from_user.id})"

View file

@ -26,7 +26,9 @@ openai.api_key = OPENAI_API
@use_chat_lang()
async def bard_chatbot(self: Client, ctx: Message, strings):
if len(ctx.command) == 1:
return await ctx.reply_msg(strings("no_question").format(cmd=ctx.command[0]), quote=True, del_in=5)
return await ctx.reply_msg(
strings("no_question").format(cmd=ctx.command[0]), quote=True, del_in=5
)
msg = await ctx.reply_msg(strings("find_answers_str"), quote=True)
data = {
"message": ctx.input,
@ -44,7 +46,9 @@ async def bard_chatbot(self: Client, ctx: Message, strings):
@use_chat_lang()
async def openai_chatbot(self: Client, ctx: Message, strings):
if len(ctx.command) == 1:
return await ctx.reply_msg(strings("no_question").format(cmd=ctx.command[0]), quote=True, del_in=5)
return await ctx.reply_msg(
strings("no_question").format(cmd=ctx.command[0]), quote=True, del_in=5
)
uid = ctx.from_user.id if ctx.from_user else ctx.sender_chat.id
is_in_gap, sleep_time = await check_time_gap(uid)
if is_in_gap and (uid not in SUDO):
@ -72,7 +76,9 @@ async def openai_chatbot(self: Client, ctx: Message, strings):
num = 0
await msg.edit_msg(answer)
except MessageTooLong:
answerlink = await post_to_telegraph(False, "MissKaty ChatBot ", html.escape(answer))
answerlink = await post_to_telegraph(
False, "MissKaty ChatBot ", html.escape(answer)
)
await msg.edit_msg(
strings("answers_too_long").format(answerlink=answerlink),
disable_web_page_preview=True,

View file

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

View file

@ -36,8 +36,13 @@ async def currency(self: Client, ctx: Message):
amount = teks[1]
currency_from = teks[2]
currency_to = teks[3]
if amount.isdigit() or (amount.replace(".", "", 1).isdigit() and amount.count(".") < 2):
url = f"https://v6.exchangerate-api.com/v6/{CURRENCY_API}/" f"pair/{currency_from}/{currency_to}/{amount}"
if amount.isdigit() or (
amount.replace(".", "", 1).isdigit() and amount.count(".") < 2
):
url = (
f"https://v6.exchangerate-api.com/v6/{CURRENCY_API}/"
f"pair/{currency_from}/{currency_to}/{amount}"
)
try:
res = await http.get(url)
data = res.json()
@ -53,6 +58,10 @@ async def currency(self: Client, ctx: Message):
f"**CURRENCY EXCHANGE RATE RESULT:**\n\n`{format(float(amount), ',')}` **{base_code}** = `{format(float(conversion_result), ',')}` **{target_code}**\n<b>Rate Today</b> = `{format(float(conversion_rate), ',')}`\n<b>Last Update:</b> {last_update}"
)
except Exception as err:
await ctx.reply_msg(f"Failed convert currency, maybe you give wrong currency format or api down.\n\n<b>ERROR</b>: {err}")
await ctx.reply_msg(
f"Failed convert currency, maybe you give wrong currency format or api down.\n\n<b>ERROR</b>: {err}"
)
else:
await ctx.reply_msg("<code>This seems to be some alien currency, which I can't convert right now.. (⊙_⊙;)</code>")
await ctx.reply_msg(
"<code>This seems to be some alien currency, which I can't convert right now.. (⊙_⊙;)</code>"
)

View file

@ -64,7 +64,15 @@ async def upload(bot, message):
text = callapi.json()
output = f'<u>File Uploaded to Anonfile</u>\n\n📂 File Name: {text["data"]["file"]["metadata"]["name"]}\n\n📦 File Size: {text["data"]["file"]["metadata"]["size"]["readable"]}\n\n📥 Download Link: {text["data"]["file"]["url"]["full"]}'
btn = InlineKeyboardMarkup([[InlineKeyboardButton("📥 Download 📥", url=f"{text['data']['file']['url']['full']}")]])
btn = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
"📥 Download 📥", url=f"{text['data']['file']['url']['full']}"
)
]
]
)
await m.edit(output, reply_markup=btn)
except Exception as e:
await bot.send_message(message.chat.id, text=f"Something Went Wrong!\n\n{e}")
@ -96,7 +104,9 @@ async def download(client, message):
)
end_t = datetime.now()
ms = (end_t - start_t).seconds
await pesan.edit(f"Downloaded to <code>{the_real_download_location}</code> in <u>{ms}</u> seconds.")
await pesan.edit(
f"Downloaded to <code>{the_real_download_location}</code> in <u>{ms}</u> seconds."
)
elif len(message.command) > 1:
start_t = datetime.now()
the_url_parts = " ".join(message.command[1:])
@ -131,13 +141,17 @@ async def download(client, message):
try:
current_message = "Trying to download...\n"
current_message += f"URL: <code>{url}</code>\n"
current_message += f"File Name: <code>{unquote(custom_file_name)}</code>\n"
current_message += (
f"File Name: <code>{unquote(custom_file_name)}</code>\n"
)
current_message += f"Speed: {speed}\n"
current_message += f"{progress_str}\n"
current_message += f"{downloaded} of {humanbytes(total_length)}\n"
current_message += f"ETA: {estimated_total_time}"
if round(diff % 10.00) == 0 and current_message != display_message:
await pesan.edit(disable_web_page_preview=True, text=current_message)
await pesan.edit(
disable_web_page_preview=True, text=current_message
)
display_message = current_message
await asyncio.sleep(10)
except Exception as e:
@ -145,9 +159,13 @@ async def download(client, message):
if os.path.exists(download_file_path):
end_t = datetime.now()
ms = (end_t - start_t).seconds
await pesan.edit(f"Downloaded to <code>{download_file_path}</code> in {ms} seconds")
await pesan.edit(
f"Downloaded to <code>{download_file_path}</code> in {ms} seconds"
)
else:
await pesan.edit("Reply to a Telegram Media, to download it to my local server.")
await pesan.edit(
"Reply to a Telegram Media, to download it to my local server."
)
@app.on_message(filters.command(["tiktokdl"], COMMAND_HANDLER))
@ -155,11 +173,15 @@ async def download(client, message):
@ratelimiter
async def tiktokdl(client, message):
if len(message.command) == 1:
return await message.reply(f"Use command /{message.command[0]} [link] to download tiktok video.")
return await message.reply(
f"Use command /{message.command[0]} [link] to download tiktok video."
)
link = message.command[1]
msg = await message.reply("Trying download...")
try:
r = (await http.get(f"https://apimu.my.id/downloader/tiktok3?link={link}")).json()
r = (
await http.get(f"https://apimu.my.id/downloader/tiktok3?link={link}")
).json()
await message.reply_video(
r["hasil"]["download_mp4_hd"],
caption=f"<b>Title:</b> <code>{r['hasil']['video_title']}</code>\n<b>Uploader</b>: <a href='https://www.tiktok.com/@{r['hasil']['username']}'>{r['hasil']['name']}</a>\n👍: {r['hasil']['like']} 🔁: {r['hasil']['share']} 💬: {r['hasil']['comment']}\n\nUploaded for {message.from_user.mention} [<code>{message.from_user.id}</code>]",
@ -174,7 +196,9 @@ async def tiktokdl(client, message):
@capture_err
async def fbdl(client, message):
if len(message.command) == 1:
return await message.reply(f"Use command /{message.command[0]} [link] to download Facebook video.")
return await message.reply(
f"Use command /{message.command[0]} [link] to download Facebook video."
)
link = message.command[1]
msg = await message.reply("Trying download...")
try:
@ -197,5 +221,7 @@ async def fbdl(client, message):
except:
pass
except Exception as e:
await message.reply(f"Failed to download Facebook video..\n\n<b>Reason:</b> {e}")
await message.reply(
f"Failed to download Facebook video..\n\n<b>Reason:</b> {e}"
)
await msg.delete()

View file

@ -31,17 +31,28 @@ async def salamregex(_, message):
await message.reply_text(text=f"Wa'alaikumsalam {message.from_user.mention} 😇")
@app.on_message(filters.regex(r"#request|#req", re.I) & (filters.text | filters.photo) & filters.chat(-1001255283935) & ~filters.channel)
@app.on_message(
filters.regex(r"#request|#req", re.I)
& (filters.text | filters.photo)
& filters.chat(-1001255283935)
& ~filters.channel
)
@capture_err
async def request_user(client, message):
if message.sender_chat:
return await message.reply(f"{message.from_user.mention} mohon gunakan akun asli saat request.")
return await message.reply(
f"{message.from_user.mention} mohon gunakan akun asli saat request."
)
is_in_gap, sleep_time = await check_time_gap(message.from_user.id)
if is_in_gap:
return await message.reply("Sabar dikit napa.. 🙄")
markup = InlineKeyboardMarkup(
[
[InlineKeyboardButton(text="💬 Lihat Pesan", url=f"https://t.me/c/1255283935/{message.id}")],
[
InlineKeyboardButton(
text="💬 Lihat Pesan", url=f"https://t.me/c/1255283935/{message.id}"
)
],
[
InlineKeyboardButton(
text="🚫 Tolak",
@ -73,7 +84,9 @@ async def request_user(client, message):
else:
REQUEST_DB[user_id] = 1
if REQUEST_DB[user_id] > 3:
return await message.reply(f"Mohon maaf {message.from_user.mention}, maksimal request hanya 3x perhari. Kalo mau tambah 5k per request 😝😝.")
return await message.reply(
f"Mohon maaf {message.from_user.mention}, maksimal request hanya 3x perhari. Kalo mau tambah 5k per request 😝😝."
)
if message.text:
forward = await client.send_message(
-1001575525902,
@ -164,18 +177,36 @@ async def callbackreq(c, q):
if q.message.caption:
await q.message.edit_text(
f"<b>COMPLETED</b>\n\n<s>{q.message.caption}</s>",
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="✅ Request Completed", callback_data="reqcompl")]]),
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="✅ Request Completed", callback_data="reqcompl"
)
]
]
),
)
else:
await q.message.edit_text(
f"<b>COMPLETED</b>\n\n<s>{q.message.text}</s>",
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="✅ Request Completed", callback_data="reqcompl")]]),
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="✅ Request Completed", callback_data="reqcompl"
)
]
]
),
)
await q.answer("Request berhasil diselesaikan ✅")
else:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True)
except UserNotParticipant:
return await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10)
return await q.answer(
"Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10
)
except PeerIdInvalid:
return await q.answer(
"Silahkan kirim pesan digrup supaya bot bisa merespon.",
@ -232,7 +263,9 @@ async def callbackreqada(c, q):
else:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True)
except UserNotParticipant:
return await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10)
return await q.answer(
"Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10
)
except PeerIdInvalid:
return await q.answer(
"Silahkan kirim pesan digrup supaya bot bisa merespon.",
@ -260,18 +293,36 @@ async def callbackreject(c, q):
if q.message.caption:
await q.message.edit_text(
f"<b>REJECTED</b>\n\n<s>{q.message.caption}</s>",
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="🚫 Request Rejected", callback_data="reqreject")]]),
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="🚫 Request Rejected", callback_data="reqreject"
)
]
]
),
)
else:
await q.message.edit_text(
f"<b>REJECTED</b>\n\n<s>{q.message.text}</s>",
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="🚫 Request Rejected", callback_data="reqreject")]]),
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="🚫 Request Rejected", callback_data="reqreject"
)
]
]
),
)
await q.answer("Request berhasil ditolak 🚫")
else:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True)
except UserNotParticipant:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10)
await q.answer(
"Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10
)
except PeerIdInvalid:
return await q.answer(
"Silahkan kirim pesan digrup supaya bot bisa merespon.",
@ -324,7 +375,9 @@ async def callbackunav(c, q):
]
),
)
await q.answer("Request tidak tersedia, mungkin belum rilis atau memang tidak tersedia versi digital.")
await q.answer(
"Request tidak tersedia, mungkin belum rilis atau memang tidak tersedia versi digital."
)
else:
await q.answer(
"Apa motivasi kamu menekan tombol ini?",
@ -332,7 +385,9 @@ async def callbackunav(c, q):
cache_time=1000,
)
except UserNotParticipant:
await q.answer("Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10)
await q.answer(
"Apa motivasi kamu menekan tombol ini?", show_alert=True, cache_time=10
)
except PeerIdInvalid:
return await q.answer(
"Silahkan kirim pesan digrup supaya bot bisa merespon.",
@ -374,7 +429,9 @@ async def callbackaft_unav(c, q):
@app.on_callback_query(filters.regex(r"^reqavailable$"))
@ratelimiter
async def callbackaft_dahada(c, q):
await q.answer("Request ini sudah ada, silahkan cari 🔍 di channelnya yaa 😉..", show_alert=True)
await q.answer(
"Request ini sudah ada, silahkan cari 🔍 di channelnya yaa 😉..", show_alert=True
)
scheduler = AsyncIOScheduler(timezone="Asia/Jakarta")

View file

@ -57,7 +57,9 @@ async def save_filters(_, m):
del_in=6,
)
if not m.reply_to_message.text and not m.reply_to_message.sticker:
return await m.reply_msg("__**You can only save text or stickers in filters for now.**__")
return await m.reply_msg(
"__**You can only save text or stickers in filters for now.**__"
)
name = m.text.split(None, 1)[1].strip()
if not name:
return await m.reply_msg("**Usage:**\n__/addfilter [FILTER_NAME]__", del_in=6)
@ -65,7 +67,9 @@ async def save_filters(_, m):
_type = "text" if m.reply_to_message.text else "sticker"
_filter = {
"type": _type,
"data": m.reply_to_message.text.markdown if _type == "text" else m.reply_to_message.sticker.file_id,
"data": m.reply_to_message.text.markdown
if _type == "text"
else m.reply_to_message.sticker.file_id,
}
await save_filter(chat_id, name, _filter)
await m.reply_msg(f"__**Saved filter {name}.**__")

View file

@ -16,7 +16,9 @@ async def draw_meme_text(image_path, text):
img = Image.open(image_path)
hapus(image_path)
i_width, i_height = img.size
m_font = ImageFont.truetype("assets/MutantAcademyStyle.ttf", int((70 / 640) * i_width))
m_font = ImageFont.truetype(
"assets/MutantAcademyStyle.ttf", int((70 / 640) * i_width)
)
if ";" in text:
upper_text, lower_text = text.split(";")
else:
@ -144,10 +146,14 @@ async def draw_meme_text(image_path, text):
@capture_err
@ratelimiter
async def memify(client, message):
if message.reply_to_message and (message.reply_to_message.sticker or message.reply_to_message.photo):
if message.reply_to_message and (
message.reply_to_message.sticker or message.reply_to_message.photo
):
try:
file = await message.reply_to_message.download()
webp, png = await draw_meme_text(file, message.text.split(None, 1)[1].strip())
webp, png = await draw_meme_text(
file, message.text.split(None, 1)[1].strip()
)
await gather(*[message.reply_document(png), message.reply_sticker(webp)])
try:
hapus(webp)
@ -162,7 +168,9 @@ async def memify(client, message):
pass
await message.reply_msg(f"ERROR: {err}")
else:
await message.reply_msg("Gunakan command <b>/mmf <text></b> dengan reply ke sticker, pisahkan dengan ; untuk membuat posisi text dibawah.")
await message.reply_msg(
"Gunakan command <b>/mmf <text></b> dengan reply ke sticker, pisahkan dengan ; untuk membuat posisi text dibawah."
)
@app.on_message(filters.command(["dice"], COMMAND_HANDLER))

View file

@ -79,7 +79,9 @@ async def genss(self: Client, ctx: Message, strings):
current_message += f"{downloaded} of {humanbytes(total_length)}\n"
current_message += f"ETA: {estimated_total_time}"
if round(diff % 10.00) == 0 and current_message != display_message:
await pesan.edit(disable_web_page_preview=True, text=current_message)
await pesan.edit(
disable_web_page_preview=True, text=current_message
)
display_message = current_message
await sleep(10)
except Exception as e:
@ -87,11 +89,15 @@ async def genss(self: Client, ctx: Message, strings):
if os.path.exists(download_file_path):
end_t = datetime.now()
ms = (end_t - start_t).seconds
await pesan.edit(f"Downloaded to <code>{download_file_path}</code> in {ms} seconds")
await pesan.edit(
f"Downloaded to <code>{download_file_path}</code> in {ms} seconds"
)
try:
images = await take_ss(download_file_path)
await pesan.edit_msg(strings("up_progress"))
await self.send_chat_action(chat_id=ctx.chat.id, action=enums.ChatAction.UPLOAD_PHOTO)
await self.send_chat_action(
chat_id=ctx.chat.id, action=enums.ChatAction.UPLOAD_PHOTO
)
try:
await gather(
*[
@ -146,11 +152,15 @@ async def genss(self: Client, ctx: Message, strings):
the_real_download_location = os.path.join("/downloads/", os.path.basename(dl))
if the_real_download_location is not None:
try:
await process.edit_msg(strings("success_dl_msg").format(path=the_real_download_location))
await process.edit_msg(
strings("success_dl_msg").format(path=the_real_download_location)
)
await sleep(2)
images = await take_ss(the_real_download_location)
await process.edit_msg(strings("up_progress"))
await self.send_chat_action(chat_id=ctx.chat.id, action=enums.ChatAction.UPLOAD_PHOTO)
await self.send_chat_action(
chat_id=ctx.chat.id, action=enums.ChatAction.UPLOAD_PHOTO
)
try:
await gather(

View file

@ -20,54 +20,77 @@ __HELP__ = """"
"""
@app.on_message(filters.incoming & ~filters.private & filters.command(["inkick"], COMMAND_HANDLER))
@app.on_message(
filters.incoming & ~filters.private & filters.command(["inkick"], COMMAND_HANDLER)
)
@ratelimiter
async def inkick(_, message):
if message.sender_chat:
return await message.reply_msg("This feature not available for channel.", del_in=4)
return await message.reply_msg(
"This feature not available for channel.", del_in=4
)
user = await app.get_chat_member(message.chat.id, message.from_user.id)
if user.status.value in ("administrator", "owner"):
if len(message.command) > 1:
input_str = message.command
sent_message = await message.reply_text("🚮**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**")
sent_message = await message.reply_text(
"🚮**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**"
)
count = 0
async for member in app.get_chat_members(message.chat.id):
if member.user.is_bot:
continue
if member.user.status.value in input_str and member.status.value not in ("administrator", "owner"):
if (
member.user.status.value in input_str
and member.status.value not in ("administrator", "owner")
):
try:
await message.chat.ban_member(member.user.id)
count += 1
await sleep(1)
await message.chat.unban_member(member.user.id)
except (ChatAdminRequired, UserAdminInvalid):
await sent_message.edit("❗**Oh tidaakk, saya bukan admin disini**\n__Saya pergi dari sini, tambahkan aku kembali dengan perijinan banned pengguna.__")
await sent_message.edit(
"❗**Oh tidaakk, saya bukan admin disini**\n__Saya pergi dari sini, tambahkan aku kembali dengan perijinan banned pengguna.__"
)
await app.leave_chat(message.chat.id)
break
except FloodWait as e:
await sleep(e.value)
try:
await sent_message.edit(f"✔️ **Berhasil menendang {count} pengguna berdasarkan argumen.**")
await sent_message.edit(
f"✔️ **Berhasil menendang {count} pengguna berdasarkan argumen.**"
)
except ChatWriteForbidden:
await app.leave_chat(message.chat.id)
else:
await message.reply_text("❗ **Arguments Required**\n__See /help in personal message for more information.__")
await message.reply_text(
"❗ **Arguments Required**\n__See /help in personal message for more information.__"
)
else:
sent_message = await message.reply_text("❗ **You have to be the group creator to do that.**")
sent_message = await message.reply_text(
"❗ **You have to be the group creator to do that.**"
)
await sleep(5)
await sent_message.delete()
# Kick User Without Username
@app.on_message(filters.incoming & ~filters.private & filters.command(["uname"], COMMAND_HANDLER))
@app.on_message(
filters.incoming & ~filters.private & filters.command(["uname"], COMMAND_HANDLER)
)
@ratelimiter
async def uname(_, message):
if message.sender_chat:
return await message.reply_msg("This feature not available for channel.", del_in=4)
return await message.reply_msg(
"This feature not available for channel.", del_in=4
)
user = await app.get_chat_member(message.chat.id, message.from_user.id)
if user.status.value in ("administrator", "owner"):
sent_message = await message.reply_text("🚮**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**")
sent_message = await message.reply_text(
"🚮**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**"
)
count = 0
async for member in app.get_chat_members(message.chat.id):
if not member.user.username and member.status.value not in (
@ -80,30 +103,44 @@ async def uname(_, message):
await sleep(1)
await message.chat.unban_member(member.user.id)
except (ChatAdminRequired, UserAdminInvalid):
await sent_message.edit("❗**Oh tidaakk, saya bukan admin disini**\n__Saya pergi dari sini, tambahkan aku kembali dengan perijinan banned pengguna.__")
await sent_message.edit(
"❗**Oh tidaakk, saya bukan admin disini**\n__Saya pergi dari sini, tambahkan aku kembali dengan perijinan banned pengguna.__"
)
await app.leave_chat(message.chat.id)
break
except FloodWait as e:
await sleep(e.value)
try:
await sent_message.edit(f"✔️ **Berhasil menendang {count} pengguna berdasarkan argumen.**")
await sent_message.edit(
f"✔️ **Berhasil menendang {count} pengguna berdasarkan argumen.**"
)
except ChatWriteForbidden:
await app.leave_chat(message.chat.id)
else:
sent_message = await message.reply_text("❗ **You have to be the group creator to do that.**")
sent_message = await message.reply_text(
"❗ **You have to be the group creator to do that.**"
)
await sleep(5)
await sent_message.delete()
@app.on_message(filters.incoming & ~filters.private & filters.command(["ban_ghosts"], COMMAND_HANDLER))
@app.on_message(
filters.incoming
& ~filters.private
& filters.command(["ban_ghosts"], COMMAND_HANDLER)
)
@ratelimiter
async def rm_delacc(client, message):
if message.sender_chat:
return await message.reply_msg("This feature not available for channel.", del_in=4)
return await message.reply_msg(
"This feature not available for channel.", del_in=4
)
user = await app.get_chat_member(message.chat.id, message.from_user.id)
if user.status.value in ("administrator", "owner"):
sent_message = await message.reply_text("🚮**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**")
sent_message = await message.reply_text(
"🚮**Sedang membersihkan user, mungkin butuh waktu beberapa saat...**"
)
count = 0
async for member in app.get_chat_members(message.chat.id):
if member.user.is_deleted and member.status.value not in (
@ -116,27 +153,37 @@ async def rm_delacc(client, message):
await sleep(1)
await message.chat.unban_member(member.user.id)
except (ChatAdminRequired, UserAdminInvalid):
await sent_message.edit("❗**Oh Nooo, i'm doesn't have admin permission in this group. Make sure i'm have admin permission to <b>ban users</b>.")
await sent_message.edit(
"❗**Oh Nooo, i'm doesn't have admin permission in this group. Make sure i'm have admin permission to <b>ban users</b>."
)
break
except FloodWait as e:
await sleep(e.value)
if count == 0:
return await sent_message.edit_msg("There are no deleted accounts in this chat.")
return await sent_message.edit_msg(
"There are no deleted accounts in this chat."
)
await sent_message.edit_msg(f"✔️ **Berhasil menendang {count} akun terhapus.**")
else:
sent_message = await message.reply_text("❗ **Kamu harus jadi admin atau owner grup untuk melakukan tindakan ini.**")
sent_message = await message.reply_text(
"❗ **Kamu harus jadi admin atau owner grup untuk melakukan tindakan ini.**"
)
await sleep(5)
await sent_message.delete()
@app.on_message(filters.incoming & ~filters.private & filters.command(["instatus"], COMMAND_HANDLER))
@app.on_message(
filters.incoming & ~filters.private & filters.command(["instatus"], COMMAND_HANDLER)
)
@ratelimiter
async def instatus(client, message):
if message.sender_chat:
return await message.reply_msg("Not supported channel.", del_in=4)
bstat = await app.get_chat_member(message.chat.id, client.me.id)
if bstat.status.value != "administrator":
return await message.reply_msg("Please give me all basic admin permission, to run this command.")
return await message.reply_msg(
"Please give me all basic admin permission, to run this command."
)
start_time = time.perf_counter()
user = await app.get_chat_member(message.chat.id, message.from_user.id)
count = await app.get_chat_members_count(message.chat.id)
@ -144,7 +191,9 @@ async def instatus(client, message):
enums.ChatMemberStatus.ADMINISTRATOR,
enums.ChatMemberStatus.OWNER,
):
sent_message = await message.reply_text("**Sedang mengumpulkan informasi pengguna...**")
sent_message = await message.reply_text(
"**Sedang mengumpulkan informasi pengguna...**"
)
recently = 0
within_week = 0
within_month = 0
@ -156,9 +205,13 @@ async def instatus(client, message):
banned = 0
uncached = 0
bot = 0
async for ban in app.get_chat_members(message.chat.id, filter=enums.ChatMembersFilter.BANNED):
async for ban in app.get_chat_members(
message.chat.id, filter=enums.ChatMembersFilter.BANNED
):
banned += 1
async for restr in app.get_chat_members(message.chat.id, filter=enums.ChatMembersFilter.RESTRICTED):
async for restr in app.get_chat_members(
message.chat.id, filter=enums.ChatMembersFilter.RESTRICTED
):
restricted += 1
async for member in app.get_chat_members(message.chat.id):
user = member.user
@ -201,6 +254,8 @@ async def instatus(client, message):
)
)
else:
sent_message = await message.reply_text("❗ **Kamu harus jadi admin atau owner grup untuk melakukan tindakan ini.**")
sent_message = await message.reply_text(
"❗ **Kamu harus jadi admin atau owner grup untuk melakukan tindakan ini.**"
)
await sleep(5)
await sent_message.delete()

View file

@ -15,9 +15,14 @@ from pykeyboard import InlineButton, InlineKeyboard
from pyrogram import __version__ as pyrover
from pyrogram import enums, filters
from pyrogram.errors import MessageIdInvalid, MessageNotModified
from pyrogram.types import (InlineKeyboardButton, InlineKeyboardMarkup,
InlineQuery, InlineQueryResultArticle,
InlineQueryResultPhoto, InputTextMessageContent)
from pyrogram.types import (
InlineKeyboardButton,
InlineKeyboardMarkup,
InlineQuery,
InlineQueryResultArticle,
InlineQueryResultPhoto,
InputTextMessageContent,
)
from misskaty import BOT_USERNAME, app, user
from misskaty.core.decorator.ratelimiter import ratelimiter

View file

@ -46,18 +46,30 @@ def section(
text = (bold_ul(title) + n) if underline else bold(title) + n
for key, value in body.items():
text += indent * w + bold(key) + ((value[0] + n) if isinstance(value, list) else mono(value))
text += (
indent * w
+ bold(key)
+ ((value[0] + n) if isinstance(value, list) else mono(value))
)
return text
async def get_user_id_and_usernames(client) -> dict:
with client.storage.lock, client.storage.conn:
users = client.storage.conn.execute('SELECT * FROM peers WHERE type in ("user", "bot") AND username NOT null').fetchall()
users = client.storage.conn.execute(
'SELECT * FROM peers WHERE type in ("user", "bot") AND username NOT null'
).fetchall()
return {user[0]: user[3] for user in users}
@app.on_message(
filters.text & filters.group & filters.incoming & filters.reply & filters.regex(regex_upvote, re.IGNORECASE) & ~filters.via_bot & ~filters.bot,
filters.text
& filters.group
& filters.incoming
& filters.reply
& filters.regex(regex_upvote, re.IGNORECASE)
& ~filters.via_bot
& ~filters.bot,
group=karma_positive_group,
)
@capture_err
@ -83,11 +95,19 @@ async def upvote(_, message):
karma = 1
new_karma = {"karma": karma}
await update_karma(chat_id, await int_to_alpha(user_id), new_karma)
await message.reply_text(f"Incremented Karma of {user_mention} By 1 \nTotal Points: {karma}")
await message.reply_text(
f"Incremented Karma of {user_mention} By 1 \nTotal Points: {karma}"
)
@app.on_message(
filters.text & filters.group & filters.incoming & filters.reply & filters.regex(regex_downvote, re.IGNORECASE) & ~filters.via_bot & ~filters.bot,
filters.text
& filters.group
& filters.incoming
& filters.reply
& filters.regex(regex_downvote, re.IGNORECASE)
& ~filters.via_bot
& ~filters.bot,
group=karma_negative_group,
)
@capture_err
@ -123,7 +143,9 @@ async def downvote(_, message):
karma = 1
new_karma = {"karma": karma}
await update_karma(chat_id, await int_to_alpha(user_id), new_karma)
await message.reply_text(f"Decremented Karma of {user_mention} By 1 \nTotal Points: {karma}")
await message.reply_text(
f"Decremented Karma of {user_mention} By 1 \nTotal Points: {karma}"
)
@app.on_message(filters.command("karma") & filters.group)

View file

@ -103,7 +103,9 @@ async def tg_lock(message, permissions: list, perm: str, lock: bool):
try:
await app.set_chat_permissions(message.chat.id, ChatPermissions(**permissions))
except ChatNotModified:
return await message.reply_text("To unlock this, you have to unlock 'messages' first.")
return await message.reply_text(
"To unlock this, you have to unlock 'messages' first."
)
await message.reply_text(("Locked." if lock else "Unlocked."))
@ -176,4 +178,7 @@ async def url_detector(_, message):
try:
await message.delete_msg()
except Exception:
await message.reply_msg("This message contains a URL, " + "but i don't have enough permissions to delete it")
await message.reply_msg(
"This message contains a URL, "
+ "but i don't have enough permissions to delete it"
)

View file

@ -13,8 +13,12 @@ from time import time
from urllib.parse import unquote
from pyrogram import Client, filters
from pyrogram.types import (CallbackQuery, InlineKeyboardButton,
InlineKeyboardMarkup, Message)
from pyrogram.types import (
CallbackQuery,
InlineKeyboardButton,
InlineKeyboardMarkup,
Message,
)
from misskaty import app
from misskaty.core.decorator.errors import capture_err
@ -60,7 +64,9 @@ def get_subname(lang, url, ext):
fragment_removed = url.split("#")[0] # keep to left of first #
query_string_removed = fragment_removed.split("?")[0]
scheme_removed = query_string_removed.split("://")[-1].split(":")[-1]
if scheme_removed.find("/") == -1 or not get_base_name(os.path.basename(unquote(scheme_removed))):
if scheme_removed.find("/") == -1 or not get_base_name(
os.path.basename(unquote(scheme_removed))
):
return f"[{lang.upper()}] MissKatySub{get_random_string(4)}.{ext}"
return f"[{lang.upper()}] {get_base_name(os.path.basename(unquote(scheme_removed)))}{get_random_string(3)}.{ext}"
@ -70,12 +76,18 @@ def get_subname(lang, url, ext):
@use_chat_lang()
async def ceksub(self: Client, ctx: Message, strings):
if len(ctx.command) == 1:
return await ctx.reply_msg(strings("sub_extr_help").format(cmd=ctx.command[0]), quote=True, del_in=5)
return await ctx.reply_msg(
strings("sub_extr_help").format(cmd=ctx.command[0]), quote=True, del_in=5
)
link = ctx.command[1]
start_time = time()
pesan = await ctx.reply_msg(strings("progress_str"), quote=True)
try:
res = (await shell_exec(f"ffprobe -loglevel 0 -print_format json -show_format -show_streams {link}"))[0]
res = (
await shell_exec(
f"ffprobe -loglevel 0 -print_format json -show_format -show_streams {link}"
)
)[0]
details = json.loads(res)
buttons = []
for stream in details["streams"]:
@ -100,7 +112,9 @@ async def ceksub(self: Client, ctx: Message, strings):
]
)
timelog = time() - start_time
buttons.append([InlineKeyboardButton(strings("cancel_btn"), f"close#{ctx.from_user.id}")])
buttons.append(
[InlineKeyboardButton(strings("cancel_btn"), f"close#{ctx.from_user.id}")]
)
msg = await pesan.edit_msg(
strings("press_btn_msg").format(timelog=get_readable_time(timelog)),
reply_markup=InlineKeyboardMarkup(buttons),
@ -118,16 +132,27 @@ async def ceksub(self: Client, ctx: Message, strings):
@use_chat_lang()
async def convertsrt(self: Client, ctx: Message, strings):
reply = ctx.reply_to_message
if not reply or not reply.document or not reply.document.file_name or not reply.document.file_name.endswith((".vtt", ".ass", ".srt")):
return await ctx.reply_msg(strings("conv_sub_help").format(cmd=ctx.command[0]), del_in=6)
if (
not reply
or not reply.document
or not reply.document.file_name
or not reply.document.file_name.endswith((".vtt", ".ass", ".srt"))
):
return await ctx.reply_msg(
strings("conv_sub_help").format(cmd=ctx.command[0]), del_in=6
)
msg = await ctx.reply_msg(strings("convert_str"), quote=True)
if not os.path.exists("downloads"):
os.makedirs("downloads")
dl = await reply.download(file_name="downloads/")
filename = dl.split("/", 3)[3]
LOGGER.info(f"ConvertSub: {filename} by {ctx.from_user.first_name if ctx.from_user else ctx.sender_chat.title} [{ctx.from_user.id if ctx.from_user else ctx.sender_chat.id}]")
LOGGER.info(
f"ConvertSub: {filename} by {ctx.from_user.first_name if ctx.from_user else ctx.sender_chat.title} [{ctx.from_user.id if ctx.from_user else ctx.sender_chat.id}]"
)
suffix = "srt" if ctx.command[0] == "converttosrt" else "ass"
(await shell_exec(f"ffmpeg -i '{dl}' 'downloads/{filename}.{suffix}'"))[0] # skipcq: PYL-W0106
(await shell_exec(f"ffmpeg -i '{dl}' 'downloads/{filename}.{suffix}'"))[
0
] # skipcq: PYL-W0106
c_time = time()
await ctx.reply_document(
f"downloads/{filename}.{suffix}",
@ -169,13 +194,17 @@ async def stream_extract(self: Client, update: CallbackQuery, strings):
start_time = time()
namafile = get_subname(lang, link, ext)
try:
LOGGER.info(f"ExtractSub: {namafile} by {update.from_user.first_name} [{update.from_user.id}]")
LOGGER.info(
f"ExtractSub: {namafile} by {update.from_user.first_name} [{update.from_user.id}]"
)
(await shell_exec(f"ffmpeg -i {link} -map {map_code} '{namafile}'"))[0]
timelog = time() - start_time
c_time = time()
await update.message.reply_document(
namafile,
caption=strings("capt_extr_sub").format(nf=namafile, bot=self.me.username, timelog=get_readable_time(timelog)),
caption=strings("capt_extr_sub").format(
nf=namafile, bot=self.me.username, timelog=get_readable_time(timelog)
),
reply_to_message_id=usr.id,
thumb="assets/thumb.jpg",
progress=progress_for_pyrogram,

View file

@ -34,7 +34,13 @@ async def mediainfo(self: Client, ctx: Message, strings):
file_info = get_file_id(ctx.reply_to_message)
if file_info is None:
return await process.edit_msg(strings("media_invalid"))
if (ctx.reply_to_message.video and ctx.reply_to_message.video.file_size > 2097152000) or (ctx.reply_to_message.document and ctx.reply_to_message.document.file_size > 2097152000):
if (
ctx.reply_to_message.video
and ctx.reply_to_message.video.file_size > 2097152000
) or (
ctx.reply_to_message.document
and ctx.reply_to_message.document.file_size > 2097152000
):
return await process.edit_msg(strings("dl_limit_exceeded"), del_in=6)
c_time = time.time()
dc_id = FileId.decode(file_info.file_id).dc_id
@ -56,11 +62,15 @@ DETAILS
"""
try:
link = await mediainfo_paste(out, "MissKaty Mediainfo")
markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=strings("viweb"), url=link)]])
markup = InlineKeyboardMarkup(
[[InlineKeyboardButton(text=strings("viweb"), url=link)]]
)
except:
try:
link = await post_to_telegraph(False, "MissKaty MediaInfo", body_text)
markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=strings("viweb"), url=link)]])
markup = InlineKeyboardMarkup(
[[InlineKeyboardButton(text=strings("viweb"), url=link)]]
)
except:
markup = None
with io.BytesIO(str.encode(body_text)) as out_file:
@ -81,7 +91,9 @@ DETAILS
link = ctx.input
process = await ctx.reply_msg(strings("wait_msg"))
try:
output = subprocess.check_output(["mediainfo", f"{link}"]).decode("utf-8")
output = subprocess.check_output(["mediainfo", f"{link}"]).decode(
"utf-8"
)
except Exception:
return await process.edit_msg(strings("err_link"))
body_text = f"""
@ -91,11 +103,17 @@ DETAILS
# link = await post_to_telegraph(False, title, body_text)
try:
link = await mediainfo_paste(out, "MissKaty Mediainfo")
markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=strings("viweb"), url=link)]])
markup = InlineKeyboardMarkup(
[[InlineKeyboardButton(text=strings("viweb"), url=link)]]
)
except:
try:
link = await post_to_telegraph(False, "MissKaty MediaInfo", body_text)
markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=strings("viweb"), url=link)]])
link = await post_to_telegraph(
False, "MissKaty MediaInfo", body_text
)
markup = InlineKeyboardMarkup(
[[InlineKeyboardButton(text=strings("viweb"), url=link)]]
)
except:
markup = None
with io.BytesIO(str.encode(output)) as out_file:
@ -108,4 +126,6 @@ DETAILS
)
await process.delete()
except IndexError:
return await ctx.reply_msg(strings("mediainfo_help").format(cmd=ctx.command[0]), del_in=6)
return await ctx.reply_msg(
strings("mediainfo_help").format(cmd=ctx.command[0]), del_in=6
)

View file

@ -38,7 +38,9 @@ __HELP__ = """<b>Enable or disable nightmode (locks the chat at specified interv
"""
TIME_ZONE = pytz.timezone(TZ)
reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="❤️", callback_data="nightmd")]])
reply_markup = InlineKeyboardMarkup(
[[InlineKeyboardButton(text="❤️", callback_data="nightmd")]]
)
# Check calculate how long it will take to Ramadhan
@ -103,28 +105,36 @@ async def un_mute_chat(chat_id: int, perm: ChatPermissions):
except ChatAdminRequired:
await app.send_message(
LOG_CHANNEL,
langdict[getlang]["nightmodev2"]["nmd_off_not_admin"].format(chat_id=chat_id, bname=BOT_NAME),
langdict[getlang]["nightmodev2"]["nmd_off_not_admin"].format(
chat_id=chat_id, bname=BOT_NAME
),
)
except (ChannelInvalid, ChannelPrivate):
scheduler.remove_job(f"enable_nightmode_{chat_id}")
scheduler.remove_job(f"disable_nightmode_{chat_id}")
await app.send_message(
LOG_CHANNEL,
langdict[getlang]["nightmodev2"]["nmd_off_not_present"].format(chat_id=chat_id, bname=BOT_NAME),
langdict[getlang]["nightmodev2"]["nmd_off_not_present"].format(
chat_id=chat_id, bname=BOT_NAME
),
)
except ChatNotModified:
pass
except Exception as e:
await app.send_message(
LOG_CHANNEL,
langdict[getlang]["nightmodev2"]["nmd_off_err"].format(chat_id=chat_id, e=e),
langdict[getlang]["nightmodev2"]["nmd_off_err"].format(
chat_id=chat_id, e=e
),
)
else:
job = scheduler.get_job(f"enable_nightmode_{chat_id}")
close_at = job.next_run_time
await app.send_message(
chat_id,
langdict[getlang]["nightmodev2"]["nmd_off_success"].format(dt=tglsekarang(), close_at=close_at),
langdict[getlang]["nightmodev2"]["nmd_off_success"].format(
dt=tglsekarang(), close_at=close_at
),
reply_markup=reply_markup,
)
@ -137,14 +147,18 @@ async def mute_chat(chat_id: int):
except ChatAdminRequired:
await app.send_message(
LOG_CHANNEL,
langdict[getlang]["nightmodev2"]["nmd_on_not_admin"].format(chat_id=chat_id, bname=BOT_NAME),
langdict[getlang]["nightmodev2"]["nmd_on_not_admin"].format(
chat_id=chat_id, bname=BOT_NAME
),
)
except (ChannelInvalid, ChannelPrivate):
scheduler.remove_job(f"enable_nightmode_{chat_id}")
scheduler.remove_job(f"disable_nightmode_{chat_id}")
await app.send_message(
LOG_CHANNEL,
langdict[getlang]["nightmodev2"]["nmd_on_not_present"].format(chat_id=chat_id, bname=BOT_NAME),
langdict[getlang]["nightmodev2"]["nmd_on_not_present"].format(
chat_id=chat_id, bname=BOT_NAME
),
)
except ChatNotModified:
pass
@ -158,7 +172,9 @@ async def mute_chat(chat_id: int):
open_at = job.next_run_time
await app.send_message(
chat_id,
langdict[getlang]["nightmodev2"]["nmd_on_success"].format(dt=tglsekarang(), open_at=open_at),
langdict[getlang]["nightmodev2"]["nmd_on_success"].format(
dt=tglsekarang(), open_at=open_at
),
reply_markup=reply_markup,
)
@ -183,7 +199,9 @@ async def nightmode_handler(c, msg, strings):
now = datetime.now(TIME_ZONE)
try:
start_timestamp = TIME_ZONE.localize(datetime.strptime((now.strftime("%m:%d:%Y - ") + start), "%m:%d:%Y - %H:%M"))
start_timestamp = TIME_ZONE.localize(
datetime.strptime((now.strftime("%m:%d:%Y - ") + start), "%m:%d:%Y - %H:%M")
)
except ValueError:
return await msg.reply_msg(strings("invalid_time_format"), del_in=6)
lockdur = re.findall(r"-e=(\w+)", msg.text)
@ -222,7 +240,11 @@ async def nightmode_handler(c, msg, strings):
)
except ConflictingIdError:
return await msg.reply_msg(strings("schedule_already_on"))
await msg.reply_msg(strings("nmd_enable_success").format(st=start_timestamp.strftime("%H:%M:%S"), lockdur=lockdur))
await msg.reply_msg(
strings("nmd_enable_success").format(
st=start_timestamp.strftime("%H:%M:%S"), lockdur=lockdur
)
)
if not bool(scheduler.state):
scheduler.start()
@ -232,6 +254,8 @@ async def nightmode_handler(c, msg, strings):
@use_chat_lang()
async def callbackanightmd(c, q, strings):
await q.answer(
strings("nmd_cb").format(bname=c.me.first_name, ver=__version__, pyver=platform.python_version()),
strings("nmd_cb").format(
bname=c.me.first_name, ver=__version__, pyver=platform.python_version()
),
show_alert=True,
)

View file

@ -62,7 +62,9 @@ async def save_notee(_, message):
_type = "text" if message.reply_to_message.text else "sticker"
note = {
"type": _type,
"data": message.reply_to_message.text.markdown if _type == "text" else message.reply_to_message.sticker.file_id,
"data": message.reply_to_message.text.markdown
if _type == "text"
else message.reply_to_message.sticker.file_id,
}
chat_id = message.chat.id
await save_note(chat_id, name, note)

View file

@ -39,7 +39,9 @@ async def handwrite(client, message):
elif len(message.command) > 1:
txt = message.text.split(None, 1)[1]
else:
return await message.reply("Please reply to message or write after command to use Nulis CMD.")
return await message.reply(
"Please reply to message or write after command to use Nulis CMD."
)
nan = await message.reply_msg("Processing...")
try:
img = Image.open("assets/kertas.jpg")
@ -54,7 +56,9 @@ async def handwrite(client, message):
file = f"nulis_{message.from_user.id}.jpg"
img.save(file)
if os.path.exists(file):
await message.reply_photo(photo=file, caption=f"<b>Written By :</b> {client.me.mention}")
await message.reply_photo(
photo=file, caption=f"<b>Written By :</b> {client.me.mention}"
)
os.remove(file)
await nan.delete()
except Exception as e:

View file

@ -29,13 +29,22 @@ __HELP__ = "/ocr [reply to photo] - Read Text From Image"
@use_chat_lang()
async def ocr(self: Client, ctx: Message, strings):
reply = ctx.reply_to_message
if not reply or not reply.sticker and not reply.photo and (not reply.document or not reply.document.mime_type.startswith("image")):
return await ctx.reply_msg(strings("no_photo").format(cmd=ctx.command[0]), quote=True)
if (
not reply
or not reply.sticker
and not reply.photo
and (not reply.document or not reply.document.mime_type.startswith("image"))
):
return await ctx.reply_msg(
strings("no_photo").format(cmd=ctx.command[0]), quote=True
)
msg = await ctx.reply_msg(strings("read_ocr"), quote=True)
try:
file_path = await reply.download()
if reply.sticker:
file_path = await reply.download(f"ocr_{ctx.from_user.id if ctx.from_user else ctx.sender_chat.id}.jpg")
file_path = await reply.download(
f"ocr_{ctx.from_user.id if ctx.from_user else ctx.sender_chat.id}.jpg"
)
response = await Telegraph().upload_file(file_path)
url = f"https://telegra.ph{response[0]['src']}"
req = (

View file

@ -56,7 +56,9 @@ async def ping_handler(self: Client, ctx: Message):
check=True,
capture_output=True,
)
resp_time = findall(r"time=.+m?s", shell.stdout, MULTILINE)[0].replace("time=", "")
resp_time = findall(r"time=.+m?s", shell.stdout, MULTILINE)[0].replace(
"time=", ""
)
text += f" **{dc.upper()}:** {resp_time}\n"
except Exception:

View file

@ -31,7 +31,9 @@ async def getDataPypi(msg, kueri, CurrentPage, user):
pypiResult = f"<b>#Pypi Results For:</b> <code>{kueri}</code>\n\n"
for c, i in enumerate(PYPI_DICT[msg.id][0][index], start=1):
pypiResult += f"<b>{c}.</b> <a href='{i['url']}'>{i['name']} {i['version']}</a>\n<b>Created:</b> <code>{i['created']}</code>\n<b>Desc:</b> <code>{i['description']}</code>\n\n"
extractbtn.append(InlineButton(c, f"pypidata#{CurrentPage}#{c}#{user}#{msg.id}"))
extractbtn.append(
InlineButton(c, f"pypidata#{CurrentPage}#{c}#{user}#{msg.id}")
)
pypiResult = "".join(i for i in pypiResult if i not in "[]")
return pypiResult, PageLen, extractbtn
except (IndexError, KeyError):
@ -44,14 +46,20 @@ async def getDataPypi(msg, kueri, CurrentPage, user):
async def pypi_s(self: Client, ctx: Message):
kueri = " ".join(ctx.command[1:])
if not kueri:
return await ctx.reply_msg("Please add query after command. Ex: <code>/pypi pyrogram</code>", del_in=6)
return await ctx.reply_msg(
"Please add query after command. Ex: <code>/pypi pyrogram</code>", del_in=6
)
pesan = await ctx.reply_msg("⏳ Please wait, getting data from pypi..", quote=True)
CurrentPage = 1
pypires, PageLen, btn = await getDataPypi(pesan, kueri, CurrentPage, ctx.from_user.id)
pypires, PageLen, btn = await getDataPypi(
pesan, kueri, CurrentPage, ctx.from_user.id
)
if not pypires:
return
keyboard = InlineKeyboard()
keyboard.paginate(PageLen, CurrentPage, "page_pypi#{number}" + f"#{pesan.id}#{ctx.from_user.id}")
keyboard.paginate(
PageLen, CurrentPage, "page_pypi#{number}" + f"#{pesan.id}#{ctx.from_user.id}"
)
keyboard.row(InlineButton("👇 Get Info ", "Hmmm"))
keyboard.row(*btn)
keyboard.row(InlineButton("❌ Close", f"close#{ctx.from_user.id}"))
@ -68,10 +76,14 @@ async def pypipage_callback(self: Client, callback_query: CallbackQuery):
try:
kueri = PYPI_DICT[message_id][1]
except KeyError:
return await callback_query.answer("Invalid callback data, please send CMD again..")
return await callback_query.answer(
"Invalid callback data, please send CMD again.."
)
try:
pypires, PageLen, btn = await getDataPypi(callback_query.message, kueri, CurrentPage, callback_query.from_user.id)
pypires, PageLen, btn = await getDataPypi(
callback_query.message, kueri, CurrentPage, callback_query.from_user.id
)
except TypeError:
return
@ -98,7 +110,9 @@ async def pypi_getdata(self: Client, callback_query: CallbackQuery):
try:
pkgname = PYPI_DICT[message_id][0][CurrentPage - 1][idlink - 1].get("name")
except KeyError:
return await callback_query.answer("Invalid callback data, please send CMD again..")
return await callback_query.answer(
"Invalid callback data, please send CMD again.."
)
keyboard = InlineKeyboard()
keyboard.row(
@ -111,7 +125,11 @@ async def pypi_getdata(self: Client, callback_query: CallbackQuery):
try:
html = await http.get(f"https://pypi.org/pypi/{pkgname}/json", headers=headers)
res = html.json()
requirement = "".join(f"{i}, " for i in res["info"].get("requires_dist")) if res["info"].get("requires_dist") else "Unknown"
requirement = (
"".join(f"{i}, " for i in res["info"].get("requires_dist"))
if res["info"].get("requires_dist")
else "Unknown"
)
msg = ""
msg += f"<b>Package Name:</b> {res['info'].get('name', 'Unknown')}\n"
msg += f"<b>Version:</b> {res['info'].get('version', 'Unknown')}\n"
@ -119,13 +137,17 @@ async def pypi_getdata(self: Client, callback_query: CallbackQuery):
msg += f"<b>Author:</b> {res['info'].get('author', 'Unknown')}\n"
msg += f"<b>Author Email:</b> {res['info'].get('author_email', 'Unknown')}\n"
msg += f"<b>Requirements:</b> {requirement}\n"
msg += f"<b>Requires Python:</b> {res['info'].get('requires_python', 'Unknown')}\n"
msg += (
f"<b>Requires Python:</b> {res['info'].get('requires_python', 'Unknown')}\n"
)
msg += f"<b>HomePage:</b> {res['info'].get('home_page', 'Unknown')}\n"
msg += f"<b>Bug Track:</b> {res['info'].get('vulnerabilities', 'Unknown')}\n"
if res["info"].get("project_urls"):
msg += f"<b>Docs Url:</b> {res['info']['project_urls'].get('Documentation', 'Unknown')}\n"
msg += f"<b>Description:</b> {res['info'].get('summary', 'Unknown')}\n"
msg += f"<b>Pip Command:</b> pip3 install {res['info'].get('name', 'Unknown')}\n"
msg += (
f"<b>Pip Command:</b> pip3 install {res['info'].get('name', 'Unknown')}\n"
)
msg += f"<b>Keywords:</b> {res['info'].get('keywords', 'Unknown')}\n"
except Exception as err:
await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard)

View file

@ -45,7 +45,11 @@ async def get_message_sender_name(ctx: Message):
if ctx.forward_sender_name:
return ctx.forward_sender_name
elif ctx.forward_from:
return f"{ctx.forward_from.first_name} {ctx.forward_from.last_name}" if ctx.forward_from.last_name else ctx.forward_from.first_name
return (
f"{ctx.forward_from.first_name} {ctx.forward_from.last_name}"
if ctx.forward_from.last_name
else ctx.forward_from.first_name
)
elif ctx.forward_from_chat:
return ctx.forward_from_chat.title
@ -64,22 +68,45 @@ async def get_message_sender_name(ctx: Message):
async def get_custom_emoji(ctx: Message):
if ctx.forward_date:
return "" if ctx.forward_sender_name or not ctx.forward_from and ctx.forward_from_chat or not ctx.forward_from else ctx.forward_from.emoji_status.custom_emoji_id
return (
""
if ctx.forward_sender_name
or not ctx.forward_from
and ctx.forward_from_chat
or not ctx.forward_from
else ctx.forward_from.emoji_status.custom_emoji_id
)
return ctx.from_user.emoji_status.custom_emoji_id if ctx.from_user else ""
async def get_message_sender_username(ctx: Message):
if ctx.forward_date:
if not ctx.forward_sender_name and not ctx.forward_from and ctx.forward_from_chat and ctx.forward_from_chat.username:
if (
not ctx.forward_sender_name
and not ctx.forward_from
and ctx.forward_from_chat
and ctx.forward_from_chat.username
):
return ctx.forward_from_chat.username
elif not ctx.forward_sender_name and not ctx.forward_from and ctx.forward_from_chat or ctx.forward_sender_name or not ctx.forward_from:
elif (
not ctx.forward_sender_name
and not ctx.forward_from
and ctx.forward_from_chat
or ctx.forward_sender_name
or not ctx.forward_from
):
return ""
else:
return ctx.forward_from.username or ""
elif ctx.from_user and ctx.from_user.username:
return ctx.from_user.username
elif ctx.from_user or ctx.sender_chat and not ctx.sender_chat.username or not ctx.sender_chat:
elif (
ctx.from_user
or ctx.sender_chat
and not ctx.sender_chat.username
or not ctx.sender_chat
):
return ""
else:
return ctx.sender_chat.username
@ -87,14 +114,25 @@ async def get_message_sender_username(ctx: Message):
async def get_message_sender_photo(ctx: Message):
if ctx.forward_date:
if not ctx.forward_sender_name and not ctx.forward_from and ctx.forward_from_chat and ctx.forward_from_chat.photo:
if (
not ctx.forward_sender_name
and not ctx.forward_from
and ctx.forward_from_chat
and ctx.forward_from_chat.photo
):
return {
"small_file_id": ctx.forward_from_chat.photo.small_file_id,
"small_photo_unique_id": ctx.forward_from_chat.photo.small_photo_unique_id,
"big_file_id": ctx.forward_from_chat.photo.big_file_id,
"big_photo_unique_id": ctx.forward_from_chat.photo.big_photo_unique_id,
}
elif not ctx.forward_sender_name and not ctx.forward_from and ctx.forward_from_chat or ctx.forward_sender_name or not ctx.forward_from:
elif (
not ctx.forward_sender_name
and not ctx.forward_from
and ctx.forward_from_chat
or ctx.forward_sender_name
or not ctx.forward_from
):
return ""
else:
return (
@ -115,7 +153,12 @@ async def get_message_sender_photo(ctx: Message):
"big_file_id": ctx.from_user.photo.big_file_id,
"big_photo_unique_id": ctx.from_user.photo.big_photo_unique_id,
}
elif ctx.from_user or ctx.sender_chat and not ctx.sender_chat.photo or not ctx.sender_chat:
elif (
ctx.from_user
or ctx.sender_chat
and not ctx.sender_chat.photo
or not ctx.sender_chat
):
return ""
else:
return {
@ -172,10 +215,16 @@ async def pyrogram_to_quotly(messages):
the_message_dict_to_append["avatar"] = True
the_message_dict_to_append["from"] = {}
the_message_dict_to_append["from"]["id"] = await get_message_sender_id(message)
the_message_dict_to_append["from"]["name"] = await get_message_sender_name(message)
the_message_dict_to_append["from"]["username"] = await get_message_sender_username(message)
the_message_dict_to_append["from"]["name"] = await get_message_sender_name(
message
)
the_message_dict_to_append["from"][
"username"
] = await get_message_sender_username(message)
the_message_dict_to_append["from"]["type"] = message.chat.type.name.lower()
the_message_dict_to_append["from"]["photo"] = await get_message_sender_photo(message)
the_message_dict_to_append["from"]["photo"] = await get_message_sender_photo(
message
)
if message.reply_to_message:
the_message_dict_to_append["replyMessage"] = {
"name": await get_message_sender_name(message.reply_to_message),
@ -232,7 +281,9 @@ async def msg_quotly_cmd(self: Client, ctx: Message):
except Exception:
return await ctx.reply_msg("🤷🏻‍♂️")
try:
messages_one = await self.get_messages(chat_id=ctx.chat.id, message_ids=ctx.reply_to_message.id, replies=-1)
messages_one = await self.get_messages(
chat_id=ctx.chat.id, message_ids=ctx.reply_to_message.id, replies=-1
)
messages = [messages_one]
except Exception:
return await ctx.reply_msg("🤷🏻‍♂️")

View file

@ -37,11 +37,19 @@ async def cek_mataa(self: Client, ctx: Message, strings):
)
usernamebefore, first_name, lastname_before = await get_userdata(ctx.from_user.id)
msg = ""
if usernamebefore != ctx.from_user.username or first_name != ctx.from_user.first_name or lastname_before != ctx.from_user.last_name:
if (
usernamebefore != ctx.from_user.username
or first_name != ctx.from_user.first_name
or lastname_before != ctx.from_user.last_name
):
msg += f"👀 <b>Mata MissKaty</b>\n\n🌞 User: {ctx.from_user.mention} [<code>{ctx.from_user.id}</code>]\n"
if usernamebefore != ctx.from_user.username:
usernamebefore = f"@{usernamebefore}" if usernamebefore else strings("no_uname")
usernameafter = f"@{ctx.from_user.username}" if ctx.from_user.username else strings("no_uname")
usernameafter = (
f"@{ctx.from_user.username}"
if ctx.from_user.username
else strings("no_uname")
)
msg += strings("uname_change_msg").format(bef=usernamebefore, aft=usernameafter)
await add_userdata(
ctx.from_user.id,
@ -50,7 +58,9 @@ async def cek_mataa(self: Client, ctx: Message, strings):
ctx.from_user.last_name,
)
if first_name != ctx.from_user.first_name:
msg += strings("firstname_change_msg").format(bef=first_name, aft=ctx.from_user.first_name)
msg += strings("firstname_change_msg").format(
bef=first_name, aft=ctx.from_user.first_name
)
await add_userdata(
ctx.from_user.id,
ctx.from_user.username,
@ -60,7 +70,9 @@ async def cek_mataa(self: Client, ctx: Message, strings):
if lastname_before != ctx.from_user.last_name:
lastname_before = lastname_before or strings("no_last_name")
lastname_after = ctx.from_user.last_name or strings("no_last_name")
msg += strings("lastname_change_msg").format(bef=lastname_before, aft=lastname_after)
msg += strings("lastname_change_msg").format(
bef=lastname_before, aft=lastname_after
)
await add_userdata(
ctx.from_user.id,
ctx.from_user.username,
@ -71,13 +83,20 @@ async def cek_mataa(self: Client, ctx: Message, strings):
await ctx.reply_msg(msg, quote=True)
@app.on_message(filters.group & filters.command("sangmata_set", COMMAND_HANDLER) & ~filters.bot & ~filters.via_bot)
@app.on_message(
filters.group
& filters.command("sangmata_set", COMMAND_HANDLER)
& ~filters.bot
& ~filters.via_bot
)
@adminsOnly("can_change_info")
@ratelimiter
@use_chat_lang()
async def set_mataa(self: Client, ctx: Message, strings):
if len(ctx.command) == 1:
return await ctx.reply_msg(strings("set_sangmata_help").format(cmd=ctx.command[0]), del_in=6)
return await ctx.reply_msg(
strings("set_sangmata_help").format(cmd=ctx.command[0]), del_in=6
)
if ctx.command[1] == "on":
cekset = await is_sangmata_on(ctx.chat.id)
if cekset:

View file

@ -36,7 +36,9 @@ async def sed(self: Client, ctx: Message):
return
try:
res = regex.sub(pattern, replace_with, text, count=count, flags=rflags, timeout=1)
res = regex.sub(
pattern, replace_with, text, count=count, flags=rflags, timeout=1
)
except TimeoutError:
return await ctx.reply_msg("Oops, your regex pattern has run for too long.")
except regex.error as e:
@ -49,6 +51,8 @@ async def sed(self: Client, ctx: Message):
reply_to_message_id=ctx.reply_to_message.id,
)
except MessageEmpty:
return await ctx.reply_msg("Please reply message to use this feature.", del_in=5)
return await ctx.reply_msg(
"Please reply message to use this feature.", del_in=5
)
except Exception as e:
return await ctx.reply_msg(f"ERROR: {str(e)}")

View file

@ -47,7 +47,9 @@ buttons_ques = [
],
]
gen_button = [[InlineKeyboardButton(text="🙄 Generate Session 🙄", callback_data="genstring")]]
gen_button = [
[InlineKeyboardButton(text="🙄 Generate Session 🙄", callback_data="genstring")]
]
async def is_batal(msg):
@ -70,34 +72,49 @@ async def is_batal(msg):
return False
@app.on_callback_query(filters.regex(pattern=r"^(genstring|pyrogram|pyrogram_bot|telethon_bot|telethon)$"))
@app.on_callback_query(
filters.regex(pattern=r"^(genstring|pyrogram|pyrogram_bot|telethon_bot|telethon)$")
)
@ratelimiter
async def callbackgenstring(bot, callback_query):
query = callback_query.matches[0].group(1)
if query == "genstring":
await callback_query.answer()
await callback_query.message.reply(ask_ques, reply_markup=InlineKeyboardMarkup(buttons_ques))
await callback_query.message.reply(
ask_ques, reply_markup=InlineKeyboardMarkup(buttons_ques)
)
elif query.startswith("pyrogram") or query.startswith("telethon"):
try:
if query == "pyrogram":
await callback_query.answer()
await generate_session(bot, callback_query.message)
elif query == "pyrogram_bot":
await callback_query.answer("» The session generator will be of Pyrogram v2.", show_alert=True)
await callback_query.answer(
"» The session generator will be of Pyrogram v2.", show_alert=True
)
await generate_session(bot, callback_query.message, is_bot=True)
elif query == "telethon_bot":
await callback_query.answer()
await generate_session(bot, callback_query.message, telethon=True, is_bot=True)
await generate_session(
bot, callback_query.message, telethon=True, is_bot=True
)
elif query == "telethon":
await callback_query.answer()
await generate_session(bot, callback_query.message, telethon=True)
except Exception as e:
LOGGER.error(traceback.format_exc())
ERROR_MESSAGE = "Something went wrong. \n\n**ERROR** : {} " "\n\n**Please forward this message to my Owner**, if this message " "doesn't contain any sensitive data " "because this error is **not logged by bot.** !"
ERROR_MESSAGE = (
"Something went wrong. \n\n**ERROR** : {} "
"\n\n**Please forward this message to my Owner**, if this message "
"doesn't contain any sensitive data "
"because this error is **not logged by bot.** !"
)
await callback_query.message.reply(ERROR_MESSAGE.format(str(e)))
@app.on_message(filters.private & ~filters.forwarded & filters.command("genstring", COMMAND_HANDLER))
@app.on_message(
filters.private & ~filters.forwarded & filters.command("genstring", COMMAND_HANDLER)
)
@ratelimiter
async def genstringg(_, msg):
await msg.reply(ask_ques, reply_markup=InlineKeyboardMarkup(buttons_ques))
@ -127,12 +144,18 @@ async def generate_session(bot, msg, telethon=False, is_bot: bool = False):
quote=True,
reply_markup=InlineKeyboardMarkup(gen_button),
)
api_hash_msg = await msg.chat.ask("» Now please send your **API_HASH** to continue.", filters=filters.text)
api_hash_msg = await msg.chat.ask(
"» Now please send your **API_HASH** to continue.", filters=filters.text
)
if await is_batal(api_hash_msg):
return
api_hash = api_hash_msg.text
await api_hash_msg.delete()
t = "Please send your **BOT_TOKEN** to continue.\nExample : `5432198765:abcdanonymousterabaaplol`'" if is_bot else "» Please send your **PHONE_NUMBER** with country code for which you want generate session. \nᴇxᴀᴍᴩʟᴇ : `+6286356837789`'"
t = (
"Please send your **BOT_TOKEN** to continue.\nExample : `5432198765:abcdanonymousterabaaplol`'"
if is_bot
else "» Please send your **PHONE_NUMBER** with country code for which you want generate session. \nᴇxᴀᴍᴩʟᴇ : `+6286356837789`'"
)
phone_number_msg = await msg.chat.ask(t, filters=filters.text)
if await is_batal(phone_number_msg):
return

View file

@ -43,7 +43,11 @@ __HELP__ = """
def get_emoji_regex():
e_list = [getattr(emoji, e).encode("unicode-escape").decode("ASCII") for e in dir(emoji) if not e.startswith("_")]
e_list = [
getattr(emoji, e).encode("unicode-escape").decode("ASCII")
for e in dir(emoji)
if not e.startswith("_")
]
# to avoid re.error excluding char that start with '*'
e_sort = sorted([x for x in e_list if not x.startswith("*")], reverse=True)
# Sort emojis by length to make sure multi-character emojis are
@ -75,7 +79,9 @@ async def getsticker_(self: Client, ctx: Message, strings):
)
await ctx.reply_to_message.reply_document(
document=sticker_file,
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}",
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}",
)
shutil.rmtree(tempdir, ignore_errors=True)
@ -84,7 +90,11 @@ async def getsticker_(self: Client, ctx: Message, strings):
@ratelimiter
async def getstickerid(self: Client, ctx: Message):
if ctx.reply_to_message.sticker:
await ctx.reply_msg("The ID of this sticker is: <code>{stickerid}</code>".format(stickerid=ctx.reply_to_message.sticker.file_id))
await ctx.reply_msg(
"The ID of this sticker is: <code>{stickerid}</code>".format(
stickerid=ctx.reply_to_message.sticker.file_id
)
)
@app.on_message(filters.command("unkang", COMMAND_HANDLER) & filters.reply)
@ -169,13 +179,22 @@ async def kang_sticker(self: Client, ctx: Message, strings):
pack_prefix = "anim" if animated else "vid" if videos else "a"
packname = f"{pack_prefix}_{ctx.from_user.id}_by_{self.me.username}"
if len(ctx.command) > 1 and ctx.command[1].isdigit() and int(ctx.command[1]) > 0:
if (
len(ctx.command) > 1
and ctx.command[1].isdigit()
and int(ctx.command[1]) > 0
):
# provide pack number to kang in desired pack
packnum = ctx.command.pop(1)
packname = f"{pack_prefix}{packnum}_{ctx.from_user.id}_by_{self.me.username}"
packname = (
f"{pack_prefix}{packnum}_{ctx.from_user.id}_by_{self.me.username}"
)
if len(ctx.command) > 1:
# matches all valid emojis in input
sticker_emoji = "".join(set(EMOJI_PATTERN.findall("".join(ctx.command[1:])))) or sticker_emoji
sticker_emoji = (
"".join(set(EMOJI_PATTERN.findall("".join(ctx.command[1:]))))
or sticker_emoji
)
filename = await self.download_media(ctx.reply_to_message)
if not filename:
# Failed to download
@ -186,7 +205,11 @@ async def kang_sticker(self: Client, ctx: Message, strings):
filename = "sticker.png"
packname = f"c{ctx.from_user.id}_by_{self.me.username}"
img_url = next(
(ctx.text[y.offset : (y.offset + y.length)] for y in ctx.entities if y.type == "url"),
(
ctx.text[y.offset : (y.offset + y.length)]
for y in ctx.entities
if y.type == "url"
),
None,
)
@ -206,7 +229,10 @@ async def kang_sticker(self: Client, ctx: Message, strings):
packnum = ctx.command.pop(2)
packname = f"a{packnum}_{ctx.from_user.id}_by_{self.me.username}"
if len(ctx.command) > 2:
sticker_emoji = "".join(set(EMOJI_PATTERN.findall("".join(ctx.command[2:])))) or sticker_emoji
sticker_emoji = (
"".join(set(EMOJI_PATTERN.findall("".join(ctx.command[2:]))))
or sticker_emoji
)
resize = True
else:
return await prog_msg.edit_msg(strings("kang_help"))
@ -327,7 +353,9 @@ async def kang_sticker(self: Client, ctx: Message, strings):
reply_markup=markup,
)
# Cleanup
await self.delete_messages(chat_id=LOG_CHANNEL, message_ids=msg_.id, revoke=True)
await self.delete_messages(
chat_id=LOG_CHANNEL, message_ids=msg_.id, revoke=True
)
try:
os.remove(filename)
except OSError:

View file

@ -30,7 +30,9 @@ async def getTitleSub(msg, kueri, CurrentPage, user):
sdata = []
scraper = cloudscraper.create_scraper()
param = {"query": kueri}
r = scraper.post("https://subscene.com/subtitles/searchbytitle", data=param).text
r = scraper.post(
"https://subscene.com/subtitles/searchbytitle", data=param
).text
soup = BeautifulSoup(r, "lxml")
lists = soup.find("div", {"class": "search-result"})
entry = lists.find_all("div", {"class": "title"})
@ -51,9 +53,13 @@ async def getTitleSub(msg, kueri, CurrentPage, user):
for c, i in enumerate(SUB_TITLE_DICT[msg.id][0][index], start=1):
subResult += f"<b>{c}. <a href='{i['link']}'>{i['title']}</a></b>\n"
if c < 6:
extractbtn1.append(InlineButton(c, f"sublist#{CurrentPage}#{c}#{msg.id}#{user}"))
extractbtn1.append(
InlineButton(c, f"sublist#{CurrentPage}#{c}#{msg.id}#{user}")
)
else:
extractbtn2.append(InlineButton(c, f"sublist#{CurrentPage}#{c}#{msg.id}#{user}"))
extractbtn2.append(
InlineButton(c, f"sublist#{CurrentPage}#{c}#{msg.id}#{user}")
)
subResult = "".join(i for i in subResult if i not in "[]")
return subResult, PageLen, extractbtn1, extractbtn2
except (IndexError, KeyError):
@ -66,7 +72,9 @@ async def getListSub(msg, link, CurrentPage, user):
if not SUB_DL_DICT.get(msg.id):
sdata = []
scraper = cloudscraper.create_scraper()
kuki = {"LanguageFilter": "13,44,50"} # Only filter language English, Malay, Indonesian
kuki = {
"LanguageFilter": "13,44,50"
} # Only filter language English, Malay, Indonesian
r = scraper.get(link, cookies=kuki).text
soup = BeautifulSoup(r, "lxml")
for i in soup.findAll(class_="a1"):
@ -90,9 +98,13 @@ async def getListSub(msg, link, CurrentPage, user):
for c, i in enumerate(SUB_DL_DICT[msg.id][0][index], start=1):
subResult += f"<b>{c}. {i['title']}</b> [{i['rate']}]\n{i['lang']}\n"
if c < 6:
extractbtn1.append(InlineButton(c, f"extractsubs#{CurrentPage}#{c}#{msg.id}#{user}"))
extractbtn1.append(
InlineButton(c, f"extractsubs#{CurrentPage}#{c}#{msg.id}#{user}")
)
else:
extractbtn2.append(InlineButton(c, f"extractsubs#{CurrentPage}#{c}#{msg.id}#{user}"))
extractbtn2.append(
InlineButton(c, f"extractsubs#{CurrentPage}#{c}#{msg.id}#{user}")
)
subResult = "".join(i for i in subResult if i not in "[]")
return subResult, PageLen, extractbtn1, extractbtn2
except (IndexError, KeyError):
@ -105,10 +117,16 @@ async def getListSub(msg, link, CurrentPage, user):
@ratelimiter
async def subsceneCMD(self: Client, ctx: Message):
if not ctx.input:
return await ctx.reply_msg(f" Please add query after CMD!\nEx: <code>/{ctx.command[0]} Jurassic World</code>")
pesan = await ctx.reply_msg("⏳ Please wait, getting data from subscene..", quote=True)
return await ctx.reply_msg(
f" Please add query after CMD!\nEx: <code>/{ctx.command[0]} Jurassic World</code>"
)
pesan = await ctx.reply_msg(
"⏳ Please wait, getting data from subscene..", quote=True
)
CurrentPage = 1
subres, PageLen, btn1, btn2 = await getTitleSub(pesan, ctx.input, CurrentPage, ctx.from_user.id)
subres, PageLen, btn1, btn2 = await getTitleSub(
pesan, ctx.input, CurrentPage, ctx.from_user.id
)
if not subres:
return
keyboard = InlineKeyboard()
@ -126,7 +144,9 @@ async def subsceneCMD(self: Client, ctx: Message):
# Callback list title
@app.on_callback_query(filters.create(lambda _, __, query: "subscenepage#" in query.data))
@app.on_callback_query(
filters.create(lambda _, __, query: "subscenepage#" in query.data)
)
@ratelimiter
async def subpage_callback(self: Client, callback_query: CallbackQuery):
if callback_query.from_user.id != int(callback_query.data.split("#")[3]):
@ -141,7 +161,9 @@ async def subpage_callback(self: Client, callback_query: CallbackQuery):
return await callback_query.message.delete_msg()
try:
subres, PageLen, btn1, btn2 = await getTitleSub(callback_query.message, kueri, CurrentPage, callback_query.from_user.id)
subres, PageLen, btn1, btn2 = await getTitleSub(
callback_query.message, kueri, CurrentPage, callback_query.from_user.id
)
except TypeError:
return
@ -156,7 +178,9 @@ async def subpage_callback(self: Client, callback_query: CallbackQuery):
if btn2:
keyboard.row(*btn2)
keyboard.row(InlineButton("❌ Close", f"close#{callback_query.from_user.id}"))
await callback_query.message.edit_msg(subres, disable_web_page_preview=True, reply_markup=keyboard)
await callback_query.message.edit_msg(
subres, disable_web_page_preview=True, reply_markup=keyboard
)
# Callback list title
@ -176,7 +200,9 @@ async def subdlpage_callback(self: Client, callback_query: CallbackQuery):
return await callback_query.message.delete_msg()
try:
subres, PageLen, btn1, btn2 = await getListSub(callback_query.message, link, CurrentPage, callback_query.from_user.id)
subres, PageLen, btn1, btn2 = await getListSub(
callback_query.message, link, CurrentPage, callback_query.from_user.id
)
except TypeError:
return
@ -191,11 +217,15 @@ async def subdlpage_callback(self: Client, callback_query: CallbackQuery):
if btn2:
keyboard.row(*btn2)
keyboard.row(InlineButton("❌ Close", f"close#{callback_query.from_user.id}"))
await callback_query.message.edit_msg(subres, disable_web_page_preview=True, reply_markup=keyboard)
await callback_query.message.edit_msg(
subres, disable_web_page_preview=True, reply_markup=keyboard
)
# Callback dl subtitle
@app.on_callback_query(filters.create(lambda _, __, query: "extractsubs#" in query.data))
@app.on_callback_query(
filters.create(lambda _, __, query: "extractsubs#" in query.data)
)
@ratelimiter
async def dlsub_callback(self: Client, callback_query: CallbackQuery):
if callback_query.from_user.id != int(callback_query.data.split("#")[4]):

View file

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

View file

@ -28,7 +28,11 @@ __HELP__ = """
async def take_ss(self: Client, ctx: Message, strings):
if len(ctx.command) == 1:
return await ctx.reply_msg(strings("no_url"), del_in=6)
url = ctx.command[1] if ctx.command[1].startswith("http") else f"https://{ctx.command[1]}"
url = (
ctx.command[1]
if ctx.command[1].startswith("http")
else f"https://{ctx.command[1]}"
)
download_file_path = os.path.join("downloads/", f"webSS_{ctx.from_user.id}.png")
msg = await ctx.reply_msg(strings("wait_str"))
try: