Some Major Change (#50)

* Big Update Coming

* reformating: code

* 'Refactored by Sourcery' (#51)

Co-authored-by: Sourcery AI <>

---------

Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Co-authored-by: methneviebyvaet <77743895+meth1337@users.noreply.github.com>
This commit is contained in:
yasirarism 2023-04-16 11:38:34 +07:00 committed by GitHub
parent 63e76023e0
commit 924ba30a8d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
45 changed files with 1389 additions and 836 deletions

View file

@ -3,7 +3,7 @@ import time
import uvloop
from logging import ERROR, INFO, StreamHandler, basicConfig, getLogger, handlers
import pyromod.listen
from misskaty.core import misskaty_patch
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.jobstores.mongodb import MongoDBJobStore
from pymongo import MongoClient
@ -29,7 +29,6 @@ HELPABLE = {}
cleanmode = {}
botStartTime = time.time()
uvloop.install()
# Pyrogram Bot Client
app = Client(

View file

@ -1,5 +1,4 @@
from pyrogram import filters
from misskaty.core.message_utils import *
import asyncio
data = {}
@ -12,11 +11,9 @@ async def task(msg, warn=False, sec=None):
pass
if warn:
user = msg.from_user
ids = await kirimPesan(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 editPesan(ids, f"Alright {user.mention} [<code>{user.id}</code>], your cooldown is over you can command again.")
await asyncio.sleep(2)
await hapusPesan(ids)
await ids.edit_msg(f"Alright {user.mention} [<code>{user.id}</code>], your cooldown is over you can command again.", del_in=3)
def wait(sec):

View file

@ -0,0 +1 @@
from . import bound, methods, listen

View file

@ -0,0 +1 @@
from .message import Message

View file

@ -0,0 +1,280 @@
import io
import html
from logging import getLogger
from pyrogram.types import Message
from pyrogram.errors import MessageNotModified, MessageAuthorRequired, MessageIdInvalid, ChatWriteForbidden, ChatAdminRequired, FloodWait, MessageTooLong, MessageDeleteForbidden
from asyncio import sleep as asleep, get_event_loop
from typing import Union
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)
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:
text (``str``):
Text of the message to be sent.
del_in (``int``):
Time in Seconds for delete that message.
quote (``bool``, *optional*):
If ``True``, the message will be sent as
a reply to this message.
If *reply_to_message_id* is passed,
this parameter will be ignored.
Defaults to ``True`` in group chats
and ``False`` in private chats.
parse_mode (:obj:`enums.ParseMode`, *optional*):
By default, texts are parsed using both
Markdown and HTML styles.
You can combine both syntaxes together.
Pass "markdown" or "md" to enable
Markdown-style parsing only.
Pass "html" to enable HTML-style parsing only.
Pass None to completely disable style parsing.
disable_web_page_preview (``bool``, *optional*):
Disables link previews for links in this message.
disable_notification (``bool``, *optional*):
Sends the message silently.
Users will receive a notification with no sound.
reply_to_message_id (``int``, *optional*):
If the message is a reply, ID of the original message.
schedule_date (:py:obj:`~datetime.datetime`, *optional*):
Date when the message will be automatically sent. Unix time.
protect_content (``bool``, *optional*):
Protects the contents of the sent message from forwarding and saving.
reply_markup (:obj:`InlineKeyboardMarkup`
| :obj:`ReplyKeyboardMarkup` | :obj:`ReplyKeyboardRemove`
| :obj:`ForceReply`, *optional*):
Additional interface options. An object for an inline keyboard,
custom reply keyboard,
instructions to remove reply keyboard or to
force a reply from the user.
Returns:
On success, the sent Message or True is returned.
Raises:
RPCError: In case of a Telegram RPC error.
"""
try:
if as_raw:
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:
return msg
await asleep(del_in)
return bool(await msg.delete())
except FloodWait as e:
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.")
return await self.chat.leave()
async def edit_text(self, text: str, del_in: int = 0, *args, **kwargs) -> Union["Message", bool]:
"""\nExample:
message.edit_msg("hello")
Parameters:
text (``str``):
New text of the message.
del_in (``int``):
Time in Seconds for delete that message.
parse_mode (:obj:`enums.ParseMode`, *optional*):
By default, texts are parsed using
both Markdown and HTML styles.
You can combine both syntaxes together.
Pass "markdown" or "md" to enable
Markdown-style parsing only.
Pass "html" to enable HTML-style parsing only.
Pass None to completely disable style parsing.
disable_web_page_preview (``bool``, *optional*):
Disables link previews for links in this message.
reply_markup (:obj:`InlineKeyboardMarkup`, *optional*):
An InlineKeyboardMarkup object.
Returns:
On success, the edited
:obj:`Message` or True is returned.
Raises:
RPCError: In case of a Telegram RPC error.
"""
try:
msg = await self.edit_text(text, *args, **kwargs)
if del_in == 0:
return msg
await asleep(del_in)
return bool(await msg.delete())
except FloodWait as e:
LOGGER.warning(str(e))
await asleep(e.value)
return await edit_text(self, text, *args, **kwargs)
except MessageNotModified:
return False
except (ChatWriteForbidden, ChatAdminRequired):
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(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]:
"""\nThis will first try to message.edit.
If it raises MessageTooLong error,
run message.send_as_file.
Example:
message.edit_or_send_as_file("some huge text")
Parameters:
text (``str``):
New text of the message.
del_in (``int``):
Time in Seconds for delete that message.
log (``bool`` | ``str``, *optional*):
If ``True``, the message will be forwarded
to the log channel.
If ``str``, the logger name will be updated.
sudo (``bool``, *optional*):
If ``True``, sudo users supported.
as_raw (``bool``, *optional*):
If ``False``, the message will be escaped with current parse mode.
default to ``False``.
parse_mode (:obj:`enums.ParseMode`, *optional*):
By default, texts are parsed using both
Markdown and HTML styles.
You can combine both syntaxes together.
Pass "markdown" or "md" to enable
Markdown-style parsing only.
Pass "html" to enable HTML-style parsing only.
Pass None to completely disable style parsing.
disable_web_page_preview (``bool``, *optional*):
Disables link previews for links in this message.
reply_markup (:obj:`InlineKeyboardMarkup`, *optional*):
An InlineKeyboardMarkup object.
**kwargs (for message.send_as_file)
Returns:
On success, the edited
:obj:`Message` or True is returned.
Raises:
RPCError: In case of a Telegram RPC error.
"""
text = html.escape(text.html) if as_raw else text
try:
msg = await edit_text(self, text=text, *args, **kwargs)
if del_in == 0:
return msg
await asleep(del_in)
return bool(await msg.delete())
except (MessageTooLong, OSError):
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 = -1, *args, **kwargs) -> Union["Message", bool]:
"""\nThis will first try to message.reply.
If it raise MessageTooLong error,
run message.send_as_file.
Example:
message.reply_or_send_as_file("some huge text")
Parameters:
text (``str``):
Text of the message to be sent.
del_in (``int``):
Time in Seconds for delete that message.
quote (``bool``, *optional*):
If ``True``, the message will be sent
as a reply to this message.
If *reply_to_message_id* is passed,
this parameter will be ignored.
Defaults to ``True`` in group chats
and ``False`` in private chats.
parse_mode (:obj:`enums.ParseMode`, *optional*):
By default, texts are parsed using
both Markdown and HTML styles.
You can combine both syntaxes together.
Pass "markdown" or "md" to enable
Markdown-style parsing only.
Pass "html" to enable HTML-style parsing only.
Pass None to completely disable style parsing.
disable_web_page_preview (``bool``, *optional*):
Disables link previews for links in this message.
disable_notification (``bool``, *optional*):
Sends the message silently.
Users will receive a notification with no sound.
reply_to_message_id (``int``, *optional*):
If the message is a reply, ID of the
original message.
reply_markup (:obj:`InlineKeyboardMarkup`
| :obj:`ReplyKeyboardMarkup` | :obj:`ReplyKeyboardRemove`
| :obj:`ForceReply`, *optional*):
Additional interface options. An object for an
inline keyboard, custom reply keyboard,
instructions to remove reply keyboard
or to force a reply from the user.
**kwargs (for message.send_as_file)
Returns:
On success, the sent Message or True is returned.
Raises:
RPCError: In case of a Telegram RPC error.
"""
text = html.escape(text.html) if as_raw else text
try:
return await reply_text(self, text=text, del_in=del_in, *args, **kwargs)
except MessageTooLong:
return await reply_as_file(self, text=text, **kwargs)
async def reply_as_file(self, text: str, filename: str = "output.txt", caption: str = "", delete_message: bool = True):
"""\nYou can send large outputs as file
Example:
message.reply_as_file(text="hello")
Parameters:
text (``str``):
Text of the message to be sent.
filename (``str``, *optional*):
file_name for output file.
caption (``str``, *optional*):
caption for output file.
delete_message (``bool``, *optional*):
If ``True``, the message will be deleted
after sending the file.
Returns:
On success, the sent Message is returned.
"""
reply_to_id = self.reply_to_message.id if self.reply_to_message else self.id
if delete_message:
get_event_loop().create_task(self.delete())
doc = io.BytesIO(text.encode())
doc.name = filename
return await self.reply_document(document=doc, caption=caption[:1024], disable_notification=True, reply_to_message_id=reply_to_id)
async def delete(self, revoke: bool = True) -> bool:
"""\nThis will first try to delete and ignore
it if it raises MessageDeleteForbidden
Parameters:
revoke (``bool``, *optional*):
Deletes messages on both parts.
This is only for private cloud chats and normal groups, messages on
channels and supergroups are always revoked (i.e.: deleted for everyone).
Defaults to True.
Returns:
True on success, False otherwise.
"""
try:
return bool(await self.delete(revoke=revoke))
except FloodWait as e:
LOGGER.warning(str(e))
await asleep(e.value)
return await delete(self, revoke)
except MessageDeleteForbidden:
return False
except Exception as e:
LOGGER.warning(str(e))
Message.reply_msg = reply_text
Message.edit_msg = edit_text
Message.edit_or_send_as_file = edit_or_send_as_file
Message.reply_or_send_as_file = reply_or_send_as_file
Message.reply_as_file = reply_as_file
Message.delete_msg = delete

View file

@ -0,0 +1 @@
from .listen import Client, MessageHandler, Chat, User

View file

@ -0,0 +1,133 @@
"""
pyromod - A monkeypatcher add-on for Pyrogram
Copyright (C) 2020 Cezar H. <https://github.com/usernein>
This file is part of pyromod.
pyromod is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pyromod is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with pyromod. If not, see <https://www.gnu.org/licenses/>.
"""
import asyncio
import functools
import pyrogram
from ..utils import patch, patchable
loop = asyncio.get_event_loop()
class ListenerCanceled(Exception):
pass
pyrogram.errors.ListenerCanceled = ListenerCanceled
@patch(pyrogram.client.Client)
class Client:
@patchable
def __init__(self, *args, **kwargs):
self.listening = {}
self.using_mod = True
self.old__init__(*args, **kwargs)
@patchable
async def listen(self, chat_id, filters=None, timeout=None):
if type(chat_id) != int:
chat = await self.get_chat(chat_id)
chat_id = chat.id
future = loop.create_future()
future.add_done_callback(functools.partial(self.clear_listener, chat_id))
self.listening.update({chat_id: {"future": future, "filters": filters}})
return await asyncio.wait_for(future, timeout)
@patchable
async def ask(self, chat_id, text, filters=None, timeout=None, *args, **kwargs):
request = await self.send_message(chat_id, text, *args, **kwargs)
response = await self.listen(chat_id, filters, timeout)
response.request = request
return response
@patchable
def clear_listener(self, chat_id, future):
if future == self.listening[chat_id]["future"]:
self.listening.pop(chat_id, None)
@patchable
def cancel_listener(self, chat_id):
listener = self.listening.get(chat_id)
if not listener or listener["future"].done():
return
listener["future"].set_exception(ListenerCanceled())
self.clear_listener(chat_id, listener["future"])
@patch(pyrogram.handlers.message_handler.MessageHandler)
class MessageHandler:
@patchable
def __init__(self, callback: callable, filters=None):
self.user_callback = callback
self.old__init__(self.resolve_listener, filters)
@patchable
async def resolve_listener(self, client, message, *args):
listener = client.listening.get(message.chat.id)
if listener and not listener["future"].done():
listener["future"].set_result(message)
else:
if listener and listener["future"].done():
client.clear_listener(message.chat.id, listener["future"])
await self.user_callback(client, message, *args)
@patchable
async def check(self, client, update):
listener = client.listening.get(update.chat.id)
if listener and not listener["future"].done():
return await listener["filters"](client, update) if callable(listener["filters"]) else True
return await self.filters(client, update) if callable(self.filters) else True
@patch(pyrogram.types.user_and_chats.chat.Chat)
class Chat(pyrogram.types.Chat):
@patchable
def listen(self, *args, **kwargs):
return self._client.listen(self.id, *args, **kwargs)
@patchable
def ask(self, *args, **kwargs):
return self._client.ask(self.id, *args, **kwargs)
@patchable
def cancel_listener(self):
return self._client.cancel_listener(self.id)
@patch(pyrogram.types.user_and_chats.user.User)
class User(pyrogram.types.User):
@patchable
def listen(self, *args, **kwargs):
return self._client.listen(self.id, *args, **kwargs)
@patchable
def ask(self, *args, **kwargs):
return self._client.ask(self.id, *args, **kwargs)
@patchable
def cancel_listener(self):
return self._client.cancel_listener(self.id)

View file

@ -0,0 +1,3 @@
from .send_message import send_message
from .edit_message_text import edit_message_text
from .send_as_file import send_as_file

View file

@ -0,0 +1,51 @@
from typing import Union
import asyncio
from pyrogram import Client
from pyrogram.types import Message
async def edit_message_text(self, chat_id: Union[int, str], message_id: int, text: str, del_in: int = 0, *args, **kwargs) -> Union["Message", bool]:
"""\nExample:
message.edit_text("hello")
Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages)
you can simply use "me" or "self".
For a contact that exists in your Telegram address book
you can use his phone number (str).
message_id (``int``):
Message identifier in the chat specified in chat_id.
text (``str``):
New text of the message.
del_in (``int``):
Time in Seconds for delete that message.
parse_mode (:obj:`enums.ParseMode`, *optional*):
By default, texts are parsed using
both Markdown and HTML styles.
You can combine both syntaxes together.
Pass "markdown" or "md" to enable
Markdown-style parsing only.
Pass "html" to enable HTML-style parsing only.
Pass None to completely disable style parsing.
entities (List of :obj:`~pyrogram.types.MessageEntity`):
List of special entities that appear in message text,
which can be specified instead of *parse_mode*.
disable_web_page_preview (``bool``, *optional*):
Disables link previews for links in this message.
reply_markup (:obj:`InlineKeyboardMarkup`, *optional*):
An InlineKeyboardMarkup object.
Returns:
On success, the edited
:obj:`Message` or True is returned.
Raises:
RPCError: In case of a Telegram RPC error.
"""
msg = await self.edit_message_text(chat_id=chat_id, message_id=message_id, text=text, *args, **kwargs)
if del_in == 0:
return msg
await asyncio.sleep(del_in)
return bool(await msg.delete())
Client.edit_msg_text = edit_message_text

View file

@ -0,0 +1,39 @@
import io
from typing import Union, Optional
from pyrogram.types import Message
from pyrogram import Client
async def send_as_file(self, chat_id: Union[int, str], text: str, filename: str = "output.txt", caption: str = "", log: Union[bool, str] = False, reply_to_message_id: Optional[int] = None) -> "Message":
"""\nYou can send large outputs as file
Example:
@userge.send_as_file(chat_id=12345, text="hello")
Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages)
you can simply use "me" or "self".
For a contact that exists in your Telegram address book
you can use his phone number (str).
text (``str``):
Text of the message to be sent.
filename (``str``, *optional*):
file_name for output file.
caption (``str``, *optional*):
caption for output file.
log (``bool`` | ``str``, *optional*):
If ``True``, the message will be forwarded
to the log channel.
If ``str``, the logger name will be updated.
reply_to_message_id (``int``, *optional*):
If the message is a reply, ID of the original message.
Returns:
On success, the sent Message is returned.
"""
doc = io.BytesIO(text.encode())
doc.name = filename
return await self.send_document(chat_id=chat_id, document=doc, caption=caption[:1024], disable_notification=True, reply_to_message_id=reply_to_message_id)
Client.send_as_file = send_as_file

View file

@ -0,0 +1,61 @@
from typing import Union
from pyrogram.types import Message
from pyrogram import Client
import asyncio
async def send_message(self, chat_id: Union[int, str], text: str, del_in: int = 0, *args, **kwargs) -> Union["Message", bool]:
"""\nSend text messages.
Example:
@userge.send_message(chat_id=12345, text='test')
Parameters:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages)
you can simply use "me" or "self".
For a contact that exists in your Telegram address book
you can use his phone number (str).
text (``str``):
Text of the message to be sent.
del_in (``int``):
Time in Seconds for delete that message.
log (``bool`` | ``str``, *optional*):
If ``True``, the message will be forwarded to the log channel.
If ``str``, the logger name will be updated.
parse_mode (:obj:`enums.ParseMode`, *optional*):
By default, texts are parsed using both Markdown and HTML styles.
You can combine both syntaxes together.
Pass "markdown" or "md" to enable Markdown-style parsing only.
Pass "html" to enable HTML-style parsing only.
Pass None to completely disable style parsing.
entities (List of :obj:`~pyrogram.types.MessageEntity`):
List of special entities that appear in message text,
which can be specified instead of *parse_mode*.
disable_web_page_preview (``bool``, *optional*):
Disables link previews for links in this message.
disable_notification (``bool``, *optional*):
Sends the message silently.
Users will receive a notification with no sound.
reply_to_message_id (``int``, *optional*):
If the message is a reply, ID of the original message.
schedule_date (:py:obj:`~datetime.datetime`, *optional*):
Date when the message will be automatically sent. Unix time.
protect_content (``bool``, *optional*):
Protects the contents of the sent message from forwarding and saving.
reply_markup (:obj:`InlineKeyboardMarkup` | :obj:`ReplyKeyboardMarkup`
| :obj:`ReplyKeyboardRemove` | :obj:`ForceReply`, *optional*):
Additional interface options. An object for an inline keyboard,
custom reply keyboard, instructions to remove
reply keyboard or to force a reply from the user.
Returns:
:obj:`Message`: On success, the sent text message or True is returned.
"""
msg = await self.send_message(chat_id=chat_id, text=text, *args, **kwargs)
if del_in == 0:
return msg
if del_in > 0:
await asyncio.sleep(del_in)
return bool(await msg.delete())
Client.send_msg = send_message

View file

@ -0,0 +1 @@
from .utils import patch, patchable

View file

@ -0,0 +1,38 @@
"""
pyromod - A monkeypatcher add-on for Pyrogram
Copyright (C) 2020 Cezar H. <https://github.com/usernein>
This file is part of pyromod.
pyromod is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pyromod is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with pyromod. If not, see <https://www.gnu.org/licenses/>.
"""
def patch(obj):
def is_patchable(item):
return getattr(item[1], "patchable", False)
def wrapper(container):
for name, func in filter(is_patchable, container.__dict__.items()):
old = getattr(obj, name, None)
setattr(obj, f"old{name}", old)
setattr(obj, name, func)
return container
return wrapper
def patchable(func):
func.patchable = True
return func

View file

@ -5,13 +5,12 @@ import shlex
import time
import traceback
import uuid
import asyncio
from pathlib import Path
from pyrogram import enums
from pyrogram.types import InlineKeyboardButton, InputMediaPhoto
from misskaty.core.message_utils import *
async def run_subprocess(cmd):
process = await asyncio.create_subprocess_shell(cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
@ -60,7 +59,7 @@ async def screenshot_flink(c, m):
media_msg = m.message.reply_to_message
# print(media_msg)
if media_msg.empty:
await editPesan(m.message, "Why did you delete the file 😠, Now i cannot help you 😒.")
await m.message.edit_msg("Why did you delete the file 😠, Now i cannot help you 😒.")
# c.CURRENT_PROCESSES[chat_id] -= 1
return
@ -72,15 +71,13 @@ async def screenshot_flink(c, m):
try:
start_time = time.time()
await editPesan(m.message, "Give me some time bruh!! 😴")
await m.message.edit_msg("Give me some time bruh!! 😴")
await editPesan(m.message, "😀 Taking Snaps!")
await m.message.edit_msg("😀 Taking Snaps!")
file_link = m.message.reply_to_message.command[1]
duration = await get_duration(file_link)
if isinstance(duration, str):
await editPesan(m.message, "Oops, What's that? Couldn't Open the file😟.")
# c.CURRENT_PROCESSES[chat_id] -= 1
return
return await m.message.edit_msg("Oops, What's that? Couldn't Open the file😟.")
reduced_sec = duration - int(duration * 2 / 100)
print(f"Total seconds: {duration}, Reduced seconds: {reduced_sec}")
@ -92,32 +89,26 @@ async def screenshot_flink(c, m):
for i, sec in enumerate(screenshot_secs):
thumbnail_template = output_folder.joinpath(f"{i+1}.png")
# print(sec)
ffmpeg_cmd = f"mediaextract -hide_banner -ss {sec} -i {shlex.quote(file_link)} -vframes 1 '{thumbnail_template}'"
output = await run_subprocess(ffmpeg_cmd)
await editPesan(m.message, f"😀 `{i+1}` of `{num_screenshots}` generated!")
await m.message.edit_msg(f"😀 `{i+1}` of `{num_screenshots}` generated!")
if thumbnail_template.exists():
screenshots.append(InputMediaPhoto(str(thumbnail_template), caption=f"ScreenShot at {datetime.timedelta(seconds=sec)}"))
continue
ffmpeg_errors += output[1].decode() + "\n\n"
# print(screenshots)
if not screenshots:
await editPesan(m.message, "😟 Sorry! Screenshot generation failed possibly due to some infrastructure failure 😥.")
# c.CURRENT_PROCESSES[chat_id] -= 1
return
return await m.message.edit_msg("😟 Sorry! Screenshot generation failed possibly due to some infrastructure failure 😥.")
await editPesan(m.message, "🤓 Its done , Now starting to upload!")
await m.message.edit_msg("🤓 Its done , Now starting to upload!")
await media_msg.reply_chat_action(enums.ChatAction.UPLOAD_PHOTO)
await media_msg.reply_media_group(screenshots, True)
await editPesan(m.message, f"Completed in {datetime.timedelta(seconds=int(time.time()-start_time))}\n\nJoin @YasirPediaChannel\n\n©️ https://yasirpedia.eu.org")
# c.CURRENT_PROCESSES[chat_id] -= 1
await m.message.edit_msg(f"Completed in {datetime.timedelta(seconds=int(time.time()-start_time))}\n\nJoin @YasirPediaChannel\n\n©️ https://yasirpedia.eu.org")
except:
traceback.print_exc()
await editPesan(m.message, "😟 Sorry! Screenshot generation failed, ERR: {aa} 😥.")
# c.CURRENT_PROCESSES[chat_id] -= 1
await m.message.edit_msg("😟 Sorry! Screenshot generation failed, ERR: {aa} 😥.")
def gen_ik_buttons():

View file

@ -3,9 +3,9 @@ import re
from logging import getLogger
from time import time
from pyrogram import enums, filters
from pyrogram import enums, filters, Client
from pyrogram.errors import ChatAdminRequired, FloodWait
from pyrogram.types import ChatPermissions, ChatPrivileges
from pyrogram.types import ChatPermissions, ChatPrivileges, Message
from database.warn_db import add_warn, get_warn, remove_warns
from misskaty import app
@ -19,7 +19,6 @@ from misskaty.core.decorator.permissions import (
)
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.core.keyboard import ikb
from misskaty.core.message_utils import kirimPesan
from misskaty.helper.localization import use_chat_lang
from misskaty.helper.functions import (
extract_user,
@ -79,24 +78,24 @@ async def admin_cache_func(_, cmu):
@require_admin(permissions=["can_delete_messages"], allow_in_private=True)
@ratelimiter
@use_chat_lang()
async def purge(_, message, strings):
if not message.from_user:
async def purge(self: Client, ctx: Message, strings) -> "Message":
if not ctx.from_user:
return
try:
repliedmsg = message.reply_to_message
await message.delete()
repliedmsg = ctx.reply_to_message
await ctx.delete_msg()
if not repliedmsg:
return await message.reply_text(strings("purge_no_reply"))
return await ctx.reply_msg(strings("purge_no_reply"))
cmd = message.command
cmd = ctx.command
if len(cmd) > 1 and cmd[1].isdigit():
purge_to = repliedmsg.id + int(cmd[1])
purge_to = min(purge_to, message.id)
purge_to = min(purge_to, ctx.id)
else:
purge_to = message.id
purge_to = ctx.id
chat_id = message.chat.id
chat_id = ctx.chat.id
message_ids = []
del_total = 0
@ -125,9 +124,9 @@ async def purge(_, message, strings):
revoke=True,
)
del_total += len(message_ids)
await kirimPesan(message, strings("purge_success").format(del_total=del_total))
await ctx.reply_msg(strings("purge_success").format(del_total=del_total))
except Exception as err:
await kirimPesan(message, f"ERROR: {err}")
await ctx.reply_msg(f"ERROR: {err}")
# Kick members
@ -135,29 +134,29 @@ async def purge(_, message, strings):
@adminsOnly("can_restrict_members")
@ratelimiter
@use_chat_lang()
async def kickFunc(client, message, strings):
if not message.from_user:
async def kickFunc(client: Client, ctx: Message, strings) -> "Message":
if not ctx.from_user:
return
user_id, reason = await extract_user_and_reason(message)
user_id, reason = await extract_user_and_reason(ctx)
if not user_id:
return await kirimPesan(message, strings("user_not_found"))
return await ctx.reply_msg(strings("user_not_found"))
if user_id == client.me.id:
return await kirimPesan(message, strings("kick_self_err"))
return await ctx.reply_msg(strings("kick_self_err"))
if user_id in SUDO:
return await kirimPesan(message, strings("kick_sudo_err"))
if user_id in (await list_admins(message.chat.id)):
return await kirimPesan(message, strings("kick_admin_err"))
return await ctx.reply_msg(strings("kick_sudo_err"))
if user_id in (await list_admins(ctx.chat.id)):
return await ctx.reply_msg(strings("kick_admin_err"))
user = await app.get_users(user_id)
msg = strings("kick_msg").format(mention=user.mention, id=user.id, kicker=message.from_user.mention if message.from_user else "Anon Admin", reasonmsg=reason or "-")
if message.command[0][0] == "d":
await message.reply_to_message.delete()
msg = strings("kick_msg").format(mention=user.mention, id=user.id, kicker=ctx.from_user.mention if ctx.from_user else "Anon Admin", reasonmsg=reason or "-")
if ctx.command[0][0] == "d":
await ctx.reply_to_message.delete_msg()
try:
await message.chat.ban_member(user_id)
await kirimPesan(message, msg)
await ctx.chat.ban_member(user_id)
await ctx.reply_msg(msg)
await asyncio.sleep(1)
await message.chat.unban_member(user_id)
await ctx.chat.unban_member(user_id)
except ChatAdminRequired:
await kirimPesan(message, strings("no_ban_permission"))
await ctx.reply_msg(strings("no_ban_permission"))
# Ban/DBan/TBan User
@ -677,28 +676,28 @@ async def check_warns(_, message, strings):
@capture_err
@ratelimiter
@use_chat_lang()
async def report_user(_, message, strings):
if not message.reply_to_message:
return await message.reply_text(strings("report_no_reply"))
reply = message.reply_to_message
async def report_user(self: Client, ctx: Message, strings) -> "Message":
if not ctx.reply_to_message:
return await ctx.reply_text(strings("report_no_reply"))
reply = ctx.reply_to_message
reply_id = reply.from_user.id if reply.from_user else reply.sender_chat.id
user_id = message.from_user.id if message.from_user else message.sender_chat.id
user_id = ctx.from_user.id if ctx.from_user else ctx.sender_chat.id
if reply_id == user_id:
return await message.reply_text(strings("report_self_err"))
return await ctx.reply_text(strings("report_self_err"))
list_of_admins = await list_admins(message.chat.id)
linked_chat = (await app.get_chat(message.chat.id)).linked_chat
list_of_admins = await list_admins(ctx.chat.id)
linked_chat = (await app.get_chat(ctx.chat.id)).linked_chat
if linked_chat is None:
if reply_id in list_of_admins or reply_id == message.chat.id:
return await message.reply_text(strings("reported_is_admin"))
elif reply_id in list_of_admins or reply_id == message.chat.id or reply_id == linked_chat.id:
return await message.reply_text(strings("reported_is_admin"))
if reply_id in list_of_admins or reply_id == ctx.chat.id:
return await ctx.reply_text(strings("reported_is_admin"))
elif reply_id in list_of_admins or reply_id == ctx.chat.id or reply_id == linked_chat.id:
return await ctx.reply_text(strings("reported_is_admin"))
user_mention = reply.from_user.mention if reply.from_user else reply.sender_chat.title
text = strings("report_msg").format(user_mention=user_mention)
admin_data = [m async for m in app.get_chat_members(message.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS)]
admin_data = [m async for m in app.get_chat_members(ctx.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS)]
for admin in admin_data:
if admin.user.is_bot or admin.user.is_deleted:
# return bots or deleted admins
continue
text += f"<a href='tg://user?id={admin.user.id}>\u2063</a>"
await kirimPesan(message.reply_to_message, text)
await ctx.reply_msg(text, reply_to_message_id=ctx.reply_to_message.id)

View file

@ -12,14 +12,15 @@
import time
import re
from pyrogram import filters, enums
from pyrogram import filters, enums, Client
from pyrogram.types import Message
from database.afk_db import add_afk, cleanmode_off, cleanmode_on, is_afk, remove_afk
from misskaty import app
from misskaty.core.decorator.errors import capture_err
from misskaty.core.decorator.permissions import adminsOnly
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.core.message_utils import kirimPesan
from misskaty.core.misskaty_patch.bound import message
from misskaty.helper import get_readable_time2
from misskaty.helper.localization import use_chat_lang
from misskaty.vars import COMMAND_HANDLER
@ -37,9 +38,9 @@ Just type something in group to remove AFK Status."""
@app.on_message(filters.command(["afk"], COMMAND_HANDLER))
@ratelimiter
@use_chat_lang()
async def active_afk(_, message, strings):
async def active_afk(self: Client, ctx: Message, strings):
if message.sender_chat:
return await kirimPesan(message, strings("no_channel"))
return await ctx.reply_msg(strings("no_channel"), del_in=6)
user_id = message.from_user.id
verifier, reasondb = await is_afk(user_id)
if verifier:
@ -182,7 +183,7 @@ async def active_afk(_, message, strings):
}
await add_afk(user_id, details)
send = await kirimPesan(message, strings("now_afk").format(usr=message.from_user.mention, id=message.from_user.id))
send = await ctx.reply_msg(strings("now_afk").format(usr=message.from_user.mention, id=message.from_user.id))
await put_cleanmode(message.chat.id, send.id)
@ -190,22 +191,22 @@ async def active_afk(_, message, strings):
@ratelimiter
@adminsOnly("can_change_info")
@use_chat_lang()
async def afk_state(_, message, strings):
async def afk_state(self: Client, ctx: Message, strings):
if not message.from_user:
return
if len(message.command) == 1:
return await kirimPesan(message, strings("afkdel_help").format(cmd=message.command[0]))
return await ctx.reply_msg(strings("afkdel_help").format(cmd=message.command[0]), del_in=6)
chat_id = message.chat.id
state = message.text.split(None, 1)[1].strip()
state = state.lower()
if state == "enable":
await cleanmode_on(chat_id)
await kirimPesan(message, strings("afkdel_enable"))
await ctx.reply_msg(strings("afkdel_enable"))
elif state == "disable":
await cleanmode_off(chat_id)
await kirimPesan(message, strings("afkdel_disable"))
await ctx.reply_msg(strings("afkdel_disable"))
else:
await kirimPesan(message, strings("afkdel_help").format(cmd=message.command[0]))
await ctx.reply_msg(strings("afkdel_help").format(cmd=message.command[0]), del_in=6)
# Detect user that AFK based on Yukki Repo
@ -214,13 +215,13 @@ async def afk_state(_, message, strings):
group=1,
)
@use_chat_lang()
async def chat_watcher_func(client, message, strings):
async def chat_watcher_func(self: Client, ctx: Message, strings):
if message.sender_chat:
return
userid = message.from_user.id
user_name = message.from_user.mention
if message.entities:
possible = ["/afk", f"/afk@{client.me.username}", "!afk"]
possible = ["/afk", f"/afk@{self.me.username}", "!afk"]
message_text = message.text or message.caption
for entity in message.entities:
if entity.type == enums.MessageEntityType.BOT_COMMAND:

View file

@ -1,9 +1,8 @@
from pyrogram import filters
from pyrogram import filters, Client
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from database.users_chats_db import db
from misskaty import app
from misskaty.core.message_utils import kirimPesan
from misskaty.vars import SUPPORT_CHAT
from utils import temp
@ -23,18 +22,17 @@ disabled_group = filters.create(disabled_chat)
@app.on_message(filters.private & banned_user & filters.incoming)
async def ban_reply(bot, message):
async def ban_reply(self: Client, ctx: Message):
ban = await db.get_ban_status(message.from_user.id)
await kirimPesan(message, f'Sorry Dude, You are Banned to use Me. \nBan Reason: {ban["ban_reason"]}')
await ctx.reply_msg(f'Sorry Dude, You are Banned to use Me. \nBan Reason: {ban["ban_reason"]}')
@app.on_message(filters.group & disabled_group & filters.incoming)
async def grp_bd(bot, message):
async def grp_bd(self: Client, ctx: Message):
buttons = [[InlineKeyboardButton("Support", url=f"https://t.me/{SUPPORT_CHAT}")]]
reply_markup = InlineKeyboardMarkup(buttons)
vazha = await db.get_chat(message.chat.id)
k = await kirimPesan(
message,
vazha = await db.get_chat(ctx.chat.id)
k = await ctx.reply_msg(
f"CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..\nReason : <code>{vazha['reason']}</code>.",
reply_markup=reply_markup,
)
@ -42,4 +40,4 @@ async def grp_bd(bot, message):
await k.pin()
except:
pass
await bot.leave_chat(message.chat.id)
await self.leave_chat(message.chat.id)

View file

@ -2,20 +2,20 @@ import asyncio
import datetime
import time
from pyrogram import filters
from pyrogram import filters, Client
from pyrogram.types import Message
from database.users_chats_db import db
from misskaty import app
from misskaty.core.message_utils import *
from misskaty.vars import SUDO
from utils import broadcast_messages
@app.on_message(filters.command("broadcast") & filters.user(SUDO) & filters.reply)
async def broadcast(bot, message):
async def broadcast(self: Client, ctx: Message):
users = await db.get_all_users()
b_msg = message.reply_to_message
sts = await kirimPesan(message, "Broadcasting your messages...")
b_msg = ctx.reply_to_message
sts = await ctx.reply_msg("Broadcasting your messages...")
start_time = time.time()
total_users = await db.total_users_count()
done = 0
@ -38,6 +38,6 @@ async def broadcast(bot, message):
done += 1
await asyncio.sleep(2)
if not done % 20:
await editPesan(sts, 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 editPesan(sts, 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

@ -10,12 +10,11 @@ import urllib.parse
from urllib.parse import unquote
import requests
from pyrogram import filters
from pyrogram import filters, Client
from pyrogram.errors import EntitiesTooLong, MessageTooLong
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from misskaty import app
from misskaty.core.message_utils import *
from misskaty.core.decorator.errors import capture_err
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.helper import http, get_readable_file_size, rentry
@ -91,17 +90,17 @@ def wetransfer_bypass(url: str) -> str:
@app.on_message(filters.command(["directurl"], COMMAND_HANDLER))
@capture_err
@ratelimiter
async def bypass(_, message):
if len(message.command) == 1:
return await kirimPesan(message, f"Gunakan perintah /{message.command[0]} untuk bypass url")
url = message.command[1]
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)
url = ctx.command[1]
urllib.parse.urlparse(url).netloc
msg = await kirimPesan(message, "Bypassing URL..", quote=True)
mention = f"**Bypasser:** {message.from_user.mention} ({message.from_user.id})"
msg = await ctx.reply_msg("Bypassing URL..", quote=True)
mention = f"**Bypasser:** {ctx.from_user.mention} ({ctx.from_user.id})"
if re.match(r"https?://(store.kde.org|www.pling.com)\/p\/(\d+)", url):
data = await pling_bypass(url)
try:
await editPesan(msg, f"{data}\n\n{mention}")
await msg.edit_msg(f"{data}\n\n{mention}")
except (MessageTooLong, EntitiesTooLong):
result = await rentry(data)
markup = InlineKeyboardMarkup(
@ -112,14 +111,11 @@ async def bypass(_, message):
]
]
)
await editPesan(
msg,
await msg.edit_msg(
f"{result}\n\nBecause your bypassed url is too long, so your link will be pasted to rentry.\n{mention}",
reply_markup=markup,
disable_web_page_preview=True,
)
elif "we.tl" or "wetransfer.com" in message.command[1]:
data = wetransfer_bypass(url)
await editPesan(msg, f"{data}\n\n{mention}")
else:
await kirimPesan(message, "Unsupported url..")
data = wetransfer_bypass(url)
await msg.edit_msg(f"{data}\n\n{mention}")

View file

@ -1,12 +1,13 @@
import openai
import asyncio
from aiohttp import ClientSession
from pyrogram import filters
from pyrogram import filters, Client
from pyrogram.types import Message
from pyrogram.errors import MessageTooLong
from misskaty import app
from misskaty.helper.localization import use_chat_lang
from misskaty.helper import post_to_telegraph, check_time_gap
from misskaty.core.message_utils import *
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.vars import COMMAND_HANDLER, OPENAI_API, SUDO
@ -16,15 +17,15 @@ openai.api_key = OPENAI_API
@app.on_message(filters.command("ask", COMMAND_HANDLER))
@ratelimiter
@use_chat_lang()
async def chatbot(c, m, strings):
if len(m.command) == 1:
return await kirimPesan(m, strings("no_question").format(cmd=m.command[0]), quote=True)
is_in_gap, sleep_time = await check_time_gap(m.from_user.id or m.sender_chat.id)
if is_in_gap and (m.from_user.id or m.sender_chat.id not in SUDO):
return await kirimPesan(m, strings("dont_spam"))
async def 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)
is_in_gap, sleep_time = await check_time_gap(ctx.from_user.id or ctx.sender_chat.id)
if is_in_gap and (ctx.from_user.id or ctx.sender_chat.id not in SUDO):
return await ctx.reply_msg(strings("dont_spam"), del_in=5)
openai.aiosession.set(ClientSession())
pertanyaan = m.text.split(" ", maxsplit=1)[1]
msg = await kirimPesan(m, strings("find_answers_str"), quote=True)
pertanyaan = ctx.input
msg = await ctx.reply_msg(strings("find_answers_str"), quote=True)
num = 0
answer = ""
try:
@ -35,13 +36,13 @@ async def chatbot(c, m, strings):
num += 1
answer += chunk.choices[0].delta.content
if num == 30:
await editPesan(msg, answer)
await msg.edit_msg(answer)
await asyncio.sleep(1.5)
num = 0
await editPesan(msg, answer)
await msg.edit_msg(answer)
await openai.aiosession.get().close()
except MessageTooLong:
answerlink = await post_to_telegraph(False, "MissKaty ChatBot ", answer)
await editPesan(msg, strings("answers_too_long").format(answerlink=answerlink), disable_web_page_preview=True)
await msg.edit_msg(strings("answers_too_long").format(answerlink=answerlink), disable_web_page_preview=True)
except Exception as err:
await editPesan(msg, f"ERROR: {str(err)}")
await msg.edit_msg(f"ERROR: {str(err)}")

View file

@ -3,7 +3,6 @@ from pyrogram.types import Message
from misskaty import app
import logging
from misskaty.helper.http import http
from misskaty.core.message_utils import kirimPesan
from misskaty.vars import COMMAND_HANDLER, CURRENCY_API
@ -16,17 +15,16 @@ LOGGER = logging.getLogger(__name__)
@app.on_message(filters.command(["currency"], COMMAND_HANDLER))
async def currency(c: Client, m: Message):
async def currency(self: Client, ctx: Message):
if CURRENCY_API is None:
return await kirimPesan(
m,
return await ctx.reply_msg(
"<code>Oops!!get the API from</code> <a href='https://app.exchangerate-api.com/sign-up'>HERE</a> <code>& add it to config vars</code> (<code>CURRENCY_API</code>)",
disable_web_page_preview=True,
)
if len(m.text.split()) != 4:
return await kirimPesan(m, f"Use format /{m.command[0]} [amount] [currency_from] [currency_to] to convert currency.")
if len(ctx.text.split()) != 4:
return await ctx.reply_msg(f"Use format /{ctx.command[0]} [amount] [currency_from] [currency_to] to convert currency.", del_in=6)
teks = m.text.split()
teks = ctx.text.split()
amount = teks[1]
currency_from = teks[2]
currency_to = teks[3]
@ -42,9 +40,9 @@ async def currency(c: Client, m: Message):
base_code = data["base_code"]
last_update = data["time_last_update_utc"]
except KeyError:
return await kirimPesan(m, "<code>Invalid response from api !</i>")
await kirimPesan(m, "**CURRENCY EXCHANGE RATE RESULT:**\n\n" f"`{amount}` **{base_code}** = `{round(conversion_result)}` **{target_code}**\n" f"<b>Rate Today</b> = `{round(conversion_rate)}`\n" f"<b>Last Update:</b> {last_update}")
return await ctx.reply_msg("<code>Invalid response from api !</i>")
await ctx.reply_msg(f"**CURRENCY EXCHANGE RATE RESULT:**\n\n`{amount}` **{base_code}** = `{round(conversion_result)}` **{target_code}**\n<b>Rate Today</b> = `{round(conversion_rate)}`\n<b>Last Update:</b> {last_update}")
except:
await kirimPesan(m, "Failed convert currency, maybe you give wrong currency format or api down.")
await ctx.reply_msg("Failed convert currency, maybe you give wrong currency format or api down.")
else:
await kirimPesan(m, r"<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

@ -18,15 +18,14 @@ from psutil import cpu_percent
from psutil import disk_usage as disk_usage_percent
from psutil import virtual_memory
from pyrogram import enums, filters, types
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from pyrogram import enums, filters, Client
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from misskaty import app, user, botStartTime, BOT_NAME
from misskaty.helper.http import http
from misskaty.helper.eval_helper import meval, format_exception
from misskaty.helper.localization import use_chat_lang
from misskaty.helper.human_read import get_readable_file_size, get_readable_time
from misskaty.core.message_utils import editPesan, hapusPesan, kirimPesan
from misskaty.vars import COMMAND_HANDLER, SUDO
__MODULE__ = "DevCommand"
@ -45,18 +44,18 @@ teskode = {}
async def edit_or_reply(msg, **kwargs):
func = msg.edit_text if msg.from_user.is_self else msg.reply
func = msg.edit if msg.from_user.is_self else msg.reply
spec = getfullargspec(func.__wrapped__).args
await func(**{k: v for k, v in kwargs.items() if k in spec})
@app.on_message(filters.command(["logs"], COMMAND_HANDLER) & filters.user(SUDO))
@use_chat_lang()
async def log_file(bot, message, strings):
async def log_file(self: Client, ctx: Message, strings) -> "Message":
"""Send log file"""
msg = await kirimPesan(message, "<b>Reading bot logs ...</b>")
if len(message.command) == 1:
await message.reply_document(
msg = await ctx.reply_msg("<b>Reading bot logs ...</b>")
if len(ctx.command) == 1:
await ctx.reply_document(
"MissKatyLogs.txt",
caption="Log Bot MissKatyPyro",
reply_markup=InlineKeyboardMarkup(
@ -64,17 +63,19 @@ async def log_file(bot, message, strings):
[
InlineKeyboardButton(
strings("cl_btn"),
f"close#{message.from_user.id}",
f"close#{ctx.from_user.id}",
)
]
]
),
)
await hapusPesan(msg)
elif len(message.command) == 2:
val = message.text.split()
await msg.delete_msg()
elif len(ctx.command) == 2:
val = ctx.text.split()
tail = await shell_exec(f"tail -n {val[1]} -v MissKatyLogs.txt")
await editPesan(msg, f"<pre language='bash'>{html.escape(tail[0])}</pre>")
await msg.edit_msg(f"<pre language='bash'>{html.escape(tail[0])}</pre>")
else:
await msg.edit_msg("Unsupported parameter")
@app.on_message(filters.command(["donate"], COMMAND_HANDLER))
@ -86,14 +87,14 @@ async def donate(_, message):
@app.on_message(filters.command(["balas"], COMMAND_HANDLER) & filters.user(SUDO) & filters.reply)
async def balas(c, m):
pesan = m.text.split(" ", 1)
await hapusPesan(m)
await m.reply(pesan[1], reply_to_message_id=m.reply_to_message.id)
async def balas(self: Client, ctx: Message) -> "str":
pesan = ctx.input
await ctx.delete_msg()
await ctx.reply_msg(pesan, reply_to_message_id=ctx.reply_to_message.id)
@app.on_message(filters.command(["stats"], COMMAND_HANDLER))
async def server_stats(c, m):
async def server_stats(self: Client, ctx: Message) -> "Message":
"""
Give system stats of the server.
"""
@ -124,68 +125,67 @@ async def server_stats(c, m):
`{neofetch}`
"""
await kirimPesan(m, caption)
await ctx.reply_msg(caption)
@app.on_message(filters.command(["shell", "sh", "term"], COMMAND_HANDLER) & filters.user(SUDO))
@app.on_edited_message(filters.command(["shell", "sh", "term"], COMMAND_HANDLER) & filters.user(SUDO))
@user.on_message(filters.command(["shell", "sh", "term"], ".") & filters.me)
@use_chat_lang()
async def shell(_, m, strings):
cmd = m.text.split(" ", 1)
if len(m.command) == 1:
return await edit_or_reply(m, text=strings("no_cmd"))
msg = await editPesan(m, strings("run_exec")) if m.from_user.is_self else await kirimPesan(m, strings("run_exec"))
shell = (await shell_exec(cmd[1]))[0]
async def shell(self: Client, ctx: Message, strings) -> "Message":
if len(ctx.command) == 1:
return await edit_or_reply(ctx, text=strings("no_cmd"))
msg = await ctx.edit_msg(strings("run_exec")) if ctx.from_user.is_self else await ctx.reply_msg(strings("run_exec"))
shell = (await shell_exec(ctx.input))[0]
if len(shell) > 3000:
with io.BytesIO(str.encode(shell)) as doc:
doc.name = "shell_output.txt"
await m.reply_document(
await ctx.reply_document(
document=doc,
caption=f"<code>{cmd[1][: 4096 // 4 - 1]}</code>",
caption=f"<code>{ctx.input[: 4096 // 4 - 1]}</code>",
file_name=doc.name,
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text=strings("cl_btn"),
callback_data=f"close#{m.from_user.id}",
callback_data=f"close#{ctx.from_user.id}",
)
]
]
),
)
await msg.delete()
await msg.delete_msg()
elif len(shell) != 0:
await edit_or_reply(
m,
ctx,
text=html.escape(shell),
parse_mode=enums.ParseMode.HTML,
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text=strings("cl_btn"), callback_data=f"close#{m.from_user.id}")]]),
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text=strings("cl_btn"), callback_data=f"close#{ctx.from_user.id}")]]),
)
if not m.from_user.is_self:
await msg.delete()
if not ctx.from_user.is_self:
await msg.delete_msg()
else:
await m.reply(strings("no_reply"))
await ctx.reply(strings("no_reply"), del_in=5)
@app.on_message((filters.command(["ev", "run", "myeval"], COMMAND_HANDLER) | filters.regex(r"app.run\(\)$")) & filters.user(SUDO))
@app.on_edited_message((filters.command(["ev", "run", "myeval"]) | filters.regex(r"app.run\(\)$")) & filters.user(SUDO))
@user.on_message(filters.command(["ev", "run", "myeval"], ".") & filters.me)
@use_chat_lang()
async def cmd_eval(self, message: types.Message, strings) -> Optional[str]:
if (message.command and len(message.command) == 1) or message.text == "app.run()":
return await edit_or_reply(message, text=strings("no_eval"))
status_message = await editPesan(message, strings("run_eval")) if message.from_user.is_self else await kirimPesan(message, strings("run_eval"), quote=True)
code = message.text.split(" ", 1)[1] if message.command else message.text.split("\napp.run()")[0]
async def cmd_eval(self: Client, ctx: Message, strings) -> Optional[str]:
if (ctx.command and len(ctx.command) == 1) or ctx.text == "app.run()":
return await edit_or_reply(ctx, text=strings("no_eval"))
status_message = await ctx.edit_msg(strings("run_eval")) if ctx.from_user.is_self else await ctx.reply_msg(strings("run_eval"), quote=True)
code = ctx.text.split(" ", 1)[1] if ctx.command else ctx.text.split("\napp.run()")[0]
out_buf = io.StringIO()
out = ""
humantime = get_readable_time
async def _eval() -> Tuple[str, Optional[str]]:
# Message sending helper for convenience
async def send(*args: Any, **kwargs: Any) -> types.Message:
return await message.reply(*args, **kwargs)
async def send(*args: Any, **kwargs: Any) -> Message:
return await ctx.reply_msg(*args, **kwargs)
# Print wrapper to capture output
# We don't override sys.stdout to avoid interfering with other output
@ -197,9 +197,8 @@ async def cmd_eval(self, message: types.Message, strings) -> Optional[str]:
eval_vars = {
"self": self,
"humantime": humantime,
"m": message,
"ctx": ctx,
"var": var,
"app": app,
"teskode": teskode,
"re": re,
"os": os,
@ -212,7 +211,7 @@ async def cmd_eval(self, message: types.Message, strings) -> Optional[str]:
"stdout": out_buf,
"traceback": traceback,
"http": http,
"replied": message.reply_to_message,
"replied": ctx.reply_to_message,
}
eval_vars.update(var)
eval_vars.update(teskode)
@ -254,7 +253,7 @@ async def cmd_eval(self, message: types.Message, strings) -> Optional[str]:
if len(final_output) > 4096:
with io.BytesIO(str.encode(out)) as out_file:
out_file.name = "MissKatyEval.txt"
await message.reply_document(
await ctx.reply_document(
document=out_file,
caption=f"<code>{code[: 4096 // 4 - 1]}</code>",
disable_notification=True,
@ -264,38 +263,38 @@ async def cmd_eval(self, message: types.Message, strings) -> Optional[str]:
[
InlineKeyboardButton(
text=strings("cl_btn"),
callback_data=f"close#{message.from_user.id}",
callback_data=f"close#{ctx.from_user.id}",
)
]
]
),
)
await status_message.delete()
await status_message.delete_msg()
else:
await edit_or_reply(
message,
ctx,
text=final_output,
parse_mode=enums.ParseMode.HTML,
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text=strings("cl_btn"), callback_data=f"close#{message.from_user.id}")]]),
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text=strings("cl_btn"), callback_data=f"close#{ctx.from_user.id}")]]),
)
if not message.from_user.is_self:
await status_message.delete()
if not ctx.from_user.is_self:
await status_message.delete_msg()
# Update and restart bot
@app.on_message(filters.command(["update"], COMMAND_HANDLER) & filters.user(SUDO))
@use_chat_lang()
async def update_restart(_, message, strings):
async def update_restart(self: Client, ctx: Message, strings) -> "Message":
try:
out = (await shell_exec("git pull"))[0]
if "Already up to date." in str(out):
return await message.reply_text(strings("already_up"))
await message.reply_text(f"<code>{out}</code>")
return await ctx.reply_msg(strings("already_up"))
await ctx.reply_msg(f"<code>{out}</code>")
except Exception as e:
return await message.reply_text(str(e))
msg = await message.reply_text(strings("up_and_rest"))
return await ctx.reply_msg(str(e))
msg = await ctx.reply_msg(strings("up_and_rest"))
with open("restart.pickle", "wb") as status:
pickle.dump([message.chat.id, msg.id], status)
pickle.dump([ctx.chat.id, msg.id], status)
os.execvp(sys.executable, [sys.executable, "-m", "misskaty"])

View file

@ -31,7 +31,6 @@ from misskaty.core.decorator.errors import capture_err
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.core.decorator.permissions import adminsOnly
from misskaty.core.keyboard import ikb
from misskaty.core.message_utils import *
from misskaty.helper.functions import extract_text_and_keyb
__MODULE__ = "Filters"
@ -48,12 +47,12 @@ You can use markdown or html to save text too.
@ratelimiter
async def save_filters(_, m):
if len(m.command) == 1 or not m.reply_to_message:
return await kirimPesan(m, "**Usage:**\nReply to a text or sticker with /addfilter [FILTER_NAME] to save it.")
return await m.reply_msg("**Usage:**\nReply to a text or sticker with /addfilter [FILTER_NAME] to save it.", del_in=6)
if not m.reply_to_message.text and not m.reply_to_message.sticker:
return await kirimPesan(m, "__**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 kirimPesan(m, "**Usage:**\n__/addfilter [FILTER_NAME]__")
return await m.reply_msg("**Usage:**\n__/addfilter [FILTER_NAME]__", del_in=6)
chat_id = m.chat.id
_type = "text" if m.reply_to_message.text else "sticker"
_filter = {
@ -61,7 +60,7 @@ async def save_filters(_, m):
"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 kirimPesan(m, f"__**Saved filter {name}.**__")
await m.reply_msg(f"__**Saved filter {name}.**__")
@app.on_message(filters.command("filters") & ~filters.private)
@ -70,12 +69,12 @@ async def save_filters(_, m):
async def get_filterss(_, m):
_filters = await get_filters_names(m.chat.id)
if not _filters:
return await kirimPesan(m, "**No filters in this chat.**")
return await m.reply_msg("**No filters in this chat.**")
_filters.sort()
msg = f"List of filters in {m.chat.title} - {m.chat.id}\n"
for _filter in _filters:
msg += f"**-** `{_filter}`\n"
await kirimPesan(m, msg)
await m.reply_msg(msg)
@app.on_message(filters.command("stopfilter") & ~filters.private)
@ -83,16 +82,16 @@ async def get_filterss(_, m):
@ratelimiter
async def del_filter(_, m):
if len(m.command) < 2:
return await kirimPesan(m, "**Usage:**\n__/stopfilter [FILTER_NAME]__")
return await m.reply_msg("**Usage:**\n__/stopfilter [FILTER_NAME]__", del_in=6)
name = m.text.split(None, 1)[1].strip()
if not name:
return await kirimPesan(m, "**Usage:**\n__/stopfilter [FILTER_NAME]__")
return await m.reply_msg("**Usage:**\n__/stopfilter [FILTER_NAME]__", del_in=6)
chat_id = m.chat.id
deleted = await delete_filter(chat_id, name)
if deleted:
await kirimPesan(m, f"**Deleted filter {name}.**")
await m.reply_msg(f"**Deleted filter {name}.**")
else:
await kirimPesan(m, "**No such filter.**")
await m.reply_msg("**No such filter.**")
@app.on_message(

View file

@ -8,16 +8,15 @@
import datetime
import os
import time
from asyncio import gather, sleep
from asyncio import gather, sleep, create_task
from logging import getLogger
from pyrogram import enums, filters
from pyrogram import enums, filters, Client
from pyrogram.errors import FloodWait
from pyrogram.types import InlineKeyboardMarkup
from pyrogram.types import InlineKeyboardMarkup, Message, CallbackQuery
from misskaty import app
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.core.message_utils import *
from misskaty.helper import gen_ik_buttons, get_duration, is_url, progress_for_pyrogram, screenshot_flink, take_ss
from misskaty.helper.localization import use_chat_lang
from misskaty.vars import COMMAND_HANDLER
@ -34,26 +33,26 @@ __HELP__ = """"
@app.on_message(filters.command(["genss"], COMMAND_HANDLER))
@ratelimiter
@use_chat_lang()
async def genss(c, m, strings):
if not m.from_user:
async def genss(self: Client, ctx: Message, strings):
if not ctx.from_user:
return
replied = m.reply_to_message
if len(m.command) == 2 and is_url(m.command[1]):
snt = await kirimPesan(m, strings("wait_msg"), quote=True)
replied = ctx.reply_to_message
if len(ctx.command) == 2 and is_url(ctx.command[1]):
snt = await ctx.reply_msg(strings("wait_msg"), quote=True)
duration = await get_duration(m.command[1])
duration = await get_duration(ctx.command[1])
if isinstance(duration, str):
return await editPesan(snt, strings("fail_open"))
return await snt.edit_msg(strings("fail_open"))
btns = gen_ik_buttons()
await editPesan(snt, strings("choose_no_ss").format(td=datetime.timedelta(seconds=duration), dur=duration), reply_markup=InlineKeyboardMarkup(btns))
await snt.edit_msg(strings("choose_no_ss").format(td=datetime.timedelta(seconds=duration), dur=duration), reply_markup=InlineKeyboardMarkup(btns))
elif replied and replied.media:
vid = [replied.video, replied.document]
media = next((v for v in vid if v is not None), None)
if media is None:
return await kirimPesan(m, strings("no_reply"), quote=True)
process = await kirimPesan(m, strings("wait_dl"), quote=True)
return await ctx.reply_msg(strings("no_reply"), quote=True)
process = await ctx.reply_msg(strings("wait_dl"), quote=True)
if media.file_size > 2097152000:
return await editPesan(process, strings("limit_dl"))
return await process.edit_msg(strings("limit_dl"))
c_time = time.time()
dl = await replied.download(
file_name="/downloads/",
@ -63,31 +62,30 @@ async def genss(c, m, strings):
the_real_download_location = os.path.join("/downloads/", os.path.basename(dl))
if the_real_download_location is not None:
try:
await editPesan(process, 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 editPesan(process, strings("up_progress"))
await c.send_chat_action(chat_id=m.chat.id, action=enums.ChatAction.UPLOAD_PHOTO)
await process.edit_msg(strings("up_progress"))
await self.send_chat_action(chat_id=ctx.chat.id, action=enums.ChatAction.UPLOAD_PHOTO)
try:
await gather(
*[
m.reply_document(images, reply_to_message_id=m.id),
m.reply_photo(images, reply_to_message_id=m.id),
ctx.reply_document(images, reply_to_message_id=ctx.id),
ctx.reply_photo(images, reply_to_message_id=ctx.id),
]
)
except FloodWait as e:
await sleep(e.value)
await gather(
*[
m.reply_document(images, reply_to_message_id=m.id),
m.reply_photo(images, reply_to_message_id=m.id),
ctx.reply_document(images, reply_to_message_id=ctx.id),
ctx.reply_photo(images, reply_to_message_id=ctx.id),
]
)
await kirimPesan(
m,
strings("up_msg").format(namma=m.from_user.mention, id=m.from_user.id, bot_uname=c.me.username),
reply_to_message_id=m.id,
await ctx.reply_msg(
strings("up_msg").format(namma=ctx.from_user.mention, id=ctx.from_user.id, bot_uname=self.me.username),
reply_to_message_id=ctx.id,
)
await process.delete()
try:
@ -96,17 +94,17 @@ async def genss(c, m, strings):
except:
pass
except Exception as exc:
await kirimPesan(m, strings("err_ssgen").format(exc=exc))
await ctx.reply_msg(strings("err_ssgen").format(exc=exc))
try:
os.remove(images)
os.remove(the_real_download_location)
except:
pass
else:
await kirimPesan(m, strings("no_reply"))
await ctx.reply_msg(strings("no_reply"), del_in=6)
@app.on_callback_query(filters.regex(r"^scht"))
@ratelimiter
async def _(c, m):
asyncio.create_task(screenshot_flink(c, m))
async def genss_cb(self: Client, cb: CallbackQuery):
create_task(screenshot_flink(self, cb))

View file

@ -9,18 +9,12 @@ from urllib.parse import quote_plus
from utils import demoji
from deep_translator import GoogleTranslator
from pykeyboard import InlineButton, InlineKeyboard
from pyrogram import filters, enums
from pyrogram.errors import (
MediaEmpty,
MessageNotModified,
PhotoInvalidDimensions,
WebpageMediaEmpty,
)
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, InputMediaPhoto
from pyrogram import filters, enums, Client
from pyrogram.errors import MediaEmpty, MessageNotModified, PhotoInvalidDimensions, WebpageMediaEmpty, MessageIdInvalid
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, InputMediaPhoto, Message, CallbackQuery
from database.imdb_db import *
from misskaty import BOT_USERNAME, app
from misskaty.core.message_utils import *
from misskaty.core.decorator.errors import capture_err
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.helper import http, get_random_string, search_jw, GENRES_EMOJI
@ -35,30 +29,30 @@ headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWe
@app.on_message(filters.command(["imdb"], COMMAND_HANDLER))
@capture_err
@ratelimiter
async def imdb_choose(_, m):
if len(m.command) == 1:
return await kirimPesan(m, f" Please add query after CMD!\nEx: <code>/{m.command[0]} Jurassic World</code>")
if m.sender_chat:
return await kirimPesan(m, "This feature not supported for channel..")
kuery = m.text.split(None, 1)[1]
is_imdb, lang = await is_imdbset(m.from_user.id)
async def imdb_choose(self: Client, ctx: Message):
if len(ctx.command) == 1:
return await ctx.reply_msg(f" Please add query after CMD!\nEx: <code>/{ctx.command[0]} Jurassic World</code>", del_in=5)
if ctx.sender_chat:
return await ctx.reply_msg("This feature not supported for channel..", del_in=5)
kuery = ctx.input
is_imdb, lang = await is_imdbset(ctx.from_user.id)
if is_imdb:
if lang == "eng":
return await imdb_search_en(kuery, m)
return await imdb_search_en(kuery, ctx)
else:
return await imdb_search_id(kuery, m)
return await imdb_search_id(kuery, ctx)
buttons = InlineKeyboard()
ranval = get_random_string(4)
LIST_CARI[ranval] = kuery
buttons.row(
InlineButton("🇺🇸 English", f"imdbcari#eng#{ranval}#{m.from_user.id}"),
InlineButton("🇮🇩 Indonesia", f"imdbcari#ind#{ranval}#{m.from_user.id}"),
InlineButton("🇺🇸 English", f"imdbcari#eng#{ranval}#{ctx.from_user.id}"),
InlineButton("🇮🇩 Indonesia", f"imdbcari#ind#{ranval}#{ctx.from_user.id}"),
)
buttons.row(InlineButton("🚩 Set Default Language", f"imdbset#{m.from_user.id}"))
buttons.row(InlineButton("❌ Close", f"close#{m.from_user.id}"))
await m.reply_photo(
buttons.row(InlineButton("🚩 Set Default Language", f"imdbset#{ctx.from_user.id}"))
buttons.row(InlineButton("❌ Close", f"close#{ctx.from_user.id}"))
await ctx.reply_photo(
"https://telegra.ph/file/270955ef0d1a8a16831a9.jpg",
caption=f"Hi {m.from_user.mention}, Please select the language you want to use on IMDB Search. If you want use default lang for every user, click third button. So no need click select lang if use CMD.",
caption=f"Hi {ctx.from_user.mention}, Please select the language you want to use on IMDB Search. If you want use default lang for every user, click third button. So no need click select lang if use CMD.",
reply_markup=buttons,
quote=True,
)
@ -66,7 +60,7 @@ async def imdb_choose(_, m):
@app.on_callback_query(filters.regex("^imdbset"))
@ratelimiter
async def imdbsetlang(client, query):
async def imdbsetlang(self: Client, query: CallbackQuery):
i, uid = query.data.split("#")
if query.from_user.id != int(uid):
return await query.answer("⚠️ Access Denied!", True)
@ -84,7 +78,7 @@ async def imdbsetlang(client, query):
@app.on_callback_query(filters.regex("^setimdb"))
@ratelimiter
async def imdbsetlang(client, query):
async def imdbsetlang(self: Client, query: CallbackQuery):
i, lang, uid = query.data.split("#")
if query.from_user.id != int(uid):
return await query.answer("⚠️ Access Denied!", True)
@ -201,7 +195,7 @@ async def imdb_search_en(kueri, message):
@app.on_callback_query(filters.regex("^imdbcari"))
@ratelimiter
async def imdbcari(client, query):
async def imdbcari(self: Client, query: CallbackQuery):
BTN = []
i, lang, msg, uid = query.data.split("#")
if lang == "ind":
@ -286,7 +280,7 @@ async def imdbcari(client, query):
@app.on_callback_query(filters.regex("^imdbres_id"))
@ratelimiter
async def imdb_id_callback(_, query):
async def imdb_id_callback(self: Client, query: CallbackQuery):
i, userid, movie = query.data.split("#")
if query.from_user.id != int(userid):
return await query.answer("⚠️ Akses Ditolak!", True)
@ -405,7 +399,7 @@ async def imdb_id_callback(_, query):
@app.on_callback_query(filters.regex("^imdbres_en"))
@ratelimiter
async def imdb_en_callback(bot, query):
async def imdb_en_callback(self: Client, query: CallbackQuery):
i, userid, movie = query.data.split("#")
if query.from_user.id != int(userid):
return await query.answer("⚠️ Access Denied!", True)

View file

@ -11,7 +11,6 @@ from pyrogram.errors.exceptions.forbidden_403 import ChatWriteForbidden
from misskaty import app
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.core.message_utils import editPesan, kirimPesan
from misskaty.vars import COMMAND_HANDLER
__MODULE__ = "Inkick"
@ -25,7 +24,7 @@ __HELP__ = """"
@ratelimiter
async def inkick(_, message):
if message.sender_chat:
return await message.reply("This feature not available for channel.")
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:
@ -65,7 +64,7 @@ async def inkick(_, message):
@ratelimiter
async def uname(_, message):
if message.sender_chat:
return await message.reply("This feature not available for channel.")
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...**")
@ -101,7 +100,7 @@ async def uname(_, message):
@ratelimiter
async def rm_delacc(client, message):
if message.sender_chat:
return await message.reply("This feature not available for channel.")
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...**")
@ -122,8 +121,8 @@ async def rm_delacc(client, message):
except FloodWait as e:
await sleep(e.value)
if count == 0:
return await editPesan(sent_message, "There are no deleted accounts in this chat.")
await editPesan(sent_message, f"✔️ **Berhasil menendang {count} akun terhapus.**")
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.**")
await sleep(5)
@ -134,7 +133,7 @@ async def rm_delacc(client, message):
@ratelimiter
async def instatus(client, message):
if message.sender_chat:
return await kirimPesan(message, "Not supported channel.")
return await message.reply_msg("Not supported channel.", del_in=4)
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)

View file

@ -10,11 +10,10 @@ import subprocess
import time
from os import remove as osremove, path
from pyrogram import filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from pyrogram import filters, Client
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from misskaty import app
from misskaty.core.message_utils import *
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.helper import progress_for_pyrogram, runcmd, post_to_telegraph
from misskaty.helper.mediainfo_paste import mediainfo_paste
@ -26,18 +25,18 @@ from utils import get_file_id
@app.on_message(filters.command(["mediainfo"], COMMAND_HANDLER))
@ratelimiter
@use_chat_lang()
async def mediainfo(client, message, strings):
if not message.from_user:
async def mediainfo(self: Client, ctx: Message, strings):
if not ctx.from_user:
return
if message.reply_to_message and message.reply_to_message.media:
process = await kirimPesan(message, strings("processing_text"), quote=True)
file_info = get_file_id(message.reply_to_message)
if ctx.reply_to_message and ctx.reply_to_message.media:
process = await ctx.reply_msg(strings("processing_text"), quote=True)
file_info = get_file_id(ctx.reply_to_message)
if file_info is None:
return await editPesan(process, strings("media_invalid"))
if (message.reply_to_message.video and message.reply_to_message.video.file_size > 2097152000) or (message.reply_to_message.document and message.reply_to_message.document.file_size > 2097152000):
return await editPesan(process, strings("dl_limit_exceeded"))
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):
return await process.edit_msg(strings("dl_limit_exceeded"), del_in=6)
c_time = time.time()
dl = await message.reply_to_message.download(
dl = await ctx.reply_to_message.download(
file_name="/downloads/",
progress=progress_for_pyrogram,
progress_args=(strings("dl_args_text"), process, c_time),
@ -65,9 +64,9 @@ DETAILS
markup = None
with io.BytesIO(str.encode(body_text)) as out_file:
out_file.name = "MissKaty_Mediainfo.txt"
await message.reply_document(
await ctx.reply_document(
out_file,
caption=strings("capt_media").format(ment=message.from_user.mention),
caption=strings("capt_media").format(ment=ctx.from_user.mention),
thumb="assets/thumb.jpg",
reply_markup=markup,
)
@ -78,12 +77,12 @@ DETAILS
pass
else:
try:
link = message.text.split(" ", maxsplit=1)[1]
process = await kirimPesan(message, strings("wait_msg"))
link = ctx.input
process = await ctx.reply_msg(strings("wait_msg"))
try:
output = subprocess.check_output(["mediainfo", f"{link}"]).decode("utf-8")
except Exception:
return await editPesan(process, strings("err_link"))
return await process.edit_msg(strings("err_link"))
body_text = f"""
MissKatyBot MediaInfo
{output}
@ -100,12 +99,12 @@ DETAILS
markup = None
with io.BytesIO(str.encode(output)) as out_file:
out_file.name = "MissKaty_Mediainfo.txt"
await message.reply_document(
await ctx.reply_document(
out_file,
caption=strings("capt_media").format(ment=message.from_user.mention),
caption=strings("capt_media").format(ment=ctx.from_user.mention),
thumb="assets/thumb.jpg",
reply_markup=markup,
)
await process.delete()
except IndexError:
return await kirimPesan(message, strings("mediainfo_help").format(cmd=message.command[0]))
return await ctx.reply_msg(strings("mediainfo_help").format(cmd=ctx.command[0]), del_in=6)

View file

@ -25,7 +25,6 @@ from pyrogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMa
from misskaty import BOT_USERNAME, app
from misskaty.core.decorator.errors import capture_err
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.core.message_utils import editPesan, hapusPesan, kirimPesan
from misskaty.helper.http import http
from misskaty.helper.tools import rentry
from misskaty.vars import COMMAND_HANDLER
@ -67,8 +66,8 @@ async def readqr(c, m):
r = await http.post(url, files=myfile)
os.remove(foto)
if res := r.json()[0]["symbol"][0]["data"] is None:
return await kirimPesan(m, res)
await kirimPesan(m, f"<b>QR Code Reader by @{c.me.username}:</b> <code>{r.json()[0]['symbol'][0]['data']}</code>", quote=True)
return await m.reply_msg(res)
await m.reply_msg(f"<b>QR Code Reader by @{c.me.username}:</b> <code>{r.json()[0]['symbol'][0]['data']}</code>", quote=True)
@app.on_message(filters.command("createqr", COMMAND_HANDLER))
@ -172,12 +171,12 @@ async def translate(client, message):
try:
my_translator = GoogleTranslator(source="auto", target=target_lang)
result = my_translator.translate(text=text)
await editPesan(msg, f"Translation using source = {my_translator.source} and target = {my_translator.target}\n\n-> {result}")
await msg.edit_msg(f"Translation using source = {my_translator.source} and target = {my_translator.target}\n\n-> {result}")
except MessageTooLong:
url = await rentry(result)
await editPesan(msg, f"Your translated text pasted to rentry because has long text:\n{url}")
await msg.edit_msg(f"Your translated text pasted to rentry because has long text:\n{url}")
except Exception as err:
await editPesan(msg, f"Oppss, Error: <code>{str(err)}</code>")
await msg.edit_msg(f"Oppss, Error: <code>{str(err)}</code>")
@app.on_message(filters.command(["tts"], COMMAND_HANDLER))
@ -289,7 +288,7 @@ async def showid(client, message):
async def who_is(client, message):
# https://github.com/SpEcHiDe/PyroGramBot/blob/master/pyrobot/plugins/admemes/whois.py#L19
if message.sender_chat:
return await kirimPesan(message, "Not supported channel..")
return await message.reply_msg("Not supported channel..")
status_message = await message.reply_text("`Fetching user info...`")
await status_message.edit("`Processing user info...`")
from_user = None
@ -350,8 +349,8 @@ async def close_callback(bot: Client, query: CallbackQuery):
return await query.answer("⚠️ Access Denied!", True)
await query.answer("Deleting this message in 5 seconds.")
await asyncio.sleep(5)
await hapusPesan(query.message)
await hapusPesan(query.message.reply_to_message)
await query.message.delete_msg()
await query.message.reply_to_message.delete_msg()
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.1.17 (KHTML, like Gecko) Version/7.1 Safari/537.85.10"}

View file

@ -9,7 +9,6 @@ from pyrogram.types import ChatPermissions, InlineKeyboardButton, InlineKeyboard
from database.locale_db import get_db_lang
from misskaty import BOT_NAME, app, scheduler
from misskaty.core.message_utils import *
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.core.decorator.permissions import require_admin
from misskaty.helper.localization import use_chat_lang, langdict
@ -140,8 +139,8 @@ async def nightmode_handler(c, msg, strings):
scheduler.remove_job(job_id=f"disable_nightmode_{chat_id}")
if not bool(scheduler.get_jobs()) and bool(scheduler.state):
scheduler.shutdown()
return await kirimPesan(msg, strings("nmd_disabled"))
return await kirimPesan(msg, strings("nmd_not_enabled"))
return await msg.reply_msg(strings("nmd_disabled"))
return await msg.reply_msg(strings("nmd_not_enabled"))
starttime = re.findall(r"-s=(\d+:\d+)", msg.text)
start = starttime[0] if starttime else "00:00"
@ -150,13 +149,13 @@ async def nightmode_handler(c, msg, strings):
try:
start_timestamp = TIME_ZONE.localize(datetime.strptime((now.strftime("%m:%d:%Y - ") + start), "%m:%d:%Y - %H:%M"))
except ValueError:
return await kirimPesan(msg, strings("invalid_time_format"))
return await msg.reply_msg(strings("invalid_time_format"), del_in=6)
lockdur = re.findall(r"-e=(\w+)", msg.text)
lockdur = lockdur[0] if lockdur else "6h"
lock_dur = extract_time(lockdur.lower())
if not lock_dur:
return await kirimPesan(msg, strings("invalid_lockdur"))
return await msg.reply_msg(strings("invalid_lockdur"), del_in=6)
if start_timestamp < now:
start_timestamp = start_timestamp + timedelta(days=1)
@ -168,8 +167,8 @@ async def nightmode_handler(c, msg, strings):
# schedule to disable nightmode
scheduler.add_job(un_mute_chat, "interval", [chat_id, msg.chat.permissions], id=f"disable_nightmode_{chat_id}", days=1, next_run_time=end_time_stamp, max_instances=50, misfire_grace_time=None)
except ConflictingIdError:
return await kirimPesan(msg, strings("schedule_already_on"))
await kirimPesan(msg, strings("nmd_enable_success").format(st=start_timestamp.strftime("%H:%M:%S"), lockdur=lockdur))
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))
if not bool(scheduler.state):
scheduler.start()

View file

@ -9,11 +9,11 @@
import os
from pyrogram import filters
from pyrogram import filters, Client
from pyrogram.types import Message
from telegraph.aio import Telegraph
from misskaty import app
from misskaty.core.message_utils import *
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.core.decorator.errors import capture_err
from misskaty.helper.localization import use_chat_lang
@ -28,15 +28,15 @@ __HELP__ = "/ocr [reply to photo] - Read Text From Image"
@capture_err
@ratelimiter
@use_chat_lang()
async def ocr(_, m, strings):
reply = m.reply_to_message
async def ocr(self: Client, ctx: Message, strings):
reply = ctx.reply_to_message
if not reply or not reply.photo and (reply.document and not reply.document.mime_type.startswith("image")) and not reply.sticker:
return await kirimPesan(m, strings("no_photo").format(cmd=m.command[0]), quote=True)
msg = await kirimPesan(m, strings("read_ocr"), quote=True)
return await ctx.reply_msg(strings("no_photo").format(cmd=ctx.command[0]), quote=True, del_in=6)
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_{m.from_user.id}.jpg")
file_path = await reply.download(f"ocr_{ctx.from_user.id}.jpg")
response = await Telegraph().upload_file(file_path)
url = f"https://telegra.ph{response[0]['src']}"
req = (
@ -45,8 +45,8 @@ async def ocr(_, m, strings):
follow_redirects=True,
)
).json()
await editPesan(msg, strings("result_ocr").format(result=req["text"]))
await msg.edit_msg(strings("result_ocr").format(result=req["text"]))
os.remove(file_path)
except Exception as e:
await editPesan(msg, str(e))
await msg.edit_msg(str(e))
os.remove(file_path)

View file

@ -13,7 +13,6 @@ from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from misskaty import app
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.core.message_utils import *
from misskaty.helper import http, rentry, post_to_telegraph
from misskaty.vars import COMMAND_HANDLER
@ -71,7 +70,7 @@ pattern = compiles(r"^text/|json$|yaml$|xml$|toml$|x-sh$|x-shellscript$|x-subrip
async def telegraph_paste(_, message):
reply = message.reply_to_message
if not reply and len(message.command) < 2:
return await kirimPesan(message, f"**Reply To A Message With /{message.command[0]} or with command**")
return await message.reply_msg(f"**Reply To A Message With /{message.command[0]} or with command**", del_in=6)
if message.from_user:
if message.from_user.username:
@ -80,14 +79,14 @@ async def telegraph_paste(_, message):
uname = f"[{message.from_user.first_name}](tg://user?id={message.from_user.id}) [{message.from_user.id}]"
else:
uname = message.sender_chat.title
msg = await kirimPesan(message, "`Pasting to Telegraph...`")
msg = await message.reply_msg("`Pasting to Telegraph...`")
if reply and (reply.photo or reply.animation):
file = await reply.download()
try:
url = await post_to_telegraph(True, media=file)
except Exception as err:
remove(file)
return editPesan(msg, f"Failed to upload. ERR: {err}")
return msg.edit_msg(f"Failed to upload. ERR: {err}")
button = [
[InlineKeyboardButton("Open Link", url=url)],
[InlineKeyboardButton("Share Link", url=f"https://telegram.me/share/url?url={url}")],
@ -95,14 +94,14 @@ async def telegraph_paste(_, message):
pasted = f"**Successfully upload your media to Telegraph<a href='{url}'>.</a>\n\nUpload by {uname}**"
remove(file)
return await editPesan(msg, pasted, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup(button))
return await msg.edit_msg(pasted, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup(button))
data = ""
limit = 1024 * 1024
if reply and reply.document:
if reply.document.file_size > limit:
return await editPesan(msg, f"**You can only paste files smaller than {humanbytes(limit)}.**")
return await msg.edit_msg(f"**You can only paste files smaller than {humanbytes(limit)}.**")
if not pattern.search(reply.document.mime_type):
return await editPesan(msg, "**Only text files can be pasted.**")
return await msg.edit_msg("**Only text files can be pasted.**")
file = await reply.download()
title = message.text.split(None, 1)[1] if len(message.command) > 1 else "MissKaty Paste"
try:
@ -114,7 +113,7 @@ async def telegraph_paste(_, message):
remove(file)
except:
pass
return await editPesan(msg, "`File Not Supported !`")
return await msg.edit_msg("`File Not Supported !`")
elif reply and (reply.text or reply.caption):
title = message.text.split(None, 1)[1] if len(message.command) > 1 else "MissKaty Paste"
data = reply.text.html.replace("\n", "<br>") or reply.caption.html.replace("\n", "<br>")
@ -125,17 +124,17 @@ async def telegraph_paste(_, message):
try:
url = await post_to_telegraph(False, title, data)
except Exception as e:
return await editPesan(msg, f"ERROR: {e}")
return await msg.edit_msg(f"ERROR: {e}")
if not url:
return await editPesan(msg, "Text Too Short Or File Problems")
return await msg.edit_msg("Text Too Short Or File Problems")
button = [
[InlineKeyboardButton("Open Link", url=url)],
[InlineKeyboardButton("Share Link", url=f"https://telegram.me/share/url?url={url}")],
]
pasted = f"**Successfully pasted your data to Telegraph<a href='{url}'>.</a>\n\nPaste by {uname}**"
await editPesan(msg, pasted, reply_markup=InlineKeyboardMarkup(button))
await msg.edit_msg(pasted, reply_markup=InlineKeyboardMarkup(button))
# Default Paste to Wastebin using Deta
@ -145,16 +144,16 @@ async def wastepaste(_, message):
reply = message.reply_to_message
target = str(message.command[0]).split("@", maxsplit=1)[0]
if not reply and len(message.command) < 2:
return await kirimPesan(message, f"**Reply To A Message With /{target} or with command**")
return await message.reply_msg(f"**Reply To A Message With /{target} or with command**", del_in=6)
msg = await kirimPesan(message, "`Pasting to YasirBin...`")
msg = await message.reply_msg("`Pasting to YasirBin...`")
data = ""
limit = 1024 * 1024
if reply and reply.document:
if reply.document.file_size > limit:
return await editPesan(msg, f"**You can only paste files smaller than {humanbytes(limit)}.**")
return await msg.edit_msg(f"**You can only paste files smaller than {humanbytes(limit)}.**")
if not pattern.search(reply.document.mime_type):
return await editPesan(msg, "**Only text files can be pasted.**")
return await msg.edit_msg("**Only text files can be pasted.**")
file = await reply.download()
try:
with open(file, "r") as text:
@ -165,7 +164,7 @@ async def wastepaste(_, message):
remove(file)
except:
pass
return await editPesan(msg, "`File Not Supported !`")
return await msg.edit_msg("`File Not Supported !`")
elif reply and (reply.text or reply.caption):
data = reply.text or reply.caption
elif not reply and len(message.command) >= 2:
@ -190,17 +189,17 @@ async def wastepaste(_, message):
response = await http.post("https://paste.yasir.eu.org/api/new", json=json_data)
url = f"https://paste.yasir.eu.org/{response.json()['id']}"
except Exception as e:
return await editPesan(msg, f"ERROR: {e}")
return await msg.edit_msg(f"ERROR: {e}")
if not url:
return await editPesan(msg, "Text Too Short Or File Problems")
return await msg.edit_msg("Text Too Short Or File Problems")
button = [
[InlineKeyboardButton("Open Link", url=url)],
[InlineKeyboardButton("Share Link", url=f"https://telegram.me/share/url?url={url}")],
]
pasted = f"**Successfully pasted your data to YasirBin<a href='{url}'>.</a>\n\nPaste by {uname}**"
await editPesan(msg, pasted, reply_markup=InlineKeyboardMarkup(button))
await msg.edit_msg(pasted, reply_markup=InlineKeyboardMarkup(button))
# Nekobin Paste
@ -210,16 +209,16 @@ async def nekopaste(_, message):
reply = message.reply_to_message
target = str(message.command[0]).split("@", maxsplit=1)[0]
if not reply and len(message.command) < 2:
return await kirimPesan(message, f"**Reply To A Message With /{target} or with command**")
return await message.reply_msg(f"**Reply To A Message With /{target} or with command**", del_in=6)
msg = await kirimPesan(message, "`Pasting to Nekobin...`")
msg = await message.reply_msg("`Pasting to Nekobin...`")
data = ""
limit = 1024 * 1024
if reply and reply.document:
if reply.document.file_size > limit:
return await editPesan(message, f"**You can only paste files smaller than {humanbytes(limit)}.**")
return await message.edit_msg(f"**You can only paste files smaller than {humanbytes(limit)}.**")
if not pattern.search(reply.document.mime_type):
return await editPesan(message, "**Only text files can be pasted.**")
return await message.edit_msg("**Only text files can be pasted.**")
file = await reply.download()
try:
with open(file, "r") as text:
@ -230,7 +229,7 @@ async def nekopaste(_, message):
remove(file)
except:
pass
return await editPesan(message, "`File Not Supported !`")
return await message.edit_msg("`File Not Supported !`")
elif reply and (reply.text or reply.caption):
data = reply.text.html or reply.caption.html
elif not reply and len(message.command) >= 2:
@ -248,17 +247,17 @@ async def nekopaste(_, message):
x = (await http.post("https://nekobin.com/api/documents", json={"content": data})).json()
url = f"https://nekobin.com/{x['result']['key']}"
except Exception as e:
return await editPesan(msg, f"ERROR: {e}")
return await msg.edit_msg(f"ERROR: {e}")
if not url:
return await editPesan(msg, "Text Too Short Or File Problems")
return await msg.edit_msg("Text Too Short Or File Problems")
button = [
[InlineKeyboardButton("Open Link", url=url)],
[InlineKeyboardButton("Share Link", url=f"https://telegram.me/share/url?url={url}")],
]
pasted = f"**Successfully pasted your data to Nekobin<a href='{url}'>.</a>\n\nPaste by {uname}**"
await editPesan(msg, pasted, reply_markup=InlineKeyboardMarkup(button))
await msg.edit_msg(pasted, reply_markup=InlineKeyboardMarkup(button))
# Paste as spacebin
@ -268,16 +267,16 @@ async def spacebinn(_, message):
reply = message.reply_to_message
target = str(message.command[0]).split("@", maxsplit=1)[0]
if not reply and len(message.command) < 2:
return await kirimPesan(message, f"**Reply To A Message With /{target} or with command**")
return await message.reply_msg(f"**Reply To A Message With /{target} or with command**", del_in=6)
msg = await kirimPesan(message, "`Pasting to Spacebin...`")
msg = await message.reply_msg("`Pasting to Spacebin...`")
data = ""
limit = 1024 * 1024
if reply and reply.document:
if reply.document.file_size > limit:
return await editPesan(msg, f"**You can only paste files smaller than {humanbytes(limit)}.**")
return await msg.edit_msg(f"**You can only paste files smaller than {humanbytes(limit)}.**")
if not pattern.search(reply.document.mime_type):
return await editPesan(msg, "**Only text files can be pasted.**")
return await msg.edit_msg("**Only text files can be pasted.**")
file = await reply.download()
try:
with open(file, "r") as text:
@ -288,7 +287,7 @@ async def spacebinn(_, message):
remove(file)
except:
pass
return await editPesan(msg, "`File Not Supported !`")
return await msg.edit_msg("`File Not Supported !`")
elif reply and (reply.text or reply.caption):
data = reply.text.html or reply.caption.html
elif not reply and len(message.command) >= 2:
@ -308,17 +307,17 @@ async def spacebinn(_, message):
response = response.json()
url = "https://spaceb.in/" + response["payload"]["id"]
except Exception as e:
return await editPesan(msg, f"ERROR: {e}")
return await msg.edit_msg(f"ERROR: {e}")
if not url:
return await editPesan(msg, "Text Too Short Or File Problems")
return await msg.edit_msg("Text Too Short Or File Problems")
button = [
[InlineKeyboardButton("Open Link", url=url)],
[InlineKeyboardButton("Share Link", url=f"https://telegram.me/share/url?url={url}")],
]
pasted = f"**Successfully pasted your data to Spacebin<a href='{url}'>.</a>\n\nPaste by {uname}**"
await editPesan(msg, pasted, reply_markup=InlineKeyboardMarkup(button))
await msg.edit_msg(pasted, reply_markup=InlineKeyboardMarkup(button))
# Rentry paste
@ -328,16 +327,16 @@ async def rentrypaste(_, message):
reply = message.reply_to_message
target = str(message.command[0]).split("@", maxsplit=1)[0]
if not reply and len(message.command) < 2:
return await kirimPesan(message, f"**Reply To A Message With /{target} or with command**")
return await message.reply_msg(f"**Reply To A Message With /{target} or with command**", del_in=6)
msg = await kirimPesan(message, "`Pasting to Rentry...`")
msg = await message.reply_msg("`Pasting to Rentry...`")
data = ""
limit = 1024 * 1024
if reply and reply.document:
if reply.document.file_size > limit:
return await editPesan(msg, f"**You can only paste files smaller than {humanbytes(limit)}.**")
return await msg.edit_msg(f"**You can only paste files smaller than {humanbytes(limit)}.**")
if not pattern.search(reply.document.mime_type):
return await editPesan(msg, "**Only text files can be pasted.**")
return await msg.edit_msg("**Only text files can be pasted.**")
file = await reply.download()
try:
with open(file, "r") as text:
@ -348,7 +347,7 @@ async def rentrypaste(_, message):
remove(file)
except:
pass
return await editPesan(msg, "`File Not Supported !`")
return await msg.edit_msg("`File Not Supported !`")
elif reply and (reply.text or reply.caption):
data = reply.text.markdown or reply.caption.markdown
elif not reply and len(message.command) >= 2:
@ -368,14 +367,14 @@ async def rentrypaste(_, message):
return await msg.edit(f"`{e}`")
if not url:
return await editPesan(msg, "Text Too Short Or File Problems")
return await msg.edit_msg("Text Too Short Or File Problems")
button = [
[InlineKeyboardButton("Open Link", url=url)],
[InlineKeyboardButton("Share Link", url=f"https://telegram.me/share/url?url={url}")],
]
pasted = f"**Successfully pasted your data to Rentry<a href='{url}'>.</a>\n\nPaste by {uname}**"
await editPesan(msg, pasted, reply_markup=InlineKeyboardMarkup(button))
await msg.edit_msg(pasted, reply_markup=InlineKeyboardMarkup(button))
# Tempaste pastebin
@ -385,16 +384,16 @@ async def tempaste(_, message):
reply = message.reply_to_message
target = str(message.command[0]).split("@", maxsplit=1)[0]
if not reply and len(message.command) < 2:
return await editPesan(message, f"**Reply To A Message With /{target} or with command**")
return await message.edit_msg(f"**Reply To A Message With /{target} or with command**", del_in=6)
msg = await kirimPesan(message, "`Pasting to TempPaste...`")
msg = await message.reply_msg("`Pasting to TempPaste...`")
data = ""
limit = 1024 * 1024
if reply and reply.document:
if reply.document.file_size > limit:
return await editPesan(msg, f"**You can only paste files smaller than {humanbytes(limit)}.**")
return await msg.edit_msg(f"**You can only paste files smaller than {humanbytes(limit)}.**")
if not pattern.search(reply.document.mime_type):
return await editPesan(msg, "**Only text files can be pasted.**")
return await msg.edit_msg("**Only text files can be pasted.**")
file = await reply.download()
try:
with open(file, "r") as text:
@ -405,7 +404,7 @@ async def tempaste(_, message):
remove(file)
except:
pass
return await editPesan(msg, "`File Not Supported !`")
return await msg.edit_msg("`File Not Supported !`")
elif reply and (reply.text or reply.caption):
data = reply.text.html or reply.caption.html
elif not reply and len(message.command) >= 2:
@ -433,14 +432,14 @@ async def tempaste(_, message):
)
url = f"https://tempaste.com/{json_loads(req.text)['url']}"
except Exception as e:
return await editPesan(msg, f"`{e}`")
return await msg.edit_msg(f"`{e}`")
if not url:
return await editPesan(msg, "Text Too Short Or File Problems")
return await msg.edit_msg("Text Too Short Or File Problems")
button = [
[InlineKeyboardButton("Open Link", url=url)],
[InlineKeyboardButton("Share Link", url=f"https://telegram.me/share/url?url={url}")],
]
pasted = f"**Successfully pasted your data to Tempaste<a href='{url}'>.</a>\n\nPaste by {uname}**"
await editPesan(msg, pasted, reply_markup=InlineKeyboardMarkup(button))
await msg.edit_msg(pasted, reply_markup=InlineKeyboardMarkup(button))

View file

@ -11,7 +11,8 @@ from asyncio import Lock
from re import MULTILINE, findall
from subprocess import run as srun
from pyrogram import filters
from pyrogram import filters, Client
from pyrogram.types import Message
from misskaty import app, botStartTime
from misskaty.core.decorator.ratelimiter import ratelimiter
@ -23,7 +24,7 @@ from misskaty.vars import COMMAND_HANDLER
@app.on_message(filters.command(["ping"], COMMAND_HANDLER))
@ratelimiter
async def ping(_, message):
async def ping(self: Client, ctx: Message):
if os.path.exists(".git"):
botVersion = (await shell_exec("git log -1 --date=format:v%y.%m%d.%H%M --pretty=format:%cd"))[0]
else:
@ -35,19 +36,16 @@ async def ping(_, message):
org = "N/A"
currentTime = get_readable_time(time.time() - botStartTime)
start_t = time.time()
rm = await message.reply_text("🐱 Pong!!...")
rm = await ctx.reply_msg("🐱 Pong!!...")
end_t = time.time()
time_taken_s = round(end_t - start_t, 3)
try:
await rm.edit(f"<b>🐈 MissKatyBot {botVersion} online.</b>\n\n<b>Ping:</b> <code>{time_taken_s} detik</code>\n<b>Uptime:</b> <code>{currentTime}</code>\nHosted by <code>{org}</code>")
except Exception:
pass
await rm.edit_msg(f"<b>🐈 MissKatyBot {botVersion} online.</b>\n\n<b>Ping:</b> <code>{time_taken_s} detik</code>\n<b>Uptime:</b> <code>{currentTime}</code>\nHosted by <code>{org}</code>")
@app.on_message(filters.command(["ping_dc"], COMMAND_HANDLER))
@ratelimiter
async def ping_handler(_, message):
m = await message.reply("Pinging datacenters...")
async def ping_handler(self: Client, ctx: Message):
m = await ctx.reply_msg("Pinging datacenters...")
async with Lock():
ips = {
"dc1": "149.154.175.53",
@ -72,4 +70,4 @@ async def ping_handler(_, message):
except Exception:
# There's a cross emoji here, but it's invisible.
text += f" **{dc.upper}:** ❌\n"
await m.edit(text)
await m.edit_msg(text)

View file

@ -6,11 +6,11 @@
* Copyright @YasirPedia All rights reserved
"""
from pykeyboard import InlineButton, InlineKeyboard
from pyrogram import filters
from pyrogram import filters, Client
from pyrogram.types import Message, CallbackQuery
from misskaty import app
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.core.message_utils import *
from misskaty.helper.http import http
from misskaty.plugins.web_scraper import split_arr, headers
from misskaty.vars import COMMAND_HANDLER
@ -22,7 +22,7 @@ async def getDataPypi(msg, kueri, CurrentPage, user):
if not PYPI_DICT.get(msg.id):
pypijson = (await http.get(f"https://yasirapi.eu.org/pypi?q={kueri}")).json()
if not pypijson.get("result"):
await editPesan(msg, "Sorry could not find any matching results!")
await msg.edit_msg("Sorry could not find any matching results!", del_in=6)
return None, 0, None
PYPI_DICT[msg.id] = [split_arr(pypijson["result"], 6), kueri]
try:
@ -36,32 +36,32 @@ async def getDataPypi(msg, kueri, CurrentPage, user):
pypiResult = "".join(i for i in pypiResult if i not in "[]")
return pypiResult, PageLen, extractbtn
except (IndexError, KeyError):
await editPesan(msg, "Sorry could not find any matching results!")
await msg.edit_msg("Sorry could not find any matching results!", del_in=6)
return None, 0, None
@app.on_message(filters.command(["pypi"], COMMAND_HANDLER))
@ratelimiter
async def pypi_s(client, message):
kueri = " ".join(message.command[1:])
async def pypi_s(self: Client, ctx: Message):
kueri = " ".join(ctx.command[1:])
if not kueri:
return await kirimPesan(message, "Please add query after command. Ex: <code>/pypi pyrogram</code>")
pesan = await kirimPesan(message, "⏳ Please wait, getting data from pypi..", quote=True)
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, message.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}#{message.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#{message.from_user.id}"))
await editPesan(pesan, pypires, reply_markup=keyboard)
keyboard.row(InlineButton("❌ Close", f"close#{ctx.from_user.id}"))
await pesan.edit_msg(pypires, reply_markup=keyboard)
@app.on_callback_query(filters.create(lambda _, __, query: "page_pypi#" in query.data))
@ratelimiter
async def pypipage_callback(client, callback_query):
async def pypipage_callback(self: Client, callback_query: CallbackQuery):
if callback_query.from_user.id != int(callback_query.data.split("#")[3]):
return await callback_query.answer("Not yours..", True)
message_id = int(callback_query.data.split("#")[2])
@ -81,12 +81,12 @@ async def pypipage_callback(client, callback_query):
keyboard.row(InlineButton("👇 Extract Data ", "Hmmm"))
keyboard.row(*btn)
keyboard.row(InlineButton("❌ Close", f"close#{callback_query.from_user.id}"))
await editPesan(callback_query.message, pypires, reply_markup=keyboard)
await callback_query.message.edit_msg(pypires, reply_markup=keyboard)
@app.on_callback_query(filters.create(lambda _, __, query: "pypidata#" in query.data))
@ratelimiter
async def pypi_getdata(_, callback_query):
async def pypi_getdata(self: Client, callback_query: CallbackQuery):
if callback_query.from_user.id != int(callback_query.data.split("#")[3]):
return await callback_query.answer("Not yours..", True)
idlink = int(callback_query.data.split("#")[2])
@ -119,6 +119,6 @@ async def pypi_getdata(_, callback_query):
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 editPesan(callback_query.message, f"ERROR: {err}", reply_markup=keyboard)
await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard)
return
await editPesan(callback_query.message, msg, reply_markup=keyboard)
await callback_query.message.edit_msg(msg, reply_markup=keyboard)

View file

@ -18,115 +18,115 @@ class QuotlyException(Exception):
pass
async def get_message_sender_id(m: Message):
if m.forward_date:
if m.forward_sender_name:
async def get_message_sender_id(ctx: Message):
if ctx.forward_date:
if ctx.forward_sender_name:
return 1
elif m.forward_from:
return m.forward_from.id
elif m.forward_from_chat:
return m.forward_from_chat.id
elif ctx.forward_from:
return ctx.forward_from.id
elif ctx.forward_from_chat:
return ctx.forward_from_chat.id
else:
return 1
elif m.from_user:
return m.from_user.id
elif m.sender_chat:
return m.sender_chat.id
elif ctx.from_user:
return ctx.from_user.id
elif ctx.sender_chat:
return ctx.sender_chat.id
else:
return 1
async def get_message_sender_name(m: Message):
if m.forward_date:
if m.forward_sender_name:
return m.forward_sender_name
elif m.forward_from:
return f"{m.forward_from.first_name} {m.forward_from.last_name}" if m.forward_from.last_name else m.forward_from.first_name
async def get_message_sender_name(ctx: Message):
if ctx.forward_date:
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
elif m.forward_from_chat:
return m.forward_from_chat.title
elif ctx.forward_from_chat:
return ctx.forward_from_chat.title
else:
return ""
elif m.from_user:
if m.from_user.last_name:
return f"{m.from_user.first_name} {m.from_user.last_name}"
elif ctx.from_user:
if ctx.from_user.last_name:
return f"{ctx.from_user.first_name} {ctx.from_user.last_name}"
else:
return m.from_user.first_name
elif m.sender_chat:
return m.sender_chat.title
return ctx.from_user.first_name
elif ctx.sender_chat:
return ctx.sender_chat.title
else:
return ""
async def get_custom_emoji(m: Message):
if m.forward_date:
return "" if m.forward_sender_name or not m.forward_from and m.forward_from_chat or not m.forward_from else m.forward_from.emoji_status.custom_emoji_id
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 m.from_user.emoji_status.custom_emoji_id if m.from_user else ""
return ctx.from_user.emoji_status.custom_emoji_id if ctx.from_user else ""
async def get_message_sender_username(m: Message):
if m.forward_date:
if not m.forward_sender_name and not m.forward_from and m.forward_from_chat and m.forward_from_chat.username:
return m.forward_from_chat.username
elif not m.forward_sender_name and not m.forward_from and m.forward_from_chat or m.forward_sender_name or not m.forward_from:
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:
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:
return ""
else:
return m.forward_from.username or ""
elif m.from_user and m.from_user.username:
return m.from_user.username
elif m.from_user or m.sender_chat and not m.sender_chat.username or not m.sender_chat:
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:
return ""
else:
return m.sender_chat.username
return ctx.sender_chat.username
async def get_message_sender_photo(m: Message):
if m.forward_date:
if not m.forward_sender_name and not m.forward_from and m.forward_from_chat and m.forward_from_chat.photo:
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:
return {
"small_file_id": m.forward_from_chat.photo.small_file_id,
"small_photo_unique_id": m.forward_from_chat.photo.small_photo_unique_id,
"big_file_id": m.forward_from_chat.photo.big_file_id,
"big_photo_unique_id": m.forward_from_chat.photo.big_photo_unique_id,
"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 m.forward_sender_name and not m.forward_from and m.forward_from_chat or m.forward_sender_name or not m.forward_from:
elif not 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 (
{
"small_file_id": m.forward_from.photo.small_file_id,
"small_photo_unique_id": m.forward_from.photo.small_photo_unique_id,
"big_file_id": m.forward_from.photo.big_file_id,
"big_photo_unique_id": m.forward_from.photo.big_photo_unique_id,
"small_file_id": ctx.forward_from.photo.small_file_id,
"small_photo_unique_id": ctx.forward_from.photo.small_photo_unique_id,
"big_file_id": ctx.forward_from.photo.big_file_id,
"big_photo_unique_id": ctx.forward_from.photo.big_photo_unique_id,
}
if m.forward_from.photo
if ctx.forward_from.photo
else ""
)
elif m.from_user and m.from_user.photo:
elif ctx.from_user and ctx.from_user.photo:
return {
"small_file_id": m.from_user.photo.small_file_id,
"small_photo_unique_id": m.from_user.photo.small_photo_unique_id,
"big_file_id": m.from_user.photo.big_file_id,
"big_photo_unique_id": m.from_user.photo.big_photo_unique_id,
"small_file_id": ctx.from_user.photo.small_file_id,
"small_photo_unique_id": ctx.from_user.photo.small_photo_unique_id,
"big_file_id": ctx.from_user.photo.big_file_id,
"big_photo_unique_id": ctx.from_user.photo.big_photo_unique_id,
}
elif m.from_user or m.sender_chat and not m.sender_chat.photo or not m.sender_chat:
elif ctx.from_user or ctx.sender_chat and not ctx.sender_chat.photo or not ctx.sender_chat:
return ""
else:
return {
"small_file_id": m.sender_chat.photo.small_file_id,
"small_photo_unique_id": m.sender_chat.photo.small_photo_unique_id,
"big_file_id": m.sender_chat.photo.big_file_id,
"big_photo_unique_id": m.sender_chat.photo.big_photo_unique_id,
"small_file_id": ctx.sender_chat.photo.small_file_id,
"small_photo_unique_id": ctx.sender_chat.photo.small_photo_unique_id,
"big_file_id": ctx.sender_chat.photo.big_file_id,
"big_photo_unique_id": ctx.sender_chat.photo.big_photo_unique_id,
}
async def get_text_or_caption(m: Message):
if m.text:
return m.text
elif m.caption:
return m.caption
async def get_text_or_caption(ctx: Message):
if ctx.text:
return ctx.text
elif ctx.caption:
return ctx.caption
else:
return ""
@ -199,43 +199,43 @@ def isArgInt(txt) -> list:
@app.on_message(filters.command(["q"]) & filters.reply)
@ratelimiter
async def msg_quotly_cmd(c: Client, m: Message):
if len(m.text.split()) > 1:
check_arg = isArgInt(m.command[1])
async def msg_quotly_cmd(self: Client, ctx: Message):
if len(ctx.text.split()) > 1:
check_arg = isArgInt(ctx.command[1])
if check_arg[0]:
if check_arg[1] < 2 or check_arg[1] > 10:
return await m.reply_text("Invalid range")
return await ctx.reply_msg("Invalid range", del_in=6)
try:
messages = [
i
for i in await c.get_messages(
chat_id=m.chat.id,
for i in await self.get_messages(
chat_id=ctx.chat.id,
message_ids=range(
m.reply_to_message.id,
m.reply_to_message.id + (check_arg[1] + 5),
ctx.reply_to_message.id,
ctx.reply_to_message.id + (check_arg[1] + 5),
),
replies=-1,
)
if not i.empty and not i.media
]
except Exception:
return await m.reply_text("🤷🏻‍♂️")
return await ctx.reply_text("🤷🏻‍♂️")
try:
make_quotly = await pyrogram_to_quotly(messages)
bio_sticker = BytesIO(make_quotly)
bio_sticker.name = "biosticker.webp"
return await m.reply_sticker(bio_sticker)
return await ctx.reply_sticker(bio_sticker)
except Exception:
return await m.reply_text("🤷🏻‍♂️")
return await ctx.reply_msg("🤷🏻‍♂️")
try:
messages_one = await c.get_messages(chat_id=m.chat.id, message_ids=m.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 m.reply_text("🤷🏻‍♂️")
return await ctx.reply_msg("🤷🏻‍♂️")
try:
make_quotly = await pyrogram_to_quotly(messages)
bio_sticker = BytesIO(make_quotly)
bio_sticker.name = "biosticker.webp"
return await m.reply_sticker(bio_sticker)
return await ctx.reply_sticker(bio_sticker)
except Exception as e:
return await m.reply_text(f"ERROR: {e}")
return await ctx.reply_msg(f"ERROR: {e}")

View file

@ -1,10 +1,10 @@
from pyrogram import filters
from pyrogram import Client, filters
from pyrogram.types import Message
from database.sangmata_db import *
from misskaty import app
from misskaty.core.decorator.permissions import adminsOnly
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.core.message_utils import kirimPesan
from misskaty.helper.localization import use_chat_lang
from misskaty.vars import COMMAND_HANDLER
@ -21,52 +21,52 @@ This feature inspired from SangMata Bot. I'm created simple detection to check u
group=3,
)
@use_chat_lang()
async def cek_mataa(_, m, strings):
if m.sender_chat or not await is_sangmata_on(m.chat.id):
async def cek_mataa(self: Client, ctx: Message, strings):
if ctx.sender_chat or not await is_sangmata_on(ctx.chat.id):
return
if not await cek_userdata(m.from_user.id):
return await add_userdata(m.from_user.id, m.from_user.username, m.from_user.first_name, m.from_user.last_name)
usernamebefore, first_name, lastname_before = await get_userdata(m.from_user.id)
if not await cek_userdata(ctx.from_user.id):
return await add_userdata(ctx.from_user.id, ctx.from_user.username, ctx.from_user.first_name, ctx.from_user.last_name)
usernamebefore, first_name, lastname_before = await get_userdata(ctx.from_user.id)
msg = ""
if usernamebefore != m.from_user.username or first_name != m.from_user.first_name or lastname_before != m.from_user.last_name:
msg += f"👀 <b>Mata MissKaty</b>\n\n🌞 User: {m.from_user.mention} [<code>{m.from_user.id}</code>]\n"
if usernamebefore != m.from_user.username:
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"@{m.from_user.username}" if m.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(m.from_user.id, m.from_user.username, m.from_user.first_name, m.from_user.last_name)
if first_name != m.from_user.first_name:
msg += strings("firstname_change_msg").format(bef=first_name, aft=m.from_user.first_name)
await add_userdata(m.from_user.id, m.from_user.username, m.from_user.first_name, m.from_user.last_name)
if lastname_before != m.from_user.last_name:
await add_userdata(ctx.from_user.id, ctx.from_user.username, ctx.from_user.first_name, 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)
await add_userdata(ctx.from_user.id, ctx.from_user.username, ctx.from_user.first_name, ctx.from_user.last_name)
if lastname_before != ctx.from_user.last_name:
lastname_before = lastname_before or strings("no_last_name")
lastname_after = m.from_user.last_name 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)
await add_userdata(m.from_user.id, m.from_user.username, m.from_user.first_name, m.from_user.last_name)
await add_userdata(ctx.from_user.id, ctx.from_user.username, ctx.from_user.first_name, ctx.from_user.last_name)
if msg != "":
await kirimPesan(m, msg, quote=True)
await ctx.reply_msg(msg, quote=True)
@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(_, m, strings):
if len(m.command) == 1:
return await kirimPesan(m, strings("set_sangmata_help").format(cmd=m.command[0]))
if m.command[1] == "on":
cekset = await is_sangmata_on(m.chat.id)
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)
if ctx.command[1] == "on":
cekset = await is_sangmata_on(ctx.chat.id)
if cekset:
await kirimPesan(m, strings("sangmata_already_on"))
await ctx.reply_msg(strings("sangmata_already_on"))
else:
await sangmata_on(m.chat.id)
await kirimPesan(m, strings("sangmata_enabled"))
elif m.command[1] == "off":
cekset = await is_sangmata_on(m.chat.id)
await sangmata_on(ctx.chat.id)
await ctx.reply_msg(strings("sangmata_enabled"))
elif ctx.command[1] == "off":
cekset = await is_sangmata_on(ctx.chat.id)
if not cekset:
await kirimPesan(m, strings("sangmata_already_off"))
await ctx.reply_msg(strings("sangmata_already_off"))
else:
await sangmata_off(m.chat.id)
await kirimPesan(m, strings("sangmata_disabled"))
await sangmata_off(ctx.chat.id)
await ctx.reply_msg(strings("sangmata_disabled"))
else:
await kirimPesan(m, strings("wrong_param"))
await ctx.reply_msg(strings("wrong_param"), del_in=6)

View file

@ -4,7 +4,8 @@
import html
import regex
from pyrogram import filters
from pyrogram import filters, Client
from pyrogram.types import Message
from pyrogram.errors import MessageEmpty
from misskaty import app
@ -13,8 +14,8 @@ from misskaty.core.decorator.ratelimiter import ratelimiter
@app.on_message(filters.regex(r"^s/(.+)?/(.+)?(/.+)?") & filters.reply)
@ratelimiter
async def sed(c, m):
exp = regex.split(r"(?<![^\\]\\)/", m.text)
async def sed(self: Client, ctx: Message):
exp = regex.split(r"(?<![^\\]\\)/", ctx.text)
pattern = exp[1]
replace_with = exp[2].replace(r"\/", "/")
flags = exp[3] if len(exp) > 3 else ""
@ -29,7 +30,7 @@ async def sed(c, m):
elif "s" in flags:
rflags = regex.S
text = m.reply_to_message.text or m.reply_to_message.caption
text = ctx.reply_to_message.text or ctx.reply_to_message.caption
if not text:
return
@ -37,17 +38,17 @@ async def sed(c, m):
try:
res = regex.sub(pattern, replace_with, text, count=count, flags=rflags, timeout=1)
except TimeoutError:
return await m.reply_text("Oops, your regex pattern has run for too long.")
return await ctx.reply_msg("Oops, your regex pattern has run for too long.")
except regex.error as e:
return await m.reply_text(str(e))
return await ctx.reply_msg(str(e))
else:
try:
await c.send_message(
m.chat.id,
await self.send_msg(
ctx.chat.id,
f"<pre>{html.escape(res)}</pre>",
reply_to_message_id=m.reply_to_message.id,
reply_to_message_id=ctx.reply_to_message.id,
)
except MessageEmpty:
return await m.reply_text("Please reply message to use this feature.")
return await ctx.reply_msg("Please reply message to use this feature.", del_in=5)
except Exception as e:
return await m.reply_text(f"ERROR: {str(e)}")
return await ctx.reply_msg(f"ERROR: {str(e)}")

View file

@ -6,13 +6,12 @@
* Copyright @YasirPedia All rights reserved
"""
import re
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message, CallbackQuery
from database.users_chats_db import db
from pyrogram import filters
from pyrogram import filters, Client
from pyrogram.errors import ChannelPrivate
from misskaty import app, BOT_USERNAME, HELPABLE, BOT_NAME
from misskaty.vars import COMMAND_HANDLER, LOG_CHANNEL
from misskaty.core.message_utils import *
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.helper import bot_sys_stats, paginate_modules
from misskaty.helper.localization import use_chat_lang
@ -67,47 +66,46 @@ keyboard = InlineKeyboardMarkup(
@app.on_message(filters.command("start", COMMAND_HANDLER))
@use_chat_lang()
async def start(_, message, strings):
if message.chat.type.value != "private":
if not await db.get_chat(message.chat.id):
async def start(self: Client, ctx: Message, strings):
if ctx.chat.type.value != "private":
if not await db.get_chat(ctx.chat.id):
try:
total = await app.get_chat_members_count(message.chat.id)
total = await app.get_chat_members_count(ctx.chat.id)
except ChannelPrivate:
return await message.chat.leave()
return await ctx.chat.leave()
await app.send_message(
LOG_CHANNEL,
strings("newgroup_log").format(jdl=message.chat.title, id=message.chat.id, c=total),
strings("newgroup_log").format(jdl=ctx.chat.title, id=ctx.chat.id, c=total),
)
await db.add_chat(message.chat.id, message.chat.title)
nama = message.from_user.mention if message.from_user else message.sender_chat.title
return await message.reply_photo(
await db.add_chat(ctx.chat.id, ctx.chat.title)
nama = ctx.from_user.mention if ctx.from_user else ctx.sender_chat.title
return await ctx.reply_photo(
photo="https://telegra.ph/file/90e9a448bc2f8b055b762.jpg",
caption=strings("start_msg").format(kamuh=nama),
reply_markup=keyboard,
)
if not await db.is_user_exist(message.from_user.id):
await db.add_user(message.from_user.id, message.from_user.first_name)
if not await db.is_user_exist(ctx.from_user.id):
await db.add_user(ctx.from_user.id, ctx.from_user.first_name)
await app.send_message(
LOG_CHANNEL,
strings("newuser_log").format(id=message.from_user.id, nm=message.from_user.mention),
strings("newuser_log").format(id=ctx.from_user.id, nm=ctx.from_user.mention),
)
if len(message.text.split()) > 1:
name = (message.text.split(None, 1)[1]).lower()
if len(ctx.text.split()) > 1:
name = (ctx.text.split(None, 1)[1]).lower()
if "_" in name:
module = name.split("_", 1)[1]
text = strings("help_name").format(mod=HELPABLE[module].__MODULE__) + HELPABLE[module].__HELP__
await kirimPesan(message, text, disable_web_page_preview=True)
await ctx.reply_msg(text, disable_web_page_preview=True)
elif name == "help":
text, keyb = await help_parser(message.from_user.first_name)
await kirimPesan(
message,
text, keyb = await help_parser(ctx.from_user.first_name)
await ctx.reply_msg(
text,
reply_markup=keyb,
)
else:
await message.reply_photo(
await ctx.reply_photo(
photo="https://telegra.ph/file/90e9a448bc2f8b055b762.jpg",
caption=home_text_pm,
reply_markup=home_keyboard_pm,
@ -116,38 +114,38 @@ async def start(_, message, strings):
@app.on_callback_query(filters.regex("bot_commands"))
@ratelimiter
async def commands_callbacc(_, CallbackQuery):
async def commands_callbacc(self: Client, CallbackQuery: CallbackQuery):
text, keyboard = await help_parser(CallbackQuery.from_user.mention)
await app.send_message(
CallbackQuery.message.chat.id,
text=text,
reply_markup=keyboard,
)
await hapusPesan(CallbackQuery.message)
await CallbackQuery.message.delete_msg()
@app.on_callback_query(filters.regex("stats_callback"))
@ratelimiter
async def stats_callbacc(_, CallbackQuery):
async def stats_callbacc(self: Client, cb: CallbackQuery):
text = await bot_sys_stats()
await app.answer_callback_query(CallbackQuery.id, text, show_alert=True)
await app.answer_callback_query(cb.id, text, show_alert=True)
@app.on_message(filters.command("help", COMMAND_HANDLER))
@ratelimiter
@use_chat_lang()
async def help_command(_, message, strings):
if message.chat.type.value != "private":
if not await db.get_chat(message.chat.id):
total = await app.get_chat_members_count(message.chat.id)
async def help_command(self: Client, ctx: Message, strings):
if ctx.chat.type.value != "private":
if not await db.get_chat(ctx.chat.id):
total = await app.get_chat_members_count(ctx.chat.id)
await app.send_message(
LOG_CHANNEL,
strings("newgroup_log").format(jdl=message.chat.title, id=message.chat.id, c=total),
strings("newgroup_log").format(jdl=ctx.chat.title, id=ctx.chat.id, c=total),
)
await db.add_chat(message.chat.id, message.chat.title)
if len(message.command) >= 2:
name = (message.text.split(None, 1)[1]).replace(" ", "_").lower()
await db.add_chat(ctx.chat.id, ctx.chat.title)
if len(ctx.command) >= 2:
name = (ctx.text.split(None, 1)[1]).replace(" ", "_").lower()
if str(name) in HELPABLE:
key = InlineKeyboardMarkup(
[
@ -159,39 +157,37 @@ async def help_command(_, message, strings):
],
]
)
await kirimPesan(
message,
await ctx.reply_msg(
strings("click_btn"),
reply_markup=key,
)
else:
await kirimPesan(message, strings("pm_detail"), reply_markup=keyboard)
await ctx.reply_msg(strings("pm_detail"), reply_markup=keyboard)
else:
await kirimPesan(message, strings("pm_detail"), reply_markup=keyboard)
await ctx.reply_msg(strings("pm_detail"), reply_markup=keyboard)
else:
if not await db.is_user_exist(message.from_user.id):
await db.add_user(message.from_user.id, message.from_user.first_name)
if not await db.is_user_exist(ctx.from_user.id):
await db.add_user(ctx.from_user.id, ctx.from_user.first_name)
await app.send_message(
LOG_CHANNEL,
strings("newuser_log").format(id=message.from_user.id, nm=message.from_user.mention),
strings("newuser_log").format(id=ctx.from_user.id, nm=ctx.from_user.mention),
)
if len(message.command) >= 2:
name = (message.text.split(None, 1)[1]).replace(" ", "_").lower()
if len(ctx.command) >= 2:
name = (ctx.text.split(None, 1)[1]).replace(" ", "_").lower()
if str(name) in HELPABLE:
text = strings("help_name").format(mod=HELPABLE[name].__MODULE__) + HELPABLE[name].__HELP__
await kirimPesan(message, text, disable_web_page_preview=True)
await ctx.reply_msg(text, disable_web_page_preview=True)
else:
text, help_keyboard = await help_parser(message.from_user.first_name)
await kirimPesan(
message,
text, help_keyboard = await help_parser(ctx.from_user.first_name)
await ctx.reply_msg(
text,
reply_markup=help_keyboard,
disable_web_page_preview=True,
)
else:
text, help_keyboard = await help_parser(message.from_user.first_name)
await kirimPesan(message, text, reply_markup=help_keyboard, disable_web_page_preview=True)
text, help_keyboard = await help_parser(ctx.from_user.first_name)
await ctx.reply_msg(text, reply_markup=help_keyboard, disable_web_page_preview=True)
async def help_parser(name, keyboard=None):
@ -214,35 +210,33 @@ If you want give coffee to my owner you can send /donate command for more info.
@app.on_callback_query(filters.regex(r"help_(.*?)"))
@ratelimiter
@use_chat_lang()
async def help_button(client, query, strings):
async def help_button(self: Client, query: CallbackQuery, strings):
home_match = re.match(r"help_home\((.+?)\)", query.data)
mod_match = re.match(r"help_module\((.+?)\)", query.data)
prev_match = re.match(r"help_prev\((.+?)\)", query.data)
next_match = re.match(r"help_next\((.+?)\)", query.data)
back_match = re.match(r"help_back", query.data)
create_match = re.match(r"help_create", query.data)
top_text = strings("help_txt").format(kamuh=query.from_user.first_name, bot=client.me.first_name)
top_text = strings("help_txt").format(kamuh=query.from_user.first_name, bot=self.me.first_name)
if mod_match:
module = mod_match[1].replace(" ", "_")
text = strings("help_name").format(mod=HELPABLE[module].__MODULE__) + HELPABLE[module].__HELP__
await editPesan(
query.message,
await query.message.edit_msg(
text=text,
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(strings("back_btn"), callback_data="help_back")]]),
disable_web_page_preview=True,
)
elif home_match:
await app.send_message(
await app.send_msg(
query.from_user.id,
text=home_text_pm,
reply_markup=home_keyboard_pm,
)
await hapusPesan(query.message)
await query.message.delete_msg()
elif prev_match:
curr_page = int(prev_match[1])
await editPesan(
query.message,
await query.message.edit_msg(
text=top_text,
reply_markup=InlineKeyboardMarkup(paginate_modules(curr_page - 1, HELPABLE, "help")),
disable_web_page_preview=True,
@ -250,16 +244,14 @@ async def help_button(client, query, strings):
elif next_match:
next_page = int(next_match[1])
await editPesan(
query.message,
await query.message.edit_msg(
text=top_text,
reply_markup=InlineKeyboardMarkup(paginate_modules(next_page + 1, HELPABLE, "help")),
disable_web_page_preview=True,
)
elif back_match:
await editPesan(
query.message,
await query.message.edit_msg(
text=top_text,
reply_markup=InlineKeyboardMarkup(paginate_modules(0, HELPABLE, "help")),
disable_web_page_preview=True,
@ -267,11 +259,10 @@ async def help_button(client, query, strings):
elif create_match:
text, keyboard = await help_parser(query)
await editPesan(
query.message,
await query.message.edit_msg(
text=text,
reply_markup=keyboard,
disable_web_page_preview=True,
)
return await client.answer_callback_query(query.id)
await self.answer_callback_query(query.id)

View file

@ -5,13 +5,13 @@ import shutil
import tempfile
from PIL import Image
from pyrogram import emoji, filters, enums
from pyrogram import emoji, filters, enums, Client
from pyrogram.errors import BadRequest, PeerIdInvalid, StickersetInvalid
from pyrogram.file_id import FileId
from pyrogram.raw.functions.messages import GetStickerSet, SendMedia
from pyrogram.raw.functions.stickers import AddStickerToSet, CreateStickerSet, RemoveStickerFromSet
from pyrogram.raw.types import DocumentAttributeFilename, InputDocument, InputMediaUploadedDocument, InputStickerSetItem, InputStickerSetShortName
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from misskaty import BOT_USERNAME, app
from misskaty.core.decorator.ratelimiter import ratelimiter
@ -45,61 +45,61 @@ SUPPORTED_TYPES = ["jpeg", "png", "webp"]
@app.on_message(filters.command(["getsticker"], COMMAND_HANDLER))
@ratelimiter
@use_chat_lang()
async def getsticker_(c, m, strings):
if sticker := m.reply_to_message.sticker:
async def getsticker_(self: Client, ctx: Message, strings):
if sticker := ctx.reply_to_message.sticker:
if sticker.is_animated:
await m.reply_text(strings("no_anim_stick"))
await ctx.reply_msg(strings("no_anim_stick"))
else:
with tempfile.TemporaryDirectory() as tempdir:
path = os.path.join(tempdir, "getsticker")
sticker_file = await c.download_media(
message=m.reply_to_message,
sticker_file = await self.download_media(
message=ctx.reply_to_message,
file_name=f"{path}/{sticker.set_name}.png",
)
await m.reply_to_message.reply_document(
await self.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}",
)
shutil.rmtree(tempdir, ignore_errors=True)
else:
await m.reply_text(strings("not_sticker"))
await ctx.reply_msg(strings("not_sticker"))
@app.on_message(filters.command("stickerid", COMMAND_HANDLER) & filters.reply)
@ratelimiter
async def getstickerid(c, m):
if m.reply_to_message.sticker:
await m.reply_text("The ID of this sticker is: <code>{stickerid}</code>".format(stickerid=m.reply_to_message.sticker.file_id))
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))
@app.on_message(filters.command("unkang", COMMAND_HANDLER) & filters.reply)
@ratelimiter
@use_chat_lang()
async def getstickerid(c, m, strings):
if m.reply_to_message.sticker:
pp = await m.reply_text(strings("unkang_msg"))
async def getstickerid(self: Client, ctx: Message, strings):
if ctx.reply_to_message.sticker:
pp = await ctx.reply_msg(strings("unkang_msg"))
try:
decoded = FileId.decode(m.reply_to_message.sticker.file_id)
decoded = FileId.decode(ctx.reply_to_message.sticker.file_id)
sticker = InputDocument(
id=decoded.media_id,
access_hash=decoded.access_hash,
file_reference=decoded.file_reference,
)
await app.invoke(RemoveStickerFromSet(sticker=sticker))
await pp.edit(strings("unkang_success"))
await pp.edit_msg(strings("unkang_success"))
except Exception as e:
await pp.edit(strings("unkang_error").format(e=e))
await pp.edit_msg(strings("unkang_error").format(e=e))
else:
await m.reply_text(strings("unkang_help").format(c=c.me.username))
await ctx.reply_msg(strings("unkang_help").format(c=self.me.username), del_in=6)
@app.on_message(filters.command(["curi", "kang"], COMMAND_HANDLER))
@ratelimiter
@use_chat_lang()
async def kang_sticker(c, m, strings):
if not m.from_user:
return await m.reply_text(strings("anon_warn"))
prog_msg = await m.reply_text(strings("kang_msg"))
async def kang_sticker(self: Client, ctx: Message, strings):
if not ctx.from_user:
return await ctx.reply_msg(strings("anon_warn"), del_in=6)
prog_msg = await ctx.reply_msg(strings("kang_msg"))
sticker_emoji = "🤔"
packnum = 0
packname_found = False
@ -107,8 +107,8 @@ async def kang_sticker(c, m, strings):
animated = False
videos = False
convert = False
reply = m.reply_to_message
user = await c.resolve_peer(m.from_user.username or m.from_user.id)
reply = ctx.reply_to_message
user = await self.resolve_peer(ctx.from_user.username or ctx.from_user.id)
if reply and reply.media:
if reply.photo:
@ -135,7 +135,7 @@ async def kang_sticker(c, m, strings):
animated = True
elif reply.sticker:
if not reply.sticker.file_name:
return await prog_msg.edit_text(strings("stick_no_name"))
return await prog_msg.edit_msg(strings("stick_no_name"))
if reply.sticker.emoji:
sticker_emoji = reply.sticker.emoji
animated = reply.sticker.is_animated
@ -145,29 +145,29 @@ async def kang_sticker(c, m, strings):
elif not reply.sticker.file_name.endswith(".tgs"):
resize = True
else:
return await prog_msg.edit_text()
return await prog_msg.edit_msg()
pack_prefix = "anim" if animated else "vid" if videos else "a"
packname = f"{pack_prefix}_{m.from_user.id}_by_{c.me.username}"
packname = f"{pack_prefix}_{ctx.from_user.id}_by_{self.me.username}"
if len(m.command) > 1 and m.command[1].isdigit() and int(m.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 = m.command.pop(1)
packname = f"{pack_prefix}{packnum}_{m.from_user.id}_by_{c.me.username}"
if len(m.command) > 1:
packnum = ctx.command.pop(1)
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(m.command[1:])))) or sticker_emoji
filename = await c.download_media(m.reply_to_message)
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
await prog_msg.delete()
return
elif m.entities and len(m.entities) > 1:
elif ctx.entities and len(ctx.entities) > 1:
pack_prefix = "a"
filename = "sticker.png"
packname = f"c{m.from_user.id}_by_{c.me.username}"
packname = f"c{ctx.from_user.id}_by_{self.me.username}"
img_url = next(
(m.text[y.offset : (y.offset + y.length)] for y in m.entities if y.type == "url"),
(ctx.text[y.offset : (y.offset + y.length)] for y in ctx.entities if y.type == "url"),
None,
)
@ -180,28 +180,28 @@ async def kang_sticker(c, m, strings):
with open(filename, mode="wb") as f:
f.write(r.read())
except Exception as r_e:
return await prog_msg.edit_text(f"{r_e.__class__.__name__} : {r_e}")
if len(m.command) > 2:
return await prog_msg.edit_msg(f"{r_e.__class__.__name__} : {r_e}")
if len(ctx.command) > 2:
# m.command[1] is image_url
if m.command[2].isdigit() and int(m.command[2]) > 0:
packnum = m.command.pop(2)
packname = f"a{packnum}_{m.from_user.id}_by_{c.me.username}"
if len(m.command) > 2:
sticker_emoji = "".join(set(EMOJI_PATTERN.findall("".join(m.command[2:])))) or sticker_emoji
if ctx.command[2].isdigit() and int(ctx.command[2]) > 0:
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
resize = True
else:
return await prog_msg.edit_text(strings("kang_help"))
return await prog_msg.edit_msg(strings("kang_help"), del_in=5)
try:
if resize:
filename = resize_image(filename)
elif convert:
filename = await convert_video(filename)
if filename is False:
return await prog_msg.edit_text("Error")
return await prog_msg.edit_msg("Error", del_in=6)
max_stickers = 50 if animated else 120
while not packname_found:
try:
stickerset = await c.invoke(
stickerset = await self.invoke(
GetStickerSet(
stickerset=InputStickerSetShortName(short_name=packname),
hash=0,
@ -209,29 +209,29 @@ async def kang_sticker(c, m, strings):
)
if stickerset.set.count >= max_stickers:
packnum += 1
packname = f"{pack_prefix}_{packnum}_{m.from_user.id}_by_{c.me.username}"
packname = f"{pack_prefix}_{packnum}_{ctx.from_user.id}_by_{self.me.username}"
else:
packname_found = True
except StickersetInvalid:
break
file = await c.save_file(filename)
media = await c.invoke(
file = await self.save_file(filename)
media = await self.invoke(
SendMedia(
peer=(await c.resolve_peer(LOG_CHANNEL)),
peer=(await self.resolve_peer(LOG_CHANNEL)),
media=InputMediaUploadedDocument(
file=file,
mime_type=c.guess_mime_type(filename),
mime_type=self.guess_mime_type(filename),
attributes=[DocumentAttributeFilename(file_name=filename)],
),
message=f"#Sticker kang by UserID -> {m.from_user.id}",
random_id=c.rnd_id(),
message=f"#Sticker kang by UserID -> {ctx.from_user.id}",
random_id=self.rnd_id(),
),
)
msg_ = media.updates[-1].message
stkr_file = msg_.media.document
if packname_found:
await prog_msg.edit_text(strings("exist_pack"))
await c.invoke(
await prog_msg.edit_msg(strings("exist_pack"))
await self.invoke(
AddStickerToSet(
stickerset=InputStickerSetShortName(short_name=packname),
sticker=InputStickerSetItem(
@ -245,8 +245,8 @@ async def kang_sticker(c, m, strings):
)
)
else:
await prog_msg.edit_text(strings("new_packs"))
stkr_title = f"{m.from_user.first_name}'s"
await prog_msg.edit_msg(strings("new_packs"))
stkr_title = f"{ctx.from_user.first_name}'s"
if animated:
stkr_title += "AnimPack"
elif videos:
@ -254,7 +254,7 @@ async def kang_sticker(c, m, strings):
if packnum != 0:
stkr_title += f" v{packnum}"
try:
await c.invoke(
await self.invoke(
CreateStickerSet(
user_id=user,
title=stkr_title,
@ -274,14 +274,14 @@ async def kang_sticker(c, m, strings):
)
)
except PeerIdInvalid:
return await prog_msg.edit_text(
return await prog_msg.edit_msg(
strings("please_start_msg"),
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
strings("click_me"),
url=f"https://t.me/{c.me.username}?start",
url=f"https://t.me/{self.me.username}?start",
)
]
]
@ -289,9 +289,9 @@ async def kang_sticker(c, m, strings):
)
except BadRequest:
return await prog_msg.edit_text(strings("pack_full"))
return await prog_msg.edit_msg(strings("pack_full"))
except Exception as all_e:
await prog_msg.edit_text(f"{all_e.__class__.__name__} : {all_e}")
await prog_msg.edit_msg(f"{all_e.__class__.__name__} : {all_e}")
else:
markup = InlineKeyboardMarkup(
[
@ -303,12 +303,12 @@ async def kang_sticker(c, m, strings):
]
]
)
await prog_msg.edit_text(
await prog_msg.edit_msg(
strings("kang_success").format(emot=sticker_emoji),
reply_markup=markup,
)
# Cleanup
await c.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

@ -12,11 +12,10 @@ from re import split as ngesplit
from time import perf_counter, time
from urllib.parse import unquote
from pyrogram import filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from pyrogram import filters, Client
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message, CallbackQuery
from misskaty import app
from misskaty.core.message_utils import *
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.core.decorator.errors import capture_err
from misskaty.helper.pyro_progress import progress_for_pyrogram
@ -65,13 +64,12 @@ def get_subname(lang, url, format):
@app.on_message(filters.command(["ceksub", "extractmedia"], COMMAND_HANDLER))
@ratelimiter
@use_chat_lang()
async def ceksub(_, m, strings):
cmd = m.text.split(" ", 1)
if len(cmd) == 1:
return await kirimPesan(m, strings("sub_extr_help").format(cmd=m.command[0]), quote=True)
link = cmd[1]
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)
link = ctx.command[1]
start_time = perf_counter()
pesan = await kirimPesan(m, strings("progress_str"), quote=True)
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]
details = json.loads(res)
@ -99,38 +97,37 @@ async def ceksub(_, m, strings):
)
end_time = perf_counter()
timelog = "{:.2f}".format(end_time - start_time) + strings("val_sec")
buttons.append([InlineKeyboardButton(strings("cancel_btn"), f"close#{m.from_user.id}")])
await editPesan(
pesan,
buttons.append([InlineKeyboardButton(strings("cancel_btn"), f"close#{ctx.from_user.id}")])
await pesan.edit_msg(
strings("press_btn_msg").format(timelog=timelog),
reply_markup=InlineKeyboardMarkup(buttons),
)
except:
await editPesan(pesan, strings("fail_extr_media"))
await pesan.edit_msg(strings("fail_extr_media"))
@app.on_message(filters.command(["converttosrt"], COMMAND_HANDLER))
@capture_err
@ratelimiter
@use_chat_lang()
async def convertsrt(c, m, strings):
reply = m.reply_to_message
async def convertsrt(self: Client, ctx: Message, strings):
reply = ctx.reply_to_message
if not reply and reply.document and (reply.document.file_name.endswith(".vtt") or reply.document.file_name.endswith(".ass")):
return await kirimPesan(m, strings("conv_sub_help").format(cmd=m.command[0]))
msg = await kirimPesan(m, strings("convert_str"), quote=True)
return await ctx.reply_msg(strings("conv_sub_help").format(cmd=ctx.command[0]), del_in=5)
msg = await ctx.reply_msg(strings("convert_str"), quote=True)
dl = await reply.download()
filename = dl.split("/", 3)[3]
LOGGER.info(f"ConvertSub: {filename} by {m.from_user.first_name} [{m.from_user.id}]")
LOGGER.info(f"ConvertSub: {filename} by {ctx.from_user.first_name} [{ctx.from_user.id}]")
(await shell_exec(f"mediaextract -i '{dl}' '{filename}.srt'"))[0]
c_time = time()
await m.reply_document(
await ctx.reply_document(
f"{filename}.srt",
caption=strings("capt_conv_sub").format(nf=filename, bot=c.me.username),
caption=strings("capt_conv_sub").format(nf=filename, bot=self.me.username),
thumb="assets/thumb.jpg",
progress=progress_for_pyrogram,
progress_args=(strings("up_str"), msg, c_time),
)
await hapusPesan(msg)
await msg.delete_msg()
try:
os.remove(dl)
os.remove(f"{filename}.srt")
@ -141,7 +138,7 @@ async def convertsrt(c, m, strings):
@app.on_callback_query(filters.regex(r"^streamextract#"))
@ratelimiter
@use_chat_lang()
async def stream_extract(bot, update, strings):
async def stream_extract(self: Client, update: CallbackQuery, strings):
cb_data = update.data
usr = update.message.reply_to_message
if update.from_user.id != usr.from_user.id:
@ -151,7 +148,7 @@ async def stream_extract(bot, update, strings):
link = update.message.reply_to_message.command[1]
except:
return await update.answer(strings("invalid_cb"), True)
await editPesan(update.message, strings("progress_str"))
await update.message.edit_msg(strings("progress_str"))
if codec == "aac":
format = "aac"
elif codec == "mp3":
@ -170,13 +167,13 @@ async def stream_extract(bot, update, strings):
c_time = time()
await update.message.reply_document(
namafile,
caption=strings("capt_extr_sub").format(nf=namafile, bot=bot.me.username, timelog=timelog),
caption=strings("capt_extr_sub").format(nf=namafile, bot=self.me.username, timelog=timelog),
reply_to_message_id=usr.id,
thumb="assets/thumb.jpg",
progress=progress_for_pyrogram,
progress_args=(strings("up_str"), update.message, c_time),
)
await hapusPesan(update.message)
await update.message.delete_msg()
try:
os.remove(namafile)
except:
@ -186,4 +183,4 @@ async def stream_extract(bot, update, strings):
os.remove(namafile)
except:
pass
await editPesan(update.message, strings("fail_extr_sub").format(link=link, e=e))
await update.message.edit_msg(strings("fail_extr_sub").format(link=link, e=e))

View file

@ -1,14 +1,16 @@
import logging, os
import asyncio
import logging
import os
import cfscrape
from bs4 import BeautifulSoup
from misskaty.helper.subscene_helper import down_page
from pykeyboard import InlineButton, InlineKeyboard
from pyrogram import filters
from pyrogram import Client, filters
from pyrogram.types import CallbackQuery, Message
from misskaty import app
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.core.message_utils import *
from misskaty.helper.subscene_helper import down_page
from misskaty.vars import COMMAND_HANDLER
from .web_scraper import split_arr
@ -51,7 +53,7 @@ async def getTitleSub(msg, kueri, CurrentPage, user):
subResult = "".join(i for i in subResult if i not in "[]")
return subResult, PageLen, extractbtn1, extractbtn2
except (IndexError, KeyError):
await editPesan(msg, "Sorry could not find any matching results!")
await msg.edit_msg("Sorry could not find any matching results!", del_in=5)
return None, 0, None
@ -90,36 +92,35 @@ async def getListSub(msg, link, CurrentPage, user):
subResult = "".join(i for i in subResult if i not in "[]")
return subResult, PageLen, extractbtn1, extractbtn2
except (IndexError, KeyError):
await editPesan(msg, "Sorry could not find any matching results!")
await msg.edit_msg("Sorry could not find any matching results!")
return None, 0, None
# Subscene CMD
@app.on_message(filters.command(["subscene"], COMMAND_HANDLER))
@ratelimiter
async def subsceneCMD(client, message):
kueri = " ".join(message.command[1:])
if not kueri:
return await kirimPesan(message, f" Please add query after CMD!\nEx: <code>/{message.command[0]} Jurassic World</code>")
pesan = await kirimPesan(message, "⏳ Please wait, getting data from subscene..", quote=True)
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)
CurrentPage = 1
subres, PageLen, btn1, btn2 = await getTitleSub(pesan, kueri, CurrentPage, message.from_user.id)
subres, PageLen, btn1, btn2 = await getTitleSub(pesan, ctx.input, CurrentPage, ctx.from_user.id)
if not subres:
return
keyboard = InlineKeyboard()
keyboard.paginate(PageLen, CurrentPage, "subscenepage#{number}" + f"#{pesan.id}#{message.from_user.id}")
keyboard.paginate(PageLen, CurrentPage, "subscenepage#{number}" + f"#{pesan.id}#{ctx.from_user.id}")
keyboard.row(InlineButton("👇 Extract Data ", "Hmmm"))
keyboard.row(*btn1)
if btn2:
keyboard.row(*btn2)
keyboard.row(InlineButton("❌ Close", f"close#{message.from_user.id}"))
await editPesan(pesan, subres, disable_web_page_preview=True, reply_markup=keyboard)
keyboard.row(InlineButton("❌ Close", f"close#{ctx.from_user.id}"))
await pesan.edit_msg(subres, disable_web_page_preview=True, reply_markup=keyboard)
# Callback list title
@app.on_callback_query(filters.create(lambda _, __, query: "subscenepage#" in query.data))
@ratelimiter
async def subpage_callback(client, callback_query):
async def subpage_callback(self: Client, callback_query: CallbackQuery):
if callback_query.from_user.id != int(callback_query.data.split("#")[3]):
return await callback_query.answer("Not yours..", True)
message_id = int(callback_query.data.split("#")[2])
@ -129,7 +130,7 @@ async def subpage_callback(client, callback_query):
except KeyError:
await callback_query.answer("Invalid callback data, please send CMD again..")
await asyncio.sleep(3)
return await callback_query.message.delete()
return await callback_query.message.delete_msg()
try:
subres, PageLen, btn1, btn2 = await getTitleSub(callback_query.message, kueri, CurrentPage, callback_query.from_user.id)
@ -143,13 +144,13 @@ async def subpage_callback(client, callback_query):
if btn2:
keyboard.row(*btn2)
keyboard.row(InlineButton("❌ Close", f"close#{callback_query.from_user.id}"))
await editPesan(callback_query.message, 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
@app.on_callback_query(filters.create(lambda _, __, query: "sublist#" in query.data))
@ratelimiter
async def subdlpage_callback(client, callback_query):
async def subdlpage_callback(self: Client, callback_query: CallbackQuery):
if callback_query.from_user.id != int(callback_query.data.split("#")[4]):
return await callback_query.answer("Not yours..", True)
idlink = int(callback_query.data.split("#")[2])
@ -160,7 +161,7 @@ async def subdlpage_callback(client, callback_query):
except KeyError:
await callback_query.answer("Invalid callback data, please send CMD again..")
await asyncio.sleep(3)
return await callback_query.message.delete()
return await callback_query.message.delete_msg()
try:
subres, PageLen, btn1, btn2 = await getListSub(callback_query.message, link, CurrentPage, callback_query.from_user.id)
@ -174,13 +175,13 @@ async def subdlpage_callback(client, callback_query):
if btn2:
keyboard.row(*btn2)
keyboard.row(InlineButton("❌ Close", f"close#{callback_query.from_user.id}"))
await editPesan(callback_query.message, 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))
@ratelimiter
async def dlsub_callback(client, callback_query):
async def dlsub_callback(self: Client, callback_query: CallbackQuery):
if callback_query.from_user.id != int(callback_query.data.split("#")[4]):
return await callback_query.answer("Not yours..", True)
idlink = int(callback_query.data.split("#")[2])
@ -192,7 +193,7 @@ async def dlsub_callback(client, callback_query):
except KeyError:
await callback_query.answer("Invalid callback data, please send CMD again..")
await asyncio.sleep(3)
return await callback_query.message.delete()
return await callback_query.message.delete_msg()
scraper = cfscrape.create_scraper()
res = await down_page(link)
dl = scraper.get(res.get("download_url"))

View file

@ -1,18 +1,19 @@
# This plugin to learn session using pyrogram
from pyrogram import filters
from pyrogram import filters, Client
from pyrogram.types import Message
from misskaty import app
from misskaty.vars import COMMAND_HANDLER
@app.on_message(filters.command(["session"], COMMAND_HANDLER))
async def session(_, message):
if not message.from_user:
async def session(self: Client, ctx: Message):
if not ctx.from_user:
return
nama = await message.chat.ask("Ketik nama kamu:")
umur = await message.chat.ask("Ketik umur kamu")
alamat = await message.chat.ask("Ketik alamat kamu:")
await app.send_message(
message.chat.id,
nama = await ctx.chat.ask("Ketik nama kamu:")
umur = await ctx.chat.ask("Ketik umur kamu")
alamat = await ctx.chat.ask("Ketik alamat kamu:")
await app.send_msg(
ctx.chat.id,
f"Nama Kamu Adalah: {nama.text}\nUmur Kamu Adalah: {umur.text}\nAlamat Kamu Adalah: {alamat.text}",
)

View file

@ -1,10 +1,10 @@
import asyncio
from pykeyboard import InlineKeyboard
from pyrogram import filters
from pyrogram import Client, filters
from pyrogram.types import Message, CallbackQuery
from misskaty import app
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.helper.http import http
from misskaty import app
from misskaty.vars import COMMAND_HANDLER
@ -12,36 +12,26 @@ async def getData(chat_id, message_id, GetWord, CurrentPage):
UDJson = (await http.get(f"https://api.urbandictionary.com/v0/define?term={GetWord}")).json()
if "list" not in UDJson:
CNMessage = await app.send_message(chat_id=chat_id, reply_to_message_id=message_id, text=(f"Word: {GetWord}\n" "Results: Sorry could not find any matching results!"))
await asyncio.sleep(5)
await CNMessage.delete()
return
return await app.send_msg(chat_id=chat_id, reply_to_message_id=message_id, text=f"Word: {GetWord}\nResults: Sorry could not find any matching results!", del_in=5)
try:
index = int(CurrentPage - 1)
PageLen = len(UDJson["list"])
UDReasult = f"**Definition of {GetWord}**\n" f"{UDJson['list'][index]['definition']}\n\n" "**📌 Examples**\n" f"__{UDJson['list'][index]['example']}__"
UDFReasult = "".join(i for i in UDReasult if i not in "[]")
return (UDFReasult, PageLen)
except IndexError or KeyError:
CNMessage = await app.send_message(chat_id=chat_id, reply_to_message_id=message_id, text=(f"Word: {GetWord}\n" "Results: Sorry could not find any matching results!"))
await asyncio.sleep(5)
await CNMessage.delete()
await app.send_msg(chat_id=chat_id, reply_to_message_id=message_id, text=f"Word: {GetWord}\nResults: Sorry could not find any matching results!", del_in=5)
@app.on_message(filters.command(["ud"], COMMAND_HANDLER))
@ratelimiter
async def urbanDictionary(client, message):
if not message.from_user:
return
message_id = message.id
chat_id = message.chat.id
GetWord = " ".join(message.command[1:])
async def urbanDictionary(self: Client, ctx: Message):
message_id = ctx.id
chat_id = ctx.chat.id
GetWord = " ".join(ctx.command[1:])
if not GetWord:
message = await message.chat.ask("Now give any word for query!", identifier=(message.from_user.id, message.from_user.id, None))
message = await ctx.chat.ask("Now give any word for query!", identifier=(ctx.from_user.id, ctx.from_user.id, None))
GetWord = message.text
CurrentPage = 1
@ -49,12 +39,12 @@ async def urbanDictionary(client, message):
keyboard = InlineKeyboard()
keyboard.paginate(PageLen, CurrentPage, "pagination_urban#{number}" + f"#{GetWord}")
await message.reply(text=f"{UDReasult}", reply_markup=keyboard)
await ctx.reply_msg(text=f"{UDReasult}", reply_markup=keyboard)
@app.on_callback_query(filters.create(lambda _, __, query: "pagination_urban#" in query.data))
@ratelimiter
async def ud_callback(client, callback_query):
async def ud_callback(self: Client, callback_query: CallbackQuery):
message_id = callback_query.message.id
chat_id = callback_query.message.chat.id
CurrentPage = int(callback_query.data.split("#")[1])
@ -67,4 +57,4 @@ async def ud_callback(client, callback_query):
keyboard = InlineKeyboard()
keyboard.paginate(PageLen, CurrentPage, "pagination_urban#{number}" + f"#{GetWord}")
await app.edit_message_text(chat_id=chat_id, message_id=message_id, text=UDReasult, reply_markup=keyboard)
await app.edit_msg(chat_id=chat_id, message_id=message_id, text=UDReasult, reply_markup=keyboard)

View file

@ -8,14 +8,15 @@ import re
import logging
from bs4 import BeautifulSoup
from pykeyboard import InlineKeyboard, InlineButton
from pyrogram import filters
from pyrogram import filters, Client
from pyrogram.types import Message
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.helper.http import http
from misskaty.helper.localization import use_chat_lang
from misskaty.helper.kuso_utils import Kusonime
from misskaty import app
from misskaty.vars import COMMAND_HANDLER
from misskaty.core.message_utils import *
__MODULE__ = "WebScraper"
__HELP__ = """
@ -52,7 +53,7 @@ async def getDataTerbit21(msg, kueri, CurrentPage, strings):
if not SCRAP_DICT.get(msg.id):
terbitjson = (await http.get(f"https://yasirapi.eu.org/terbit21?q={kueri}")).json() if kueri else (await http.get("https://yasirapi.eu.org/terbit21")).json()
if not terbitjson.get("result"):
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, None
SCRAP_DICT[msg.id] = [split_arr(terbitjson["result"], 6), kueri]
try:
@ -69,7 +70,7 @@ async def getDataTerbit21(msg, kueri, CurrentPage, strings):
TerbitRes = "".join(i for i in TerbitRes if i not in "[]")
return TerbitRes, PageLen
except (IndexError, KeyError):
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, None
@ -78,7 +79,7 @@ async def getDatalk21(msg, kueri, CurrentPage, strings):
if not SCRAP_DICT.get(msg.id):
lk21json = (await http.get(f"https://yasirapi.eu.org/lk21?q={kueri}")).json() if kueri else (await http.get("https://yasirapi.eu.org/lk21")).json()
if not lk21json.get("result"):
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, None
SCRAP_DICT[msg.id] = [split_arr(lk21json["result"], 6), kueri]
try:
@ -95,7 +96,7 @@ async def getDatalk21(msg, kueri, CurrentPage, strings):
lkResult = "".join(i for i in lkResult if i not in "[]")
return lkResult, PageLen
except (IndexError, KeyError):
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, None
@ -104,7 +105,7 @@ async def getDataPahe(msg, kueri, CurrentPage, strings):
if not SCRAP_DICT.get(msg.id):
pahejson = (await http.get(f"https://yasirapi.eu.org/pahe?q={kueri}")).json()
if not pahejson.get("result"):
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, None
SCRAP_DICT[msg.id] = [split_arr(pahejson["result"], 6), kueri]
try:
@ -117,7 +118,7 @@ async def getDataPahe(msg, kueri, CurrentPage, strings):
paheResult = "".join(i for i in paheResult if i not in "[]")
return paheResult, PageLen
except (IndexError, KeyError):
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, None
@ -133,7 +134,7 @@ async def getDataKuso(msg, kueri, CurrentPage, user, strings):
link = ress["href"]
kusodata.append({"title": title, "link": link})
if not kusodata:
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, 0, None, None
SCRAP_DICT[msg.id] = [split_arr(kusodata, 10), kueri]
try:
@ -152,7 +153,7 @@ async def getDataKuso(msg, kueri, CurrentPage, user, strings):
kusoResult = "".join(i for i in kusoResult if i not in "[]")
return kusoResult, PageLen, extractbtn1, extractbtn2
except (IndexError, KeyError):
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, 0, None, None
@ -170,7 +171,7 @@ async def getDataMovieku(msg, kueri, CurrentPage, strings):
typee = typ.strip() if typ.strip() != "" else "~"
moviekudata.append({"judul": judul, "link": link, "type": typee})
if not moviekudata:
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, None
SCRAP_DICT[msg.id] = [split_arr(moviekudata, 6), kueri]
try:
@ -183,7 +184,7 @@ async def getDataMovieku(msg, kueri, CurrentPage, strings):
moviekuResult = "".join(i for i in moviekuResult if i not in "[]")
return moviekuResult, PageLen
except (IndexError, KeyError):
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, None
@ -196,9 +197,9 @@ async def getDataSavefilm21(msg, kueri, CurrentPage, user, strings):
entry = text.find_all(class_="entry-header")
if "Tidak Ditemukan" in entry[0].text:
if not kueri:
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
else:
await editPesan(msg, strings("no_result_w_query").format(kueri=kueri))
await msg.edit_msg(strings("no_result_w_query").format(kueri=kueri), del_in=5)
return None, 0, None
for i in entry:
genre = i.find(class_="gmr-movie-on").text
@ -218,7 +219,7 @@ async def getDataSavefilm21(msg, kueri, CurrentPage, user, strings):
sfResult = "".join(i for i in sfResult if i not in "[]")
return sfResult, PageLen, extractbtn
except (IndexError, KeyError):
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, 0, None
@ -235,7 +236,7 @@ async def getDataLendrive(msg, kueri, CurrentPage, user, strings):
kualitas = o.find(class_="typez TV").text if o.find(class_="typez TV") else o.find(class_="typez BD")
lenddata.append({"judul": title, "link": link, "quality": kualitas, "status": status})
if not lenddata:
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, 0, None
SCRAP_DICT[msg.id] = [split_arr(lenddata, 6), kueri]
try:
@ -250,7 +251,7 @@ async def getDataLendrive(msg, kueri, CurrentPage, user, strings):
lenddataResult = "".join(i for i in lenddataResult if i not in "[]")
return lenddataResult, PageLen, extractbtn
except (IndexError, KeyError):
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, 0, None
@ -270,7 +271,7 @@ async def getDataMelong(msg, kueri, CurrentPage, user, strings):
quality = "N/A"
melongdata.append({"judul": title, "link": url, "quality": quality})
if not melongdata:
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, 0, None
SCRAP_DICT[msg.id] = [split_arr(melongdata, 6), kueri]
try:
@ -285,7 +286,7 @@ async def getDataMelong(msg, kueri, CurrentPage, user, strings):
melongResult = "".join(i for i in melongResult if i not in "[]")
return melongResult, PageLen, extractbtn
except (IndexError, KeyError):
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, 0, None
@ -297,9 +298,9 @@ async def getDataGomov(msg, kueri, CurrentPage, user, strings):
entry = text.find_all(class_="entry-header")
if entry[0].text.strip() == "Nothing Found":
if not kueri:
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
else:
await editPesan(msg, strings("no_result_w_query").format(kueri=kueri))
await msg.edit_msg(strings("no_result_w_query").format(kueri=kueri), del_in=5)
return None, 0, None
data = []
for i in entry:
@ -323,7 +324,7 @@ async def getDataGomov(msg, kueri, CurrentPage, user, strings):
gomovResult = "".join(i for i in gomovResult if i not in "[]")
return gomovResult, PageLen, extractbtn
except (IndexError, KeyError):
await editPesan(msg, strings("no_result"))
await msg.edit_msg(strings("no_result"), del_in=5)
return None, 0, None
@ -335,7 +336,7 @@ async def terbit21_s(client, message, strings):
kueri = " ".join(message.command[1:])
if not kueri:
kueri = None
pesan = await kirimPesan(message, strings("get_data"), quote=True)
pesan = await message.reply_msg(strings("get_data"), quote=True)
CurrentPage = 1
terbitres, PageLen = await getDataTerbit21(pesan, kueri, CurrentPage, strings)
if not terbitres:
@ -343,7 +344,7 @@ async def terbit21_s(client, message, strings):
keyboard = InlineKeyboard()
keyboard.paginate(PageLen, CurrentPage, "page_terbit21#{number}" + f"#{pesan.id}#{message.from_user.id}")
keyboard.row(InlineButton(strings("cl_btn"), f"close#{message.from_user.id}"))
await editPesan(pesan, terbitres, reply_markup=keyboard)
await pesan.edit_msg(terbitres, reply_markup=keyboard)
# LK21 CMD
@ -355,7 +356,7 @@ async def lk21_s(client, message, strings):
kueri = " ".join(message.command[1:])
if not kueri:
kueri = None
pesan = await kirimPesan(message, strings("get_data"), quote=True)
pesan = await message.reply_msg(strings("get_data"), quote=True)
CurrentPage = 1
lkres, PageLen = await getDatalk21(pesan, kueri, CurrentPage, strings)
if not lkres:
@ -363,7 +364,7 @@ async def lk21_s(client, message, strings):
keyboard = InlineKeyboard()
keyboard.paginate(PageLen, CurrentPage, "page_lk21#{number}" + f"#{pesan.id}#{message.from_user.id}")
keyboard.row(InlineButton(strings("cl_btn"), f"close#{message.from_user.id}"))
await editPesan(pesan, lkres, disable_web_page_preview=True, reply_markup=keyboard)
await pesan.edit_msg(lkres, disable_web_page_preview=True, reply_markup=keyboard)
# Pahe CMD
@ -375,7 +376,7 @@ async def pahe_s(client, message, strings):
kueri = " ".join(message.command[1:])
if not kueri:
kueri = ""
pesan = await kirimPesan(message, strings("get_data"), quote=True)
pesan = await message.reply_msg(strings("get_data"), quote=True)
CurrentPage = 1
paheres, PageLen = await getDataPahe(pesan, kueri, CurrentPage, strings)
if not paheres:
@ -383,7 +384,7 @@ async def pahe_s(client, message, strings):
keyboard = InlineKeyboard()
keyboard.paginate(PageLen, CurrentPage, "page_pahe#{number}" + f"#{pesan.id}#{message.from_user.id}")
keyboard.row(InlineButton(strings("cl_btn"), f"close#{message.from_user.id}"))
await editPesan(pesan, paheres, disable_web_page_preview=True, reply_markup=keyboard)
await pesan.edit_msg(paheres, disable_web_page_preview=True, reply_markup=keyboard)
# Gomov CMD
@ -394,7 +395,7 @@ async def gomov_s(client, message, strings):
kueri = " ".join(message.command[1:])
if not kueri:
kueri = ""
pesan = await kirimPesan(message, strings("get_data"), quote=True)
pesan = await message.reply_msg(strings("get_data"), quote=True)
CurrentPage = 1
gomovres, PageLen, btn = await getDataGomov(pesan, kueri, CurrentPage, message.from_user.id, strings)
if not gomovres:
@ -404,7 +405,7 @@ async def gomov_s(client, message, strings):
keyboard.row(InlineButton(strings("ex_data"), user_id=message.from_user.id))
keyboard.row(*btn)
keyboard.row(InlineButton(strings("cl_btn"), f"close#{message.from_user.id}"))
await editPesan(pesan, gomovres, disable_web_page_preview=True, reply_markup=keyboard)
await pesan.edit_msg(gomovres, disable_web_page_preview=True, reply_markup=keyboard)
# MelongMovie CMD
@ -415,7 +416,7 @@ async def melong_s(client, message, strings):
kueri = " ".join(message.command[1:])
if not kueri:
kueri = ""
pesan = await kirimPesan(message, strings("get_data"), quote=True)
pesan = await message.reply_msg(strings("get_data"), quote=True)
CurrentPage = 1
melongres, PageLen, btn = await getDataMelong(pesan, kueri, CurrentPage, message.from_user.id, strings)
if not melongres:
@ -425,7 +426,7 @@ async def melong_s(client, message, strings):
keyboard.row(InlineButton(strings("ex_data"), user_id=message.from_user.id))
keyboard.row(*btn)
keyboard.row(InlineButton(strings("cl_btn"), f"close#{message.from_user.id}"))
await editPesan(pesan, melongres, disable_web_page_preview=True, reply_markup=keyboard)
await pesan.edit_msg(melongres, disable_web_page_preview=True, reply_markup=keyboard)
# Savefilm21 CMD
@ -436,7 +437,7 @@ async def savefilm_s(client, message, strings):
kueri = " ".join(message.command[1:])
if not kueri:
kueri = ""
pesan = await kirimPesan(message, strings("get_data"), quote=True)
pesan = await message.reply_msg(strings("get_data"), quote=True)
CurrentPage = 1
savefilmres, PageLen, btn = await getDataSavefilm21(pesan, kueri, CurrentPage, message.from_user.id, strings)
if not savefilmres:
@ -446,7 +447,7 @@ async def savefilm_s(client, message, strings):
keyboard.row(InlineButton(strings("ex_data"), user_id=message.from_user.id))
keyboard.row(*btn)
keyboard.row(InlineButton(strings("cl_btn"), f"close#{message.from_user.id}"))
await editPesan(pesan, savefilmres, disable_web_page_preview=True, reply_markup=keyboard)
await pesan.edit_msg(savefilmres, disable_web_page_preview=True, reply_markup=keyboard)
# Kusonime CMD
@ -457,7 +458,7 @@ async def kusonime_s(client, message, strings):
kueri = " ".join(message.command[1:])
if not kueri:
kueri = ""
pesan = await kirimPesan(message, strings("get_data"), quote=True)
pesan = await message.reply_msg(strings("get_data"), quote=True)
CurrentPage = 1
kusores, PageLen, btn1, btn2 = await getDataKuso(pesan, kueri, CurrentPage, message.from_user.id, strings)
if not kusores:
@ -469,47 +470,47 @@ async def kusonime_s(client, message, strings):
if btn2:
keyboard.row(*btn2)
keyboard.row(InlineButton(strings("cl_btn"), f"close#{message.from_user.id}"))
await editPesan(pesan, kusores, disable_web_page_preview=True, reply_markup=keyboard)
await pesan.edit_msg(kusores, disable_web_page_preview=True, reply_markup=keyboard)
# Lendrive CMD
@app.on_message(filters.command(["lendrive"], COMMAND_HANDLER))
@ratelimiter
@use_chat_lang()
async def lendrive_s(client, message, strings):
kueri = " ".join(message.command[1:])
async def lendrive_s(self: Client, ctx: Message, strings):
kueri = ctx.input
if not kueri:
kueri = ""
pesan = await kirimPesan(message, strings("get_data"), quote=True)
pesan = await ctx.edit_msg(strings("get_data"), quote=True)
CurrentPage = 1
lendres, PageLen, btn = await getDataLendrive(pesan, kueri, CurrentPage, message.from_user.id, strings)
lendres, PageLen, btn = await getDataLendrive(pesan, kueri, CurrentPage, ctx.from_user.id, strings)
if not lendres:
return
keyboard = InlineKeyboard()
keyboard.paginate(PageLen, CurrentPage, "page_lendrive#{number}" + f"#{pesan.id}#{message.from_user.id}")
keyboard.row(InlineButton(strings("ex_data"), user_id=message.from_user.id))
keyboard.paginate(PageLen, CurrentPage, "page_lendrive#{number}" + f"#{pesan.id}#{ctx.from_user.id}")
keyboard.row(InlineButton(strings("ex_data"), user_id=ctx.from_user.id))
keyboard.row(*btn)
keyboard.row(InlineButton(strings("cl_btn"), f"close#{message.from_user.id}"))
await editPesan(pesan, lendres, disable_web_page_preview=True, reply_markup=keyboard)
keyboard.row(InlineButton(strings("cl_btn"), f"close#{ctx.from_user.id}"))
await pesan.edit_msg(lendres, disable_web_page_preview=True, reply_markup=keyboard)
# Movieku CMD
@app.on_message(filters.command(["movieku"], COMMAND_HANDLER))
@ratelimiter
@use_chat_lang()
async def movieku_s(client, message, strings):
kueri = " ".join(message.command[1:])
async def movieku_s(self: Client, ctx: Message, strings):
kueri = ctx.input
if not kueri:
kueri = ""
pesan = await kirimPesan(message, strings("get_data"), quote=True)
pesan = await ctx.reply_msg(strings("get_data"), quote=True)
CurrentPage = 1
moviekures, PageLen = await getDataMovieku(pesan, kueri, CurrentPage, strings)
if not moviekures:
return
keyboard = InlineKeyboard()
keyboard.paginate(PageLen, CurrentPage, "page_movieku#{number}" + f"#{pesan.id}#{message.from_user.id}")
keyboard.row(InlineButton(strings("cl_btn"), f"close#{message.from_user.id}"))
await editPesan(pesan, moviekures, disable_web_page_preview=True, reply_markup=keyboard)
keyboard.paginate(PageLen, CurrentPage, "page_movieku#{number}" + f"#{pesan.id}#{ctx.from_user.id}")
keyboard.row(InlineButton(strings("cl_btn"), f"close#{ctx.from_user.id}"))
await pesan.edit_msg(moviekures, disable_web_page_preview=True, reply_markup=keyboard)
# Savefillm21 Page Callback
@ -536,7 +537,7 @@ async def savefilmpage_callback(client, callback_query, strings):
keyboard.row(InlineButton(strings("ex_data"), user_id=callback_query.from_user.id))
keyboard.row(*btn)
keyboard.row(InlineButton(strings("cl_btn"), f"close#{callback_query.from_user.id}"))
await editPesan(callback_query.message, savefilmres, disable_web_page_preview=True, reply_markup=keyboard)
await callback_query.message.edit_msg(savefilmres, disable_web_page_preview=True, reply_markup=keyboard)
# Kuso Page Callback
@ -565,7 +566,7 @@ async def kusopage_callback(client, callback_query, strings):
if btn2:
keyboard.row(*btn2)
keyboard.row(InlineButton(strings("cl_btn"), f"close#{callback_query.from_user.id}"))
await editPesan(callback_query.message, kusores, disable_web_page_preview=True, reply_markup=keyboard)
await callback_query.message.edit_msg(kusores, disable_web_page_preview=True, reply_markup=keyboard)
# Lendrive Page Callback
@ -592,7 +593,7 @@ async def moviekupage_callback(client, callback_query, strings):
keyboard.row(InlineButton(strings("ex_data"), user_id=callback_query.from_user.id))
keyboard.row(*btn)
keyboard.row(InlineButton(strings("cl_btn"), f"close#{callback_query.from_user.id}"))
await editPesan(callback_query.message, lendres, disable_web_page_preview=True, reply_markup=keyboard)
await callback_query.message.edit_msg(lendres, disable_web_page_preview=True, reply_markup=keyboard)
# Movieku Page Callback
@ -617,7 +618,7 @@ async def moviekupage_callback(client, callback_query, strings):
keyboard = InlineKeyboard()
keyboard.paginate(PageLen, CurrentPage, "page_movieku#{number}" + f"#{message_id}#{callback_query.from_user.id}")
keyboard.row(InlineButton(strings("cl_btn"), f"close#{callback_query.from_user.id}"))
await editPesan(callback_query.message, moviekures, disable_web_page_preview=True, reply_markup=keyboard)
await callback_query.message.edit_msg(moviekures, disable_web_page_preview=True, reply_markup=keyboard)
# Terbit21 Page Callback
@ -642,7 +643,7 @@ async def terbit21page_callback(client, callback_query, strings):
keyboard = InlineKeyboard()
keyboard.paginate(PageLen, CurrentPage, "page_terbit21#{number}" + f"#{message_id}#{callback_query.from_user.id}")
keyboard.row(InlineButton(strings("cl_btn"), f"close#{callback_query.from_user.id}"))
await editPesan(callback_query.message, terbitres, disable_web_page_preview=True, reply_markup=keyboard)
await callback_query.message.edit_msg(terbitres, disable_web_page_preview=True, reply_markup=keyboard)
# Page Callback Melong
@ -669,7 +670,7 @@ async def melongpage_callback(client, callback_query, strings):
keyboard.row(InlineButton(strings("ex_data"), user_id=callback_query.from_user.id))
keyboard.row(*btn)
keyboard.row(InlineButton(strings("cl_btn"), f"close#{callback_query.from_user.id}"))
await editPesan(callback_query.message, terbitres, disable_web_page_preview=True, reply_markup=keyboard)
await callback_query.message.edit_msg(terbitres, disable_web_page_preview=True, reply_markup=keyboard)
# Lk21 Page Callback
@ -694,7 +695,7 @@ async def lk21page_callback(client, callback_query, strings):
keyboard = InlineKeyboard()
keyboard.paginate(PageLen, CurrentPage, "page_lk21#{number}" + f"#{message_id}#{callback_query.from_user.id}")
keyboard.row(InlineButton(strings("cl_btn"), f"close#{callback_query.from_user.id}"))
await editPesan(callback_query.message, lkres, disable_web_page_preview=True, reply_markup=keyboard)
await callback_query.message.edit_msg(lkres, disable_web_page_preview=True, reply_markup=keyboard)
# Pahe Page Callback
@ -719,7 +720,7 @@ async def pahepage_callback(client, callback_query, strings):
keyboard = InlineKeyboard()
keyboard.paginate(PageLen, CurrentPage, "page_pahe#{number}" + f"#{message_id}#{callback_query.from_user.id}")
keyboard.row(InlineButton(strings("cl_btn"), f"close#{callback_query.from_user.id}"))
await editPesan(callback_query.message, lkres, disable_web_page_preview=True, reply_markup=keyboard)
await callback_query.message.edit_msg(lkres, disable_web_page_preview=True, reply_markup=keyboard)
# Gomov Page Callback
@ -746,7 +747,7 @@ async def gomovpage_callback(client, callback_query, strings):
keyboard.row(InlineButton(strings("ex_data"), user_id=callback_query.from_user.id))
keyboard.row(*btn)
keyboard.row(InlineButton(strings("cl_btn"), f"close#{callback_query.from_user.id}"))
await editPesan(callback_query.message, gomovres, disable_web_page_preview=True, reply_markup=keyboard)
await callback_query.message.edit_msg(gomovres, disable_web_page_preview=True, reply_markup=keyboard)
### Scrape DDL Link From Web ###
@ -771,17 +772,17 @@ async def kusonime_scrap(_, callback_query, strings):
try:
if init_url := data_kuso.get(link, None):
ph = init_url.get("ph_url")
await editPesan(callback_query.message, strings("res_scrape").format(link=link, kl=ph), reply_markup=keyboard, disable_web_page_preview=False)
await callback_query.message.edit_msg(strings("res_scrape").format(link=link, kl=ph), reply_markup=keyboard, disable_web_page_preview=False)
return
tgh = await kuso.telegraph(link, message_id)
if tgh["error"]:
await editPesan(callback_query.message, f"ERROR: {tgh['error_message']}", reply_markup=keyboard)
await callback_query.message.edit_msg(f"ERROR: {tgh['error_message']}", reply_markup=keyboard)
return
except Exception as err:
await editPesan(callback_query.message, f"ERROR: {err}", reply_markup=keyboard)
await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard)
return
data_kuso[link] = {"ph_url": tgh["url"]}
await editPesan(callback_query.message, strings("res_scrape").format(link=link, kl=tgh["url"]), reply_markup=keyboard, disable_web_page_preview=False)
await callback_query.message.edit_msg(strings("res_scrape").format(link=link, kl=tgh["url"]), reply_markup=keyboard, disable_web_page_preview=False)
# Savefilm21 DDL
@ -807,9 +808,9 @@ async def savefilm21_scrap(_, callback_query, strings):
res = soup.find_all(class_="button button-shadow")
res = "".join(f"{i.text}\n{i['href']}\n\n" for i in res)
except Exception as err:
await editPesan(callback_query.message, f"ERROR: {err}", reply_markup=keyboard)
await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard)
return
await editPesan(callback_query.message, strings("res_scrape").format(link=link, kl=res), reply_markup=keyboard)
await callback_query.message.edit_msg(strings("res_scrape").format(link=link, kl=res), reply_markup=keyboard)
# Scrape Link Download Movieku.CC
@ -865,9 +866,9 @@ async def melong_scrap(_, callback_query, strings):
softsub = ep.findNext("div")
rep += f"{hardsub}\n{softsub}"
except Exception as err:
await editPesan(callback_query.message, f"ERROR: {err}", reply_markup=keyboard)
await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard)
return
await editPesan(callback_query.message, strings("res_scrape").format(link=link, kl=rep), reply_markup=keyboard)
await callback_query.message.edit_msg(strings("res_scrape").format(link=link, kl=rep), reply_markup=keyboard)
# Scrape DDL Link Gomov
@ -897,9 +898,9 @@ async def gomov_dl(_, callback_query, strings):
link = i.find("a")["href"]
hasil += f"\n{title}\n{link}\n"
except Exception as err:
await editPesan(callback_query.message, f"ERROR: {err}", reply_markup=keyboard)
await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard)
return
await editPesan(callback_query.message, strings("res_scrape").format(link=link, kl=hasil), reply_markup=keyboard)
await callback_query.message.edit_msg(strings("res_scrape").format(link=link, kl=hasil), reply_markup=keyboard)
@app.on_callback_query(filters.create(lambda _, __, query: "lendriveextract#" in query.data))
@ -928,6 +929,6 @@ async def lendrive_dl(_, callback_query, strings):
continue
kl += f"{i.find('strong')}:\n"
kl += "".join(f"[ <a href='{a.get('href')}'>{a.text}</a> ]\n" for a in i.findAll("a"))
await editPesan(callback_query.message, strings("res_scrape").format(link=link, kl=kl), reply_markup=keyboard)
await callback_query.message.edit_msg(strings("res_scrape").format(link=link, kl=kl), reply_markup=keyboard)
except Exception as err:
await editPesan(callback_query.message, f"ERROR: {err}", reply_markup=keyboard)
await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard)

View file

@ -1,9 +1,9 @@
from asyncio import gather
from pyrogram import filters
from pyrogram import filters, Client
from pyrogram.types import Message
from misskaty import app
from misskaty.core.message_utils import *
from misskaty.core.decorator.errors import capture_err
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.helper.localization import use_chat_lang
@ -19,15 +19,15 @@ __HELP__ = """
@capture_err
@ratelimiter
@use_chat_lang()
async def take_ss(_, m, strings):
if len(m.command) == 1:
return await kirimPesan(m, strings("no_url"))
url = m.command[1] if m.command[1].startswith("http") else f"https://{m.command[1]}"
filename = f"webSS_{m.from_user.id}.png"
msg = await m.reply(strings("wait_str"))
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]}"
filename = f"webSS_{ctx.from_user.id}.png"
msg = await ctx.reply_msg(strings("wait_str"))
try:
url = f"https://webss.yasirapi.eu.org/api?url={url}&width=1280&height=720"
await gather(*[m.reply_document(url, file_name=filename), m.reply_photo(url)])
await hapusPesan(msg)
await gather(*[ctx.reply_document(url, file_name=filename), ctx.reply_photo(url)])
await msg.delete_msg()
except Exception as e:
await editPesan(msg, strings("ss_failed_str").format(err=str(e)))
await msg.edit_msg(strings("ss_failed_str").format(err=str(e)))

View file

@ -3,11 +3,10 @@ from re import compile as recompile
from uuid import uuid4
from iytdl import iYTDL, main
from pyrogram import filters
from pyrogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, InputMediaPhoto
from pyrogram import filters, Client
from pyrogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, InputMediaPhoto, Message
from misskaty import app
from misskaty.core.message_utils import *
from misskaty.core.decorator.errors import capture_err
from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.helper.http import http
@ -27,17 +26,17 @@ def rand_key():
@capture_err
@ratelimiter
@use_chat_lang()
async def ytsearch(_, message, strings):
if message.sender_chat:
return await kirimPesan(message, strings("no_channel"))
if len(message.command) == 1:
return await kirimPesan(message, strings("no_query"))
query = message.text.split(" ", maxsplit=1)[1]
async def ytsearch(self: Client, ctx: Message, strings):
if ctx.sender_chat:
return await ctx.reply_msg(strings("no_channel"))
if len(ctx.command) == 1:
return await ctx.reply_msg(strings("no_query"))
query = ctx.text.split(" ", maxsplit=1)[1]
search_key = rand_key()
YT_DB[search_key] = query
search = await main.VideosSearch(query).next()
if search["result"] == []:
return await message.reply(strings("no_res").format(kweri=query))
return await ctx.reply_msg(strings("no_res").format(kweri=query))
i = search["result"][0]
out = f"<b><a href={i['link']}>{i['title']}</a></b>\n"
out = strings("yts_msg").format(pub=i["publishedTime"], dur=i["duration"], vi=i["viewCount"]["short"], clink=i["channel"]["link"], cname=i["channel"]["name"])
@ -55,36 +54,36 @@ async def ytsearch(_, message, strings):
img = await get_ytthumb(i["id"])
caption = out
markup = btn
await message.reply_photo(img, caption=caption, reply_markup=markup, quote=True)
await ctx.reply_photo(img, caption=caption, reply_markup=markup, quote=True)
@app.on_message(filters.command(["ytdown"], COMMAND_HANDLER))
@capture_err
@ratelimiter
@use_chat_lang()
async def ytdownv2(_, message, strings):
if not message.from_user:
return await kirimPesan(message, strings("no_channel"))
if len(message.command) == 1:
return await message.reply(strings("invalid_link"))
url = message.text.split(" ", maxsplit=1)[1]
async def ytdownv2(self: Client, ctx: Message, strings):
if not ctx.from_user:
return await ctx.reply_msg(strings("no_channel"))
if len(ctx.command) == 1:
return await ctx.reply_msg(strings("invalid_link"))
url = ctx.input
async with iYTDL(log_group_id=0, cache_path="cache", ffmpeg_location="/usr/bin/mediaextract") as ytdl:
try:
x = await ytdl.parse(url)
if x is None:
return await message.reply(strings("err_parse"))
return await ctx.reply_msg(strings("err_parse"))
img = await get_ytthumb(x.key)
caption = x.caption
markup = x.buttons
await message.reply_photo(img, caption=caption, reply_markup=markup, quote=True)
await ctx.reply_photo(img, caption=caption, reply_markup=markup, quote=True)
except Exception as err:
await kirimPesan(message, f"Opps, ERROR: {str(err)}")
await ctx.reply_msg(f"Opps, ERROR: {str(err)}")
@app.on_callback_query(filters.regex(r"^yt_listall"))
@ratelimiter
@use_chat_lang()
async def ytdl_listall_callback(_, cq: CallbackQuery, strings):
async def ytdl_listall_callback(self: Client, cq: CallbackQuery, strings):
if cq.from_user.id != cq.message.reply_to_message.from_user.id:
return await cq.answer(strings("unauth"), True)
callback = cq.data.split("|")
@ -96,7 +95,7 @@ async def ytdl_listall_callback(_, cq: CallbackQuery, strings):
@app.on_callback_query(filters.regex(r"^yt_extract_info"))
@ratelimiter
@use_chat_lang()
async def ytdl_extractinfo_callback(_, cq: CallbackQuery, strings):
async def ytdl_extractinfo_callback(self: Client, cq: CallbackQuery, strings):
if cq.from_user.id != cq.message.reply_to_message.from_user.id:
return await cq.answer(strings("unauth"), True)
await cq.answer(strings("wait"))
@ -123,7 +122,7 @@ async def ytdl_extractinfo_callback(_, cq: CallbackQuery, strings):
@app.on_callback_query(filters.regex(r"^yt_(gen|dl)"))
@ratelimiter
@use_chat_lang()
async def ytdl_gendl_callback(_, cq: CallbackQuery, strings):
async def ytdl_gendl_callback(self: Client, cq: CallbackQuery, strings):
if cq.from_user.id != cq.message.reply_to_message.from_user.id:
return await cq.answer(strings("unauth"), True)
callback = cq.data.split("|")
@ -174,7 +173,7 @@ async def ytdl_gendl_callback(_, cq: CallbackQuery, strings):
@app.on_callback_query(filters.regex(r"^ytdl_scroll"))
@ratelimiter
@use_chat_lang()
async def ytdl_scroll_callback(_, cq: CallbackQuery, strings):
async def ytdl_scroll_callback(self: Client, cq: CallbackQuery, strings):
if cq.from_user.id != cq.message.reply_to_message.from_user.id:
return await cq.answer(strings("unauth"), True)
callback = cq.data.split("|")