style: format code with isort, Ruff Formatter and Yapf (#300)

* style: format code with isort, Ruff Formatter and Yapf

This commit fixes the style issues introduced in f9f107e according to the output
from isort, Ruff Formatter and Yapf.

Details: None

* refactor: autofix issues in 2 files

Resolved issues in the following files with DeepSource Autofix:
1. misskaty/plugins/download_upload.py
2. misskaty/plugins/nightmodev2.py

* style: format code with isort, Ruff Formatter and Yapf

This commit fixes the style issues introduced in 1bc1345 according to the output
from isort, Ruff Formatter and Yapf.

Details: https://github.com/yasirarism/MissKatyPyro/pull/300

* refactor: autofix issues in 2 files

Resolved issues in the following files with DeepSource Autofix:
1. misskaty/plugins/dev.py
2. misskaty/plugins/misc_tools.py

* style: format code with isort, Ruff Formatter and Yapf

This commit fixes the style issues introduced in 58d2f1a according to the output
from isort, Ruff Formatter and Yapf.

Details: https://github.com/yasirarism/MissKatyPyro/pull/300

---------

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
Co-authored-by: Yasir Aris M <git@yasirdev.my.id>
This commit is contained in:
deepsource-autofix[bot] 2024-07-30 11:52:58 +07:00 committed by GitHub
parent 0bc0e91688
commit 2aa93bb4d5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
60 changed files with 747 additions and 371 deletions

View file

@ -1,9 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-09-06 10:12:09
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-09-06 10:12:09
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
from async_pymongo import AsyncClient
from misskaty.vars import DATABASE_NAME, DATABASE_URI

View file

@ -1,8 +1,9 @@
import pytz
from datetime import datetime
from misskaty.vars import SUDO
from database import dbname
import pytz
from database import dbname
from misskaty.vars import SUDO
fedsdb = dbname["federation"]
@ -32,9 +33,7 @@ async def get_feds_by_owner(owner_id):
feds = await cursor.to_list(length=None)
if not feds:
return False
return [
{"fed_id": fed["fed_id"], "fed_name": fed["fed_name"]} for fed in feds
]
return [{"fed_id": fed["fed_id"], "fed_name": fed["fed_name"]} for fed in feds]
async def transfer_owner(fed_id, current_owner_id, new_owner_id):

View file

@ -2,9 +2,11 @@ from database import dbname
greetingdb = dbname["greetings"]
async def is_welcome(chat_id: int) -> bool:
return bool(await greetingdb.find_one({"chat_id": chat_id}))
async def toggle_welcome(chat_id: int):
if await is_welcome(chat_id):
await greetingdb.delete_one({"chat_id": chat_id})
@ -13,4 +15,5 @@ async def toggle_welcome(chat_id: int):
await greetingdb.insert_one({"chat_id": chat_id})
return True
# todo other features for custom welcome here

View file

@ -2,11 +2,13 @@
# * @date 2023-06-21 22:12:27
# * @projectName MissKatyPyro
# * Copyright ©YasirPedia All rights reserved
import time, os, uvloop
import os
import time
from asyncio import get_event_loop
from faulthandler import enable as faulthandler_enable
from logging import ERROR, INFO, StreamHandler, basicConfig, getLogger, handlers
import uvloop
from apscheduler.jobstores.mongodb import MongoDBJobStore
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from async_pymongo import AsyncClient
@ -28,7 +30,9 @@ basicConfig(
format="[%(levelname)s] - [%(asctime)s - %(name)s - %(message)s] -> [%(module)s:%(lineno)d]",
datefmt="%d-%b-%y %H:%M:%S",
handlers=[
handlers.RotatingFileHandler("MissKatyLogs.txt", mode="w+", maxBytes=5242880, backupCount=1),
handlers.RotatingFileHandler(
"MissKatyLogs.txt", mode="w+", maxBytes=5242880, backupCount=1
),
StreamHandler(),
],
)

View file

@ -1,9 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import asyncio
import importlib
import os
@ -15,7 +16,15 @@ from pyrogram import __version__, idle
from pyrogram.raw.all import layer
from database import dbname
from misskaty import BOT_NAME, BOT_USERNAME, HELPABLE, UBOT_NAME, app, scheduler, get_event_loop
from misskaty import (
BOT_NAME,
BOT_USERNAME,
HELPABLE,
UBOT_NAME,
app,
get_event_loop,
scheduler,
)
from misskaty.plugins import ALL_MODULES
from misskaty.plugins.web_scraper import web
from misskaty.vars import SUDO, USER_SESSION

View file

@ -6,8 +6,8 @@ from logging import getLogger
from typing import Union
from pyrogram.errors import (
ChatAdminRequired,
ChannelPrivate,
ChatAdminRequired,
ChatSendPlainForbidden,
ChatWriteForbidden,
FloodWait,
@ -22,6 +22,7 @@ from pyrogram.types import Message
LOGGER = getLogger("MissKaty")
@property
def parse_cmd(msg):
return msg.text.split(None, 1)[1] if len(msg.command) > 1 else None

View file

@ -66,7 +66,9 @@ async def anonymous_admin_verification(
try:
member = await CallbackQuery.message.chat.get_member(CallbackQuery.from_user.id)
except pyrogram.errors.exceptions.bad_request_400.UserNotParticipant:
return await CallbackQuery.answer("You're not member of this group.", show_alert=True)
return await CallbackQuery.answer(
"You're not member of this group.", show_alert=True
)
except pyrogram.errors.exceptions.forbidden_403.ChatAdminRequired:
return await CallbackQuery.message.edit_text(
"I must be admin to execute this task, or i will leave from this group.",

View file

@ -21,7 +21,7 @@ def command(
handler: typing.Optional[list] = None,
filtercmd: typing.Union[pyrogram.filters.Filter] = None,
*args,
**kwargs
**kwargs,
):
"""
### `tgClient.command`

View file

@ -12,7 +12,7 @@ async def edit_message_text(
text: str,
del_in: int = 0,
*args,
**kwargs
**kwargs,
) -> Union["Message", bool]:
"""\nExample:
message.edit_text("hello")

View file

@ -23,7 +23,7 @@ import pyrogram
async def get_user(
m: typing.Union[pyrogram.types.Message, pyrogram.types.CallbackQuery]
m: typing.Union[pyrogram.types.Message, pyrogram.types.CallbackQuery],
) -> pyrogram.types.User or bool:
"""
### `tgEasy.get_user`
@ -75,7 +75,7 @@ async def get_user(
async def get_user_adv(
m: typing.Union[pyrogram.types.Message, pyrogram.types.CallbackQuery]
m: typing.Union[pyrogram.types.Message, pyrogram.types.CallbackQuery],
) -> pyrogram.types.User or bool:
"""
### `tgEasy.get_user_adv`

View file

@ -53,7 +53,9 @@ async def handle_error(
f_errname = f"crash_{tgl_now.strftime('%d %B %Y')}.txt"
LOGGER.error(traceback.format_exc())
with open(f_errname, "w+", encoding="utf-8") as log:
log.write(f"✍️ Message: {m.text or m.caption}\n👱‍♂️ User: {m.from_user.id if m.from_user else m.sender_chat.id}\n\n{traceback.format_exc()}")
log.write(
f"✍️ Message: {m.text or m.caption}\n👱‍♂️ User: {m.from_user.id if m.from_user else m.sender_chat.id}\n\n{traceback.format_exc()}"
)
log.close()
if isinstance(m, pyrogram.types.Message):
with contextlib.suppress(Exception):

View file

@ -17,6 +17,7 @@ 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/>.
"""
from contextlib import asynccontextmanager, contextmanager
from inspect import iscoroutinefunction
from logging import getLogger

View file

@ -3,8 +3,8 @@ from .files import *
from .functions import *
from .http import *
from .human_read import *
from .localization import *
from .kuso_utils import *
from .localization import *
from .media_helper import *
from .misc import *
from .pyro_progress import *

View file

@ -17,6 +17,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import math
import os

View file

@ -1,7 +1,7 @@
from asyncio import gather
from httpx import AsyncClient, Timeout
from aiohttp import ClientSession
from httpx import AsyncClient, Timeout
# Aiohttp Async Client
session = ClientSession()

View file

@ -8,7 +8,9 @@ def get_readable_file_size(size_in_bytes) -> str:
while size_in_bytes >= 1024 and index < len(SIZE_UNITS) - 1:
size_in_bytes /= 1024
index += 1
return f"{size_in_bytes:.2f} {SIZE_UNITS[index]}" if index > 0 else f"{size_in_bytes}B"
return (
f"{size_in_bytes:.2f} {SIZE_UNITS[index]}" if index > 0 else f"{size_in_bytes}B"
)
def get_readable_time(seconds: int) -> str:

View file

@ -1,11 +1,11 @@
import logging
import traceback
from html import escape
from typing import Optional
import chevron
from bs4 import BeautifulSoup
from telegraph.aio import Telegraph
from typing import Optional
from misskaty import BOT_USERNAME
from misskaty.helper.http import fetch
@ -26,23 +26,85 @@ async def kusonimeBypass(url: str):
# title = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > p:nth-child(3) > strong")[0].text.strip()
try:
title = soup.find("h1", {"class": "jdlz"}).text # fix title njing haha
season = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(3)")[0].text.split(":").pop().strip()
tipe = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(5)")[0].text.split(":").pop().strip()
status_anime = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(6)")[0].text.split(":").pop().strip()
ep = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(7)")[0].text.split(":").pop().strip()
score = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(8)")[0].text.split(":").pop().strip()
duration = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(9)")[0].text.split(":").pop().strip()
rilis = soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(10)")[0].text.split(":").pop().strip()
season = (
soup.select(
"#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(3)"
)[0]
.text.split(":")
.pop()
.strip()
)
tipe = (
soup.select(
"#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(5)"
)[0]
.text.split(":")
.pop()
.strip()
)
status_anime = (
soup.select(
"#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(6)"
)[0]
.text.split(":")
.pop()
.strip()
)
ep = (
soup.select(
"#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(7)"
)[0]
.text.split(":")
.pop()
.strip()
)
score = (
soup.select(
"#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(8)"
)[0]
.text.split(":")
.pop()
.strip()
)
duration = (
soup.select(
"#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(9)"
)[0]
.text.split(":")
.pop()
.strip()
)
rilis = (
soup.select(
"#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(10)"
)[0]
.text.split(":")
.pop()
.strip()
)
except Exception:
e = traceback.format_exc()
LOGGER.error(e)
title, season, tipe, status_anime, ep, score, duration, rilis = "None", "None", "None", "None", 0, 0, 0, "None"
title, season, tipe, status_anime, ep, score, duration, rilis = (
"None",
"None",
"None",
"None",
0,
0,
0,
"None",
)
num = 1
genre = []
for _genre in soup.select("#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(2)"):
for _genre in soup.select(
"#venkonten > div.vezone > div.venser > div.venutama > div.lexot > div.info > p:nth-child(2)"
):
gen = _genre.text.split(":").pop().strip().split(", ")
genre = gen
for smokedl in soup.find("div", {"class": "dlbodz"}).find_all("div", {"class": "smokeddlrh"}):
for smokedl in soup.find("div", {"class": "dlbodz"}).find_all(
"div", {"class": "smokeddlrh"}
):
if not smokedl:
continue
mendata = {"name": title, "links": []}
@ -68,7 +130,9 @@ async def kusonimeBypass(url: str):
mendata["links"].append({"quality": quality, "link_download": links})
data.append(mendata)
num += 1
for smokedl in soup.find("div", {"class": "dlbodz"}).find_all("div", {"class": "smokeddl"}):
for smokedl in soup.find("div", {"class": "dlbodz"}).find_all(
"div", {"class": "smokeddl"}
):
if not smokedl:
continue
mendata = {"name": title, "links": []}
@ -94,7 +158,22 @@ async def kusonimeBypass(url: str):
mendata["links"].append({"quality": quality, "link_download": links})
data.append(mendata)
num += 1
result.update({"title": title, "thumb": thumb, "genre": genre, "genre_string": ", ".join(genre), "status_anime": status_anime, "season": season, "tipe": tipe, "ep": ep, "score": score, "duration": duration, "rilis": rilis, "data": data})
result.update(
{
"title": title,
"thumb": thumb,
"genre": genre,
"genre_string": ", ".join(genre),
"status_anime": status_anime,
"season": season,
"tipe": tipe,
"ep": ep,
"score": score,
"duration": duration,
"rilis": rilis,
"data": data,
}
)
except Exception as e:
if result:
result.clear()

View file

@ -76,9 +76,7 @@ def paginate_modules(page_n, module_dict, prefix, chat=None):
)
]
else:
pairs = pairs[
modulo_page * COLUMN_SIZE : COLUMN_SIZE * (modulo_page + 1)
] + [
pairs = pairs[modulo_page * COLUMN_SIZE : COLUMN_SIZE * (modulo_page + 1)] + [
(
EqInlineKeyboardButton(
"Back", callback_data=f"{prefix}_home({modulo_page})"

View file

@ -17,6 +17,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from typing import List
from pyrogram import Client, errors, raw

View file

@ -4,17 +4,17 @@ import random
import re
import string
import time
import cv2
import numpy as np
from http.cookies import SimpleCookie
from misskaty.core.decorator import asyncify
from re import match as re_match
from typing import Union
from urllib.parse import urlparse
import cv2
import numpy as np
import psutil
from misskaty import BOT_NAME, UBOT_NAME, botStartTime
from misskaty.core.decorator import asyncify
from misskaty.helper.http import fetch
from misskaty.helper.human_read import get_readable_time
from misskaty.plugins import ALL_MODULES
@ -159,11 +159,13 @@ async def search_jw(movie_name: str, locale: Union[str, None] = "ID"):
def isValidURL(str):
# Regex to check valid URL
regex = ("((http|https)://)(www.)?" +
"[a-zA-Z0-9@:%._\\+~#?&//=]" +
"{2,256}\\.[a-z]" +
"{2,6}\\b([-a-zA-Z0-9@:%" +
"._\\+~#?&//=]*)")
regex = (
"((http|https)://)(www.)?"
+ "[a-zA-Z0-9@:%._\\+~#?&//=]"
+ "{2,256}\\.[a-z]"
+ "{2,6}\\b([-a-zA-Z0-9@:%"
+ "._\\+~#?&//=]*)"
)
# Compile the ReGex
p = re.compile(regex)
@ -189,16 +191,18 @@ def gen_trans_image(source, path):
# apply morphology to remove isolated extraneous noise
# use borderconstant of black since foreground touches the edges
kernel = np.ones((3,3), np.uint8)
kernel = np.ones((3, 3), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
# anti-alias the mask -- blur then stretch
# blur alpha channel
mask = cv2.GaussianBlur(mask, (0,0), sigmaX=2, sigmaY=2, borderType = cv2.BORDER_DEFAULT)
mask = cv2.GaussianBlur(
mask, (0, 0), sigmaX=2, sigmaY=2, borderType=cv2.BORDER_DEFAULT
)
# linear stretch so that 127.5 goes to 0, but 255 stays 255
mask = (2*(mask.astype(np.float32))-255.0).clip(0,255).astype(np.uint8)
mask = (2 * (mask.astype(np.float32)) - 255.0).clip(0, 255).astype(np.uint8)
# put mask into alpha channel
result = img.copy()

View file

@ -1,9 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright ©YasirPedia All rights reserved
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright ©YasirPedia All rights reserved
"""
import glob
import importlib
import sys

View file

@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import asyncio
import os
import re
@ -34,7 +35,7 @@ from pyrogram.errors import (
PeerIdInvalid,
UsernameNotOccupied,
)
from pyrogram.types import ChatPermissions, ChatMember, ChatPrivileges, Message
from pyrogram.types import ChatMember, ChatPermissions, ChatPrivileges, Message
from database.warn_db import add_warn, get_warn, remove_warns
from misskaty import app
@ -568,7 +569,9 @@ async def mute(client, message, strings):
if reason:
msg += strings("banned_reason").format(reas=reason)
try:
await message.chat.restrict_member(user_id, permissions=ChatPermissions(all_perms=False))
await message.chat.restrict_member(
user_id, permissions=ChatPermissions(all_perms=False)
)
await message.reply_text(msg, reply_markup=keyboard)
except Exception as e:
await message.reply_msg(str(e))
@ -861,21 +864,28 @@ async def set_chat_photo(_, ctx: Message):
os.remove(photo)
@app.on_message(filters.group & filters.command('mentionall', COMMAND_HANDLER))
@app.on_message(filters.group & filters.command("mentionall", COMMAND_HANDLER))
async def mentionall(app: Client, msg: Message):
user = await msg.chat.get_member(msg.from_user.id)
if user.status in (enums.ChatMemberStatus.OWNER, enums.ChatMemberStatus.ADMINISTRATOR):
if user.status in (
enums.ChatMemberStatus.OWNER,
enums.ChatMemberStatus.ADMINISTRATOR,
):
total = []
async for member in app.get_chat_members(msg.chat.id):
member: ChatMember
if member.user.username:
total.append(f'@{member.user.username}')
total.append(f"@{member.user.username}")
else:
total.append(member.user.mention())
NUM = 4
for i in range(0, len(total), NUM):
message = ' '.join(total[i:i+NUM])
await app.send_message(msg.chat.id, message, message_thread_id=msg.message_thread_id)
message = " ".join(total[i : i + NUM])
await app.send_message(
msg.chat.id, message, message_thread_id=msg.message_thread_id
)
else:
await app.send_message(msg.chat.id, 'Admins only can do that !', reply_to_message_id=msg.id)
await app.send_message(
msg.chat.id, "Admins only can do that !", reply_to_message_id=msg.id
)

View file

@ -1,9 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
from pyrogram import filters
from pyrogram.errors import UserAlreadyParticipant, UserIsBlocked
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup

View file

@ -1,5 +1,3 @@
from database import dbname
from pyrogram import filters
from pyrogram.types import (
CallbackQuery,
@ -9,9 +7,10 @@ from pyrogram.types import (
Message,
)
from database import dbname
from misskaty import app
from misskaty.vars import SUDO, COMMAND_HANDLER
from misskaty.core.decorator.permissions import adminsOnly, member_permissions
from misskaty.vars import COMMAND_HANDLER, SUDO
approvaldb = dbname["autoapprove"]
@ -67,13 +66,7 @@ async def approval_cb(_, cb: CallbackQuery):
if await approvaldb.count_documents({"chat_id": chat_id}) == 0:
approvaldb.insert_one({"chat_id": chat_id})
keyboard_off = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
"Turn OFF", callback_data="approval_off"
)
]
]
[[InlineKeyboardButton("Turn OFF", callback_data="approval_off")]]
)
await cb.edit_message_text(
"**Autoapproval for this chat: Enabled.**",
@ -83,13 +76,7 @@ async def approval_cb(_, cb: CallbackQuery):
if await approvaldb.count_documents({"chat_id": chat_id}) > 0:
approvaldb.delete_one({"chat_id": chat_id})
keyboard_on = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
"Turn ON", callback_data="approval_on"
)
]
]
[[InlineKeyboardButton("Turn ON", callback_data="approval_on")]]
)
await cb.edit_message_text(
"**Autoapproval for this chat: Disabled.**",

View file

@ -1,4 +1,5 @@
from curses.ascii import isblank
from pyrogram import Client, filters
from pyrogram.errors import ChannelPrivate, PeerIdInvalid
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
@ -93,7 +94,9 @@ async def ban_a_user(bot, message):
f"{k.mention} is already banned\n<b>Reason:</b> {alesan['reason']}"
)
await db.ban_user(k.id, reason)
await message.reply(f"Successfully banned user {k.mention}!!\n<b>Reason:</b> {reason}")
await message.reply(
f"Successfully banned user {k.mention}!!\n<b>Reason:</b> {reason}"
)
@app.on_message(filters.command("unbanuser", COMMAND_HANDLER) & filters.user(SUDO))

View file

@ -21,12 +21,13 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import re
from datetime import datetime, timedelta
from pyrogram import filters
from pyrogram.types import ChatPermissions
from pyrogram.errors import ChatAdminRequired
from pyrogram.types import ChatPermissions
from database.blacklist_db import (
delete_blacklist_filter,
@ -113,7 +114,9 @@ async def blacklist_filters_re(self, message):
until_date=datetime.now() + timedelta(hours=1),
)
except ChatAdminRequired:
return await message.reply("Please give me admin permissions to blacklist user", quote=False)
return await message.reply(
"Please give me admin permissions to blacklist user", quote=False
)
except Exception as err:
self.log.info(f"ERROR Blacklist Chat: ID = {chat_id}, ERR = {err}")
return

View file

@ -2,11 +2,11 @@ import asyncio
import datetime
import time
from async_pymongo import AsyncClient
from pyrogram import filters
from pyrogram.types import Message
from async_pymongo import AsyncClient
from misskaty import app, DATABASE_URI
from misskaty import DATABASE_URI, app
from misskaty.vars import SUDO
from utils import broadcast_messages

View file

@ -1,10 +1,11 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @lastModified 2022-12-01 09:32:31
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @lastModified 2022-12-01 09:32:31
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import re
import urllib.parse
from urllib.parse import unquote
@ -16,7 +17,7 @@ from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from misskaty import app
from misskaty.core.decorator.errors import capture_err
from misskaty.helper import get_readable_file_size, fetch, rentry
from misskaty.helper import fetch, get_readable_file_size, rentry
from misskaty.vars import COMMAND_HANDLER
LIST_LINK = """
@ -37,9 +38,8 @@ Supported Link:
Credit: <a href='https://github.com/sanjit-sinha/PyBypass'>PyBypass</a>
"""
# Stopped development for this plugin since always changed time by time.
async def pling_bypass(url):
try:
id_url = re.search(r"https?://(store.kde.org|www.pling.com)\/p\/(\d+)", url)[2]

View file

@ -6,7 +6,7 @@ import asyncio
import html
import random
from openai import AsyncOpenAI, APIConnectionError, RateLimitError, APIStatusError
from openai import APIConnectionError, APIStatusError, AsyncOpenAI, RateLimitError
from pyrogram import filters
from pyrogram.errors import MessageTooLong
from pyrogram.types import Message
@ -14,8 +14,7 @@ from pyrogram.types import Message
from misskaty import app
from misskaty.core import pyro_cooldown
from misskaty.helper import check_time_gap, fetch, post_to_telegraph, use_chat_lang
from misskaty.vars import GOOGLEAI_KEY, COMMAND_HANDLER, OPENAI_KEY, SUDO
from misskaty.vars import COMMAND_HANDLER, GOOGLEAI_KEY, OPENAI_KEY, SUDO
__MODULE__ = "ChatBot"
__HELP__ = """
@ -25,7 +24,9 @@ __HELP__ = """
@app.on_message(filters.command("ai", COMMAND_HANDLER) & pyro_cooldown.wait(10))
@app.on_bot_business_message(filters.command("ai", COMMAND_HANDLER) & pyro_cooldown.wait(10))
@app.on_bot_business_message(
filters.command("ai", COMMAND_HANDLER) & pyro_cooldown.wait(10)
)
@use_chat_lang()
async def gemini_chatbot(_, ctx: Message, strings):
if len(ctx.command) == 1:
@ -36,18 +37,20 @@ async def gemini_chatbot(_, ctx: Message, strings):
return await ctx.reply_msg("GOOGLEAI_KEY env is missing!!!")
msg = await ctx.reply_msg(strings("find_answers_str"), quote=True)
try:
data = {
"query": ctx.text.split(maxsplit=1)[1],
"key": GOOGLEAI_KEY
}
data = {"query": ctx.text.split(maxsplit=1)[1], "key": GOOGLEAI_KEY}
# Fetch from API beacuse my VPS is not supported
response = await fetch.post(
"https://yasirapi.eu.org/gemini", data=data
)
response = await fetch.post("https://yasirapi.eu.org/gemini", data=data)
if not response.json().get("candidates"):
await ctx.reply_msg("⚠️ Sorry, the prompt you sent maybe contains a forbidden word that is not permitted by AI.")
await ctx.reply_msg(
"⚠️ Sorry, the prompt you sent maybe contains a forbidden word that is not permitted by AI."
)
else:
await ctx.reply_msg(html.escape(response.json()["candidates"][0]["content"]["parts"][0]["text"])+'\n<b>Powered by:</b> <code>Gemini Flash 1.5</code>')
await ctx.reply_msg(
html.escape(
response.json()["candidates"][0]["content"]["parts"][0]["text"]
)
+ "\n<b>Powered by:</b> <code>Gemini Flash 1.5</code>"
)
await msg.delete()
except Exception as e:
await ctx.reply_msg(str(e))
@ -101,9 +104,13 @@ async def openai_chatbot(_, ctx: Message, strings):
await msg.edit_msg(f"The server could not be reached because {e.__cause__}")
except RateLimitError as e:
if "billing details" in str(e):
return await msg.edit_msg("This openai key from this bot has expired, please give openai key donation for bot owner.")
return await msg.edit_msg(
"This openai key from this bot has expired, please give openai key donation for bot owner."
)
await msg.edit_msg("You're got rate limit, please try again later.")
except APIStatusError as e:
await msg.edit_msg(f"Another {e.status_code} status code was received with response {e.response}")
await msg.edit_msg(
f"Another {e.status_code} status code was received with response {e.response}"
)
except Exception as e:
await msg.edit_msg(f"ERROR: {e}")

View file

@ -34,7 +34,6 @@ from pyrogram.errors import (
FloodWait,
MessageTooLong,
PeerIdInvalid,
ReactionInvalid,
)
from pyrogram.raw.types import UpdateBotStopped
from pyrogram.types import (

View file

@ -3,17 +3,16 @@
# * @projectName MissKatyPyro
# * Copyright ©YasirPedia All rights reserved
import asyncio
import cloudscraper
import math
import os
import re
import time
from bs4 import BeautifulSoup
from cloudscraper import create_scraper
from datetime import datetime
from logging import getLogger
from urllib.parse import unquote
from bs4 import BeautifulSoup
from cloudscraper import create_scraper
from pyrogram import filters
from pyrogram.file_id import FileId
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
@ -194,21 +193,35 @@ async def instadl(_, message):
"Connection": "keep-alive",
"Referer": "https://saveig.app/id",
}
post = create_scraper().post("https://saveig.app/api/ajaxSearch", data={"q": link, "t": "media", "lang": "id"}, headers=headers)
post = create_scraper().post(
"https://saveig.app/api/ajaxSearch",
data={"q": link, "t": "media", "lang": "id"},
headers=headers,
)
if post.status_code not in [200, 401]:
return await message.reply("Unknown error.")
res = post.json()
if r := re.findall(r'href="(https?://(?!play\.google\.com|/)[^"]+)"', res["data"]):
if r := re.findall(
r'href="(https?://(?!play\.google\.com|/)[^"]+)"', res["data"]
):
res = r[0].replace("&amp;", "&")
fname = (await fetch.head(res)).headers.get("content-disposition", "").split("filename=")[1]
is_img = (await fetch.head(res)).headers.get("content-type").startswith("image")
fname = (
(await fetch.head(res))
.headers.get("content-disposition", "")
.split("filename=")[1]
)
is_img = (
(await fetch.head(res)).headers.get("content-type").startswith("image")
)
if is_img:
await message.reply_photo(res, caption=fname)
else:
await message.reply_video(res, caption=fname)
await msg.delete()
except Exception as e:
await message.reply(f"Failed to download instagram video..\n\n<b>Reason:</b> {e}")
await message.reply(
f"Failed to download instagram video..\n\n<b>Reason:</b> {e}"
)
await msg.delete()
@ -251,15 +264,29 @@ async def twitterdl(_, message):
if post.status_code not in [200, 401]:
return await msg.edit_msg("Unknown error.")
soup = BeautifulSoup(post.text, "lxml")
cekdata = soup.find("a", {"pure-button pure-button-primary is-center u-bl dl-button download_link without_watermark vignette_active"})
cekdata = soup.find(
"a",
{
"pure-button pure-button-primary is-center u-bl dl-button download_link without_watermark vignette_active"
},
)
if not cekdata:
return await message.reply("ERROR: Oops! It seems that this tweet doesn't have a video! Try later or check your link")
return await message.reply(
"ERROR: Oops! It seems that this tweet doesn't have a video! Try later or check your link"
)
try:
fname = (await fetch.head(cekdata.get("href"))).headers.get("content-disposition", "").split("filename=")[1]
fname = (
(await fetch.head(cekdata.get("href")))
.headers.get("content-disposition", "")
.split("filename=")[1]
)
obj = SmartDL(cekdata.get("href"), progress_bar=False, timeout=15)
obj.start()
path = obj.get_dest()
await message.reply_video(path, caption=f"<code>{fname}</code>\n\nUploaded for {message.from_user.mention} [<code>{message.from_user.id}</code>]",)
await message.reply_video(
path,
caption=f"<code>{fname}</code>\n\nUploaded for {message.from_user.mention} [<code>{message.from_user.id}</code>]",
)
except Exception as er:
LOGGER.error("ERROR: while fetching TwitterDL. %s", er)
return await msg.edit_msg("ERROR: Got error while extracting link.")
@ -284,8 +311,10 @@ async def tiktokdl(_, message):
"https://lovetik.com/api/ajax/search", data={"query": link}
)
).json()
fname = (await fetch.head(r["links"][0]["a"])).headers.get("content-disposition", "")
filename = unquote(fname.split('filename=')[1].strip('"').split('"')[0])
fname = (await fetch.head(r["links"][0]["a"])).headers.get(
"content-disposition", ""
)
filename = unquote(fname.split("filename=")[1].strip('"').split('"')[0])
await message.reply_video(
r["links"][0]["a"],
caption=f"<b>Title:</b> <code>{filename}</code>\n<b>Uploader</b>: <a href='https://www.tiktok.com/{r['author']}'>{r['author_name']}</a>\n\nUploaded for {message.from_user.mention} [<code>{message.from_user.id}</code>]",

View file

@ -23,20 +23,19 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import uuid
import asyncio
from database.feds_db import *
from misskaty import app, BOT_ID
from misskaty.vars import SUDO, LOG_GROUP_ID, COMMAND_HANDLER
import uuid
from pyrogram import filters
from pyrogram.enums import ChatMemberStatus, ChatType, ParseMode
from pyrogram.errors import FloodWait, PeerIdInvalid
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from misskaty.helper.functions import extract_user, extract_user_and_reason
from pyrogram.errors import FloodWait, PeerIdInvalid
from database.feds_db import *
from misskaty import BOT_ID, app
from misskaty.core.decorator.errors import capture_err
from misskaty.helper.functions import extract_user, extract_user_and_reason
from misskaty.vars import COMMAND_HANDLER, LOG_GROUP_ID, SUDO
__MODULE__ = "Federation"
__HELP__ = """
@ -451,7 +450,9 @@ async def get_all_fadmins_mentions(client, message):
fadmin_ids = fed_info.get("fadmins", [])
if not fadmin_ids:
return await message.reply_text(f"**Owner: {fed_info['owner_mention']}\n\nNo fadmins found in the federation.")
return await message.reply_text(
f"**Owner: {fed_info['owner_mention']}\n\nNo fadmins found in the federation."
)
user_mentions = []
for user_id in fadmin_ids:
@ -460,7 +461,10 @@ async def get_all_fadmins_mentions(client, message):
user_mentions.append(f"{user.mention}[`{user.id}`]")
except Exception:
user_mentions.append(f"● `Admin🥷`[`{user_id}`]")
reply_text = f"**Owner: {fed_info['owner_mention']}\n\nList of fadmins:**\n" + "\n".join(user_mentions)
reply_text = (
f"**Owner: {fed_info['owner_mention']}\n\nList of fadmins:**\n"
+ "\n".join(user_mentions)
)
await message.reply_text(reply_text)
@ -572,7 +576,9 @@ async def fban_user(client, message):
chat = message.chat
from_user = message.from_user
if message.chat.type == ChatType.PRIVATE:
return await message.reply_text("This command is specific to groups, not our pm!.")
return await message.reply_text(
"This command is specific to groups, not our pm!."
)
fed_id = await get_fed_id(chat.id)
if not fed_id:
return await message.reply_text("**This chat is not a part of any federation.")
@ -592,7 +598,9 @@ async def fban_user(client, message):
try:
user = await app.get_users(user_id)
except PeerIdInvalid:
return await message.reply_msg("Sorry, i never meet this user. So i cannot fban.")
return await message.reply_msg(
"Sorry, i never meet this user. So i cannot fban."
)
if not user_id:
return await message.reply_text("I can't find that user.")
if user_id in all_admins or user_id in SUDO:

View file

@ -24,8 +24,10 @@ from .ytdl_plugins import YT_DB
chat = [-1001128045651, -1001255283935, -1001455886928]
REQUEST_DB = {}
# This modules is only working for my movies group to help collect a list of film requests by members.
# @app.on_message(filters.regex(r"alamu'?ala[iy]ku+m", re.I) & filters.chat(chat))
async def salamregex(_, message):
await message.reply_text(text=f"Wa'alaikumsalam {message.from_user.mention} 😇")
@ -186,7 +188,8 @@ async def callbackreq(c, q):
[
[
InlineKeyboardButton(
text="✅ Request Completed", callback_data="reqcompl"
text="✅ Request Completed",
callback_data="reqcompl",
)
]
]
@ -199,7 +202,8 @@ async def callbackreq(c, q):
[
[
InlineKeyboardButton(
text="✅ Request Completed", callback_data="reqcompl"
text="✅ Request Completed",
callback_data="reqcompl",
)
]
]
@ -300,7 +304,8 @@ async def callbackreject(c, q):
[
[
InlineKeyboardButton(
text="🚫 Request Rejected", callback_data="reqreject"
text="🚫 Request Rejected",
callback_data="reqreject",
)
]
]
@ -313,7 +318,8 @@ async def callbackreject(c, q):
[
[
InlineKeyboardButton(
text="🚫 Request Rejected", callback_data="reqreject"
text="🚫 Request Rejected",
callback_data="reqreject",
)
]
]
@ -428,7 +434,8 @@ async def callbackaft_unav(_, q):
@app.on_callback_query(filters.regex(r"^reqavailable$"))
async def callbackaft_dahada(_, q):
await q.answer(
"Request ini sudah ada, silahkan cari 🔍 di channelnya yaa 😉..", show_alert=True
"Request ini sudah ada, silahkan cari 🔍 di channelnya yaa 😉..",
show_alert=True,
)

View file

@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import re
from pyrogram import filters
@ -55,7 +56,9 @@ You can use markdown or html to save text too.
"""
@app.on_message(filters.command(["addfilter", "filter"], COMMAND_HANDLER) & ~filters.private)
@app.on_message(
filters.command(["addfilter", "filter"], COMMAND_HANDLER) & ~filters.private
)
@adminsOnly("can_change_info")
async def save_filters(_, message):
try:
@ -80,7 +83,11 @@ async def save_filters(_, message):
elif not replied_message.text and not replied_message.caption:
data = None
else:
data = replied_message.text.markdown if replied_message.text else replied_message.caption.markdown
data = (
replied_message.text.markdown
if replied_message.text
else replied_message.caption.markdown
)
if replied_message.text:
_type = "text"
file_id = None
@ -110,7 +117,9 @@ async def save_filters(_, message):
file_id = replied_message.voice.file_id
if replied_message.reply_markup and "~" not in data:
if urls := extract_urls(replied_message.reply_markup):
response = "\n".join([f"{name}=[{text}, {url}]" for name, text, url in urls])
response = "\n".join(
[f"{name}=[{text}, {url}]" for name, text, url in urls]
)
data = data + response
name = name.replace("_", " ")
_filter = {
@ -121,7 +130,9 @@ async def save_filters(_, message):
await save_filter(chat_id, name, _filter)
return await message.reply_text(f"__**Saved filter {name}.**__")
except UnboundLocalError:
return await message.reply_text("**Replied message is inaccessible.\n`Forward the message and try again`**")
return await message.reply_text(
"**Replied message is inaccessible.\n`Forward the message and try again`**"
)
@app.on_message(filters.command("filters", COMMAND_HANDLER) & ~filters.private)
@ -137,7 +148,9 @@ async def get_filterss(_, m):
await m.reply_msg(msg)
@app.on_message(filters.command(["stop", "stopfilter"], COMMAND_HANDLER) & ~filters.private)
@app.on_message(
filters.command(["stop", "stopfilter"], COMMAND_HANDLER) & ~filters.private
)
@adminsOnly("can_change_info")
async def del_filter(_, m):
if len(m.command) < 2:
@ -159,7 +172,9 @@ async def del_filter(_, m):
)
async def filters_re(_, message):
text = message.text.lower().strip()
if not text or (message.command and message.command[0].lower() in ["filter", "addfilter"]):
if not text or (
message.command and message.command[0].lower() in ["filter", "addfilter"]
):
return
chat_id = message.chat.id
list_of_filters = await get_filters_names(chat_id)
@ -242,12 +257,16 @@ async def stop_all(_, message):
else:
keyboard = InlineKeyboardMarkup(
[
[InlineKeyboardButton("YES, DO IT", callback_data="stop_yes"),
InlineKeyboardButton("Cancel", callback_data="stop_no")
[
InlineKeyboardButton("YES, DO IT", callback_data="stop_yes"),
InlineKeyboardButton("Cancel", callback_data="stop_no"),
]
]
)
await message.reply_text("**Are you sure you want to delete all the filters in this chat forever ?.**", reply_markup=keyboard)
await message.reply_text(
"**Are you sure you want to delete all the filters in this chat forever ?.**",
reply_markup=keyboard,
)
@app.on_callback_query(filters.regex("stop_(.*)"))
@ -257,12 +276,17 @@ async def stop_all_cb(_, cb):
permissions = await member_permissions(chat_id, from_user.id)
permission = "can_change_info"
if permission not in permissions:
return await cb.answer(f"You don't have the required permission.\n Permission: {permission}", show_alert=True)
return await cb.answer(
f"You don't have the required permission.\n Permission: {permission}",
show_alert=True,
)
input = cb.data.split("_", 1)[1]
if input == "yes":
stoped_all = await deleteall_filters(chat_id)
if stoped_all:
return await cb.message.edit("**Successfully deleted all filters on this chat.**")
return await cb.message.edit(
"**Successfully deleted all filters on this chat.**"
)
if input == "no":
await cb.message.reply_to_message.delete()
await cb.message.delete()

View file

@ -1,8 +1,8 @@
import textwrap
import regex
from asyncio import gather
from os import remove as hapus
import regex
from PIL import Image, ImageDraw, ImageFont
from pyrogram import filters
from pyrogram.errors import MessageIdInvalid, PeerIdInvalid, ReactionInvalid
@ -201,16 +201,20 @@ async def beriharapan(c, m):
@user.on_message(filters.command("react", "."))
async def givereact(c, m):
if len(m.command) == 1:
return await m.reply("Please add reaction after command, you can give multiple reaction too.")
return await m.reply(
"Please add reaction after command, you can give multiple reaction too."
)
if not m.reply_to_message:
return await m.reply("Please reply to the message you want to react to.")
emot = list(regex.findall(r'\p{Emoji}', m.text))
emot = list(regex.findall(r"\p{Emoji}", m.text))
try:
await m.reply_to_message.react(emoji=emot)
except ReactionInvalid:
await m.reply("Please give valid reaction.")
except MessageIdInvalid:
await m.reply("Sorry, i couldn't react to other bots or without being as administrator.")
await m.reply(
"Sorry, i couldn't react to other bots or without being as administrator."
)
except PeerIdInvalid:
await m.reply("Sorry, i can't react chat without join that groups.")
except Exception as err:

View file

@ -1,9 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import math
import os
import time
@ -46,7 +47,9 @@ async def genss(self: Client, ctx: Message, strings):
file_name = os.path.basename(url)
download_file_path = os.path.join("downloads/", file_name)
try:
downloader = SmartDL(url, download_file_path, progress_bar=False, timeout=10, verify=False)
downloader = SmartDL(
url, download_file_path, progress_bar=False, timeout=10, verify=False
)
downloader.start(blocking=False)
except Exception as err:
return await pesan.edit(str(err))
@ -111,7 +114,9 @@ async def genss(self: Client, ctx: Message, strings):
)
await ctx.reply_msg(
strings("up_msg").format(
namma=ctx.from_user.mention if ctx.from_user else ctx.sender_chat.title,
namma=ctx.from_user.mention
if ctx.from_user
else ctx.sender_chat.title,
id=ctx.from_user.id if ctx.from_user else ctx.sender_chat.title,
bot_uname=self.me.username,
),
@ -178,7 +183,9 @@ async def genss(self: Client, ctx: Message, strings):
)
await ctx.reply_msg(
strings("up_msg").format(
namma=ctx.from_user.mention if ctx.from_user else ctx.sender_chat.title,
namma=ctx.from_user.mention
if ctx.from_user
else ctx.sender_chat.title,
id=ctx.from_user.id if ctx.from_user else ctx.sender_chat.id,
bot_uname=self.me.username,
),

View file

@ -16,8 +16,8 @@ from pyrogram.errors import (
)
from pyrogram.types import ChatMemberUpdated, InlineKeyboardButton, InlineKeyboardMarkup
from database.users_chats_db import db
from database.greetings_db import is_welcome, toggle_welcome
from database.users_chats_db import db
from misskaty import BOT_USERNAME, app
from misskaty.core.decorator import asyncify, capture_err
from misskaty.helper import fetch, use_chat_lang
@ -169,7 +169,9 @@ async def member_has_joined(c: app, member: ChatMemberUpdated, strings):
@app.adminsOnly("can_change_info")
async def welcome_toggle_handler(client, message):
is_enabled = await toggle_welcome(message.chat.id)
await message.reply_msg(f"Welcome messages are now {'enabled' if is_enabled else 'disabled'}.")
await message.reply_msg(
f"Welcome messages are now {'enabled' if is_enabled else 'disabled'}."
)
# ToDo with ChatMemberUpdated

View file

@ -3,13 +3,13 @@
# * @projectName MissKatyPyro
# * Copyright ©YasirPedia All rights reserved
import contextlib
import httpx
import json
import logging
import re
import sys
from urllib.parse import quote_plus
import httpx
from bs4 import BeautifulSoup
from deep_translator import GoogleTranslator
from pykeyboard import InlineButton, InlineKeyboard
@ -145,7 +145,9 @@ async def imdb_search_id(kueri, message):
return await k.edit_caption(
f"⛔️ Tidak ditemukan hasil untuk kueri: <code>{kueri}</code>"
)
msg += f"🎬 Ditemukan ({len(res)}) hasil untuk kueri: <code>{kueri}</code>\n\n"
msg += (
f"🎬 Ditemukan ({len(res)}) hasil untuk kueri: <code>{kueri}</code>\n\n"
)
for num, movie in enumerate(res, start=1):
title = movie.get("l")
if year := movie.get("yr"):
@ -207,7 +209,9 @@ async def imdb_search_en(kueri, message):
return await k.edit_caption(
f"⛔️ Result not found for keywords: <code>{kueri}</code>"
)
msg += f"🎬 Found ({len(res)}) result for keywords: <code>{kueri}</code>\n\n"
msg += (
f"🎬 Found ({len(res)}) result for keywords: <code>{kueri}</code>\n\n"
)
for num, movie in enumerate(res, start=1):
title = movie.get("l")
if year := movie.get("yr"):
@ -300,13 +304,17 @@ async def imdbcari(_, query: CallbackQuery):
InlineKeyboardButton(
text="🚩 Language", callback_data=f"imdbset#{uid}"
),
InlineKeyboardButton(text="❌ Close", callback_data=f"close#{uid}"),
InlineKeyboardButton(
text="❌ Close", callback_data=f"close#{uid}"
),
)
)
buttons.add(*BTN)
await query.message.edit_caption(msg, reply_markup=buttons)
except httpx.HTTPError as exc:
await query.message.edit_caption(f"HTTP Exception for IMDB Search - <code>{exc}</code>")
await query.message.edit_caption(
f"HTTP Exception for IMDB Search - <code>{exc}</code>"
)
except (MessageIdInvalid, MessageNotModified):
pass
except Exception as err:
@ -357,13 +365,17 @@ async def imdbcari(_, query: CallbackQuery):
InlineKeyboardButton(
text="🚩 Language", callback_data=f"imdbset#{uid}"
),
InlineKeyboardButton(text="❌ Close", callback_data=f"close#{uid}"),
InlineKeyboardButton(
text="❌ Close", callback_data=f"close#{uid}"
),
)
)
buttons.add(*BTN)
await query.message.edit_caption(msg, reply_markup=buttons)
except httpx.HTTPError as exc:
await query.message.edit_caption(f"HTTP Exception for IMDB Search - <code>{exc}</code>")
await query.message.edit_caption(
f"HTTP Exception for IMDB Search - <code>{exc}</code>"
)
except (MessageIdInvalid, MessageNotModified):
pass
except Exception as err:
@ -387,7 +399,9 @@ async def imdb_id_callback(self: Client, query: CallbackQuery):
r_json = json.loads(
sop.find("script", attrs={"type": "application/ld+json"}).contents[0]
)
ott = await search_jw(r_json.get("alternateName") or r_json.get("name"), "ID")
ott = await search_jw(
r_json.get("alternateName") or r_json.get("name"), "ID"
)
typee = r_json.get("@type", "")
res_str = ""
tahun = (
@ -402,7 +416,9 @@ async def imdb_id_callback(self: Client, query: CallbackQuery):
res_str += "\n"
if durasi := sop.select('li[data-testid="title-techspec_runtime"]'):
durasi = (
durasi[0].find(class_="ipc-metadata-list-item__content-container").text
durasi[0]
.find(class_="ipc-metadata-list-item__content-container")
.text
)
res_str += f"<b>Durasi:</b> <code>{GoogleTranslator('auto', 'id').translate(durasi)}</code>\n"
if kategori := r_json.get("contentRating"):
@ -420,9 +436,7 @@ async def imdb_id_callback(self: Client, query: CallbackQuery):
rilis_url = release[0].find(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)["href"]
res_str += (
f"<b>Rilis:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n"
)
res_str += f"<b>Rilis:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n"
if genre := r_json.get("genre"):
genre = "".join(
f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, "
@ -461,19 +475,26 @@ async def imdb_id_callback(self: Client, query: CallbackQuery):
)
res_str += f"<b>Penulis:</b> {creator[:-2]}\n"
if actors := r_json.get("actor"):
actor = "".join(f"<a href='{i['url']}'>{i['name']}</a>, " for i in actors)
actor = "".join(
f"<a href='{i['url']}'>{i['name']}</a>, " for i in actors
)
res_str += f"<b>Pemeran:</b> {actor[:-2]}\n\n"
if deskripsi := r_json.get("description"):
summary = GoogleTranslator("auto", "id").translate(deskripsi)
res_str += f"<b>📜 Plot:</b>\n<blockquote><code>{summary}</code></blockquote>\n\n"
if keywd := r_json.get("keywords"):
key_ = "".join(
f"#{i.replace(' ', '_').replace('-', '_')}, " for i in keywd.split(",")
f"#{i.replace(' ', '_').replace('-', '_')}, "
for i in keywd.split(",")
)
res_str += (
f"<b>🔥 Kata Kunci:</b>\n<blockquote>{key_[:-2]}</blockquote>\n"
)
res_str += f"<b>🔥 Kata Kunci:</b>\n<blockquote>{key_[:-2]}</blockquote>\n"
if award := sop.select('li[data-testid="award_information"]'):
awards = (
award[0].find(class_="ipc-metadata-list-item__list-content-item").text
award[0]
.find(class_="ipc-metadata-list-item__list-content-item")
.text
)
res_str += f"<b>🏆 Penghargaan:</b>\n<blockquote><code>{GoogleTranslator('auto', 'id').translate(awards)}</code></blockquote>\n"
else:
@ -521,15 +542,21 @@ async def imdb_id_callback(self: Client, query: CallbackQuery):
res_str, parse_mode=enums.ParseMode.HTML, reply_markup=markup
)
except Exception as err:
LOGGER.error(f"Terjadi error saat menampilkan data IMDB. ERROR: {err}")
LOGGER.error(
f"Terjadi error saat menampilkan data IMDB. ERROR: {err}"
)
else:
await query.message.edit_caption(
res_str, parse_mode=enums.ParseMode.HTML, reply_markup=markup
)
except httpx.HTTPError as exc:
await query.message.edit_caption(f"HTTP Exception for IMDB Search - <code>{exc}</code>")
await query.message.edit_caption(
f"HTTP Exception for IMDB Search - <code>{exc}</code>"
)
except AttributeError:
await query.message.edit_caption("Maaf, gagal mendapatkan info data dari IMDB.")
await query.message.edit_caption(
"Maaf, gagal mendapatkan info data dari IMDB."
)
except (MessageNotModified, MessageIdInvalid):
pass
@ -549,7 +576,9 @@ async def imdb_en_callback(self: Client, query: CallbackQuery):
r_json = json.loads(
sop.find("script", attrs={"type": "application/ld+json"}).contents[0]
)
ott = await search_jw(r_json.get("alternateName") or r_json.get("name"), "US")
ott = await search_jw(
r_json.get("alternateName") or r_json.get("name"), "US"
)
typee = r_json.get("@type", "")
res_str = ""
tahun = (
@ -564,7 +593,9 @@ async def imdb_en_callback(self: Client, query: CallbackQuery):
res_str += "\n"
if durasi := sop.select('li[data-testid="title-techspec_runtime"]'):
durasi = (
durasi[0].find(class_="ipc-metadata-list-item__content-container").text
durasi[0]
.find(class_="ipc-metadata-list-item__content-container")
.text
)
res_str += f"<b>Duration:</b> <code>{durasi}</code>\n"
if kategori := r_json.get("contentRating"):
@ -582,9 +613,7 @@ async def imdb_en_callback(self: Client, query: CallbackQuery):
rilis_url = release[0].find(
class_="ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link"
)["href"]
res_str += (
f"<b>Rilis:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n"
)
res_str += f"<b>Rilis:</b> <a href='https://www.imdb.com{rilis_url}'>{rilis}</a>\n"
if genre := r_json.get("genre"):
genre = "".join(
f"{GENRES_EMOJI[i]} #{i.replace('-', '_').replace(' ', '_')}, "
@ -612,7 +641,8 @@ async def imdb_en_callback(self: Client, query: CallbackQuery):
res_str += "\n<b>🙎 Cast Info:</b>\n"
if r_json.get("director"):
director = "".join(
f"<a href='{i['url']}'>{i['name']}</a>, " for i in r_json["director"]
f"<a href='{i['url']}'>{i['name']}</a>, "
for i in r_json["director"]
)
res_str += f"<b>Director:</b> {director[:-2]}\n"
if r_json.get("creator"):
@ -634,10 +664,14 @@ async def imdb_en_callback(self: Client, query: CallbackQuery):
f"#{i.replace(' ', '_').replace('-', '_')}, "
for i in r_json["keywords"].split(",")
)
res_str += f"<b>🔥 Keywords:</b>\n<blockquote>{key_[:-2]}</blockquote>\n"
res_str += (
f"<b>🔥 Keywords:</b>\n<blockquote>{key_[:-2]}</blockquote>\n"
)
if award := sop.select('li[data-testid="award_information"]'):
awards = (
award[0].find(class_="ipc-metadata-list-item__list-content-item").text
award[0]
.find(class_="ipc-metadata-list-item__list-content-item")
.text
)
res_str += f"<b>🏆 Awards:</b>\n<blockquote><code>{awards}</code></blockquote>\n"
else:
@ -691,7 +725,9 @@ async def imdb_en_callback(self: Client, query: CallbackQuery):
res_str, parse_mode=enums.ParseMode.HTML, reply_markup=markup
)
except httpx.HTTPError as exc:
await query.message.edit_caption(f"HTTP Exception for IMDB Search - <code>{exc}</code>")
await query.message.edit_caption(
f"HTTP Exception for IMDB Search - <code>{exc}</code>"
)
except AttributeError:
await query.message.edit_caption("Sorry, failed getting data from IMDB.")
except (MessageNotModified, MessageIdInvalid):

View file

@ -117,9 +117,9 @@ async def inline_menu(self, inline_query: InlineQuery):
description="New Calculator",
input_message_content=InputTextMessageContent(
message_text=f"Made by @{self.me.username}",
disable_web_page_preview=True
disable_web_page_preview=True,
),
reply_markup=calc_btn(inline_query.from_user.id)
reply_markup=calc_btn(inline_query.from_user.id),
)
]
else:
@ -130,9 +130,8 @@ async def inline_menu(self, inline_query: InlineQuery):
title="Answer",
description=f"Result: {result}",
input_message_content=InputTextMessageContent(
message_text=f"{data} = {result}",
disable_web_page_preview=True
)
message_text=f"{data} = {result}", disable_web_page_preview=True
),
)
]
await inline_query.answer(
@ -731,7 +730,9 @@ async def imdb_inl(_, query):
f"#{i.replace(' ', '_').replace('-', '_')}, "
for i in r_json["keywords"].split(",")
)
res_str += f"<b>🔥 Kata Kunci:</b>\n<blockquote>{key_[:-2]}</blockquote>\n"
res_str += (
f"<b>🔥 Kata Kunci:</b>\n<blockquote>{key_[:-2]}</blockquote>\n"
)
if award := sop.select('li[data-testid="award_information"]'):
awards = (
award[0]

View file

@ -1,8 +1,8 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import os

View file

@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import asyncio
from logging import getLogger
@ -178,7 +179,7 @@ async def locks_func(_, message):
chat_id,
ChatPermissions(
all_perms=True,
)
),
)
await message.reply(f"Unlocked Everything in {message.chat.title}")
except ChatAdminRequired:

View file

@ -1,9 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @created 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
* @author yasir <yasiramunandar@gmail.com>
* @created 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import json
import os
import traceback

View file

@ -1,9 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import io
import subprocess
import time
@ -66,7 +67,9 @@ DETAILS
)
except:
try:
link = await post_to_telegraph(False, "MissKaty MediaInfo", f"<code>{body_text}</code>")
link = await post_to_telegraph(
False, "MissKaty MediaInfo", f"<code>{body_text}</code>"
)
markup = InlineKeyboardMarkup(
[[InlineKeyboardButton(text=strings("viweb"), url=link)]]
)
@ -76,7 +79,11 @@ DETAILS
out_file.name = "MissKaty_Mediainfo.txt"
await ctx.reply_document(
out_file,
caption=strings("capt_media").format(ment=ctx.from_user.mention if ctx.from_user else ctx.sender_chat.title),
caption=strings("capt_media").format(
ment=ctx.from_user.mention
if ctx.from_user
else ctx.sender_chat.title
),
thumb="assets/thumb.jpg",
reply_markup=markup,
)
@ -119,7 +126,11 @@ DETAILS
out_file.name = "MissKaty_Mediainfo.txt"
await ctx.reply_document(
out_file,
caption=strings("capt_media").format(ment=ctx.from_user.mention if ctx.from_user else ctx.sender_chat.title),
caption=strings("capt_media").format(
ment=ctx.from_user.mention
if ctx.from_user
else ctx.sender_chat.title
),
thumb="assets/thumb.jpg",
reply_markup=markup,
)

View file

@ -5,6 +5,7 @@
* Copyright @YasirPedia All rights reserved
"""
import ast
import asyncio
import contextlib
import html
@ -73,11 +74,11 @@ def remove_html_tags(text):
def calcExpression(text):
try:
return float(eval(text))
return float(ast.literal_eval(text))
except (SyntaxError, ZeroDivisionError):
return ""
except TypeError:
return float(eval(text.replace("(", "*(")))
return float(ast.literal_eval(text.replace("(", "*(")))
except Exception as e:
LOGGER.error(e, exc_info=True)
return ""

View file

@ -5,7 +5,6 @@
import platform
import re
from datetime import datetime, timedelta
from attr import Attribute
import pytz
from apscheduler.jobstores.base import ConflictingIdError
@ -17,7 +16,7 @@ from pyrogram.errors import (
ChatNotModified,
ChatRestricted,
PeerIdInvalid,
QueryIdInvalid
QueryIdInvalid,
)
from pyrogram.types import ChatPermissions, InlineKeyboardButton, InlineKeyboardMarkup
@ -241,7 +240,7 @@ async def nightmode_handler(self, msg, strings):
can_send_roundvideos=msg.chat.permissions.can_send_roundvideos,
can_send_stickers=msg.chat.permissions.can_send_stickers,
can_send_videos=msg.chat.permissions.can_send_videos,
can_send_voices=msg.chat.permissions.can_send_voices
can_send_voices=msg.chat.permissions.can_send_voices,
)
try:
# schedule to enable nightmode

View file

@ -21,19 +21,25 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from re import findall
from pyrogram import filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from database.notes_db import delete_note, get_note, get_note_names, save_note, deleteall_notes
from database.notes_db import (
delete_note,
deleteall_notes,
get_note,
get_note_names,
save_note,
)
from misskaty import app
from misskaty.vars import COMMAND_HANDLER
from misskaty.core.decorator.errors import capture_err
from misskaty.core.decorator.permissions import adminsOnly, member_permissions
from misskaty.core.keyboard import ikb
from misskaty.helper.functions import extract_text_and_keyb, extract_urls
from misskaty.vars import COMMAND_HANDLER
__MODULE__ = "Notes"
__HELP__ = """/notes To Get All The Notes In The Chat.
@ -51,12 +57,16 @@ To change caption of any files use.\n/save [NOTE_NAME] or /addnote [NOTE_NAME] [
"""
@app.on_message(filters.command(["addnote", "save"], COMMAND_HANDLER) & ~filters.private)
@app.on_message(
filters.command(["addnote", "save"], COMMAND_HANDLER) & ~filters.private
)
@adminsOnly("can_change_info")
async def save_notee(_, message):
try:
if len(message.command) < 2 or not message.reply_to_message:
await message.reply_msg("**Usage:**\nReply to a message with /save [NOTE_NAME] to save a new note.")
await message.reply_msg(
"**Usage:**\nReply to a message with /save [NOTE_NAME] to save a new note."
)
else:
text = message.text.markdown
name = text.split(None, 1)[1].strip()
@ -74,7 +84,11 @@ async def save_notee(_, message):
elif not replied_message.text and not replied_message.caption:
data = None
else:
data = replied_message.text.markdown if replied_message.text else replied_message.caption.markdown
data = (
replied_message.text.markdown
if replied_message.text
else replied_message.caption.markdown
)
if replied_message.text:
_type = "text"
file_id = None
@ -104,7 +118,9 @@ async def save_notee(_, message):
file_id = replied_message.voice.file_id
if replied_message.reply_markup and "~" not in data:
if urls := extract_urls(replied_message.reply_markup):
response = "\n".join([f"{name}=[{text}, {url}]" for name, text, url in urls])
response = "\n".join(
[f"{name}=[{text}, {url}]" for name, text, url in urls]
)
data = data + response
note = {
"type": _type,
@ -116,7 +132,9 @@ async def save_notee(_, message):
await save_note(chat_id, name, note)
await message.reply_msg(f"__**Saved note {name}.**__")
except UnboundLocalError:
return await message.reply_text("**Replied message is inaccessible.\n`Forward the message and try again`**")
return await message.reply_text(
"**Replied message is inaccessible.\n`Forward the message and try again`**"
)
@app.on_message(filters.command("notes", COMMAND_HANDLER) & ~filters.private)
@ -206,7 +224,9 @@ async def get_one_note(self, message):
)
@app.on_message(filters.command(["delnote", "clear"], COMMAND_HANDLER) & ~filters.private)
@app.on_message(
filters.command(["delnote", "clear"], COMMAND_HANDLER) & ~filters.private
)
@adminsOnly("can_change_info")
async def del_note(_, message):
if len(message.command) < 2:
@ -233,12 +253,16 @@ async def delete_all(_, message):
return await message.reply_text("**No notes in this chat.**")
keyboard = InlineKeyboardMarkup(
[
[InlineKeyboardButton("YES, DO IT", callback_data="delete_yes"),
InlineKeyboardButton("Cancel", callback_data="delete_no")
[
InlineKeyboardButton("YES, DO IT", callback_data="delete_yes"),
InlineKeyboardButton("Cancel", callback_data="delete_no"),
]
]
)
await message.reply_text("**Are you sure you want to delete all the notes in this chat forever ?.**", reply_markup=keyboard)
await message.reply_text(
"**Are you sure you want to delete all the notes in this chat forever ?.**",
reply_markup=keyboard,
)
@app.on_callback_query(filters.regex("delete_(.*)"))
@ -248,9 +272,14 @@ async def delete_all_cb(_, cb):
permissions = await member_permissions(chat_id, from_user.id)
permission = "can_change_info"
if permission not in permissions:
return await cb.answer(f"You don't have the required permission.\n Permission: {permission}", show_alert=True)
return await cb.answer(
f"You don't have the required permission.\n Permission: {permission}",
show_alert=True,
)
input = cb.data.split("_", 1)[1]
if input == "yes":
stoped_all = await deleteall_notes(chat_id)
if stoped_all:
return await cb.message.edit("**Successfully deleted all notes on this chat.**")
return await cb.message.edit(
"**Successfully deleted all notes on this chat.**"
)

View file

@ -1,11 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import os
from pyrogram import filters

View file

@ -1,9 +1,10 @@
"""
* @author Yasir Aris M <yasiramunandar@gmail.com>
* @created 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
* @author Yasir Aris M <yasiramunandar@gmail.com>
* @created 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
from json import loads as json_loads
from os import remove
from re import compile as compiles
@ -214,7 +215,9 @@ async def wastepaste(_, message):
"expire_at": 0,
"expire_in": 0,
}
response = await fetch.post("https://paste.yasir.eu.org/api/new", json=json_data)
response = await fetch.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 msg.edit_msg(f"ERROR: {e}")
@ -282,7 +285,9 @@ async def nekopaste(_, message):
try:
x = (
await fetch.post("https://nekobin.com/api/documents", json={"content": data})
await fetch.post(
"https://nekobin.com/api/documents", json={"content": data}
)
).json()
url = f"https://nekobin.com/{x['result']['key']}"
except Exception as e:

View file

@ -1,9 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import platform
import time
from asyncio import Lock
@ -18,9 +19,9 @@ from misskaty import app, botStartTime, misskaty_version
from misskaty.helper.human_read import get_readable_time
from misskaty.vars import COMMAND_HANDLER
PING_LOCK = Lock()
@app.on_message(filters.command(["ping"], COMMAND_HANDLER))
async def ping(_, ctx: Message):
currentTime = get_readable_time(time.time() - botStartTime)

View file

@ -1,9 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2023-01-23 19:41:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
* @author yasir <yasiramunandar@gmail.com>
* @date 2023-01-23 19:41:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
from pykeyboard import InlineButton, InlineKeyboard
from pyrogram import filters
from pyrogram.errors import MessageTooLong, QueryIdInvalid

View file

@ -33,7 +33,6 @@ __HELP__ = """
/genstring - Generate string session using this bot. Only support Pyrogram v2 and Telethon.
"""
ask_ques = "**» Please choose the library for which you want generate string :**\n\nNote: I'm not collecting any personal info from this feature, you can deploy own bot if you want."
buttons_ques = [
[

View file

@ -1,9 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import re
from pyrogram import Client, filters
@ -20,7 +21,6 @@ from misskaty.helper import bot_sys_stats, paginate_modules
from misskaty.helper.localization import use_chat_lang
from misskaty.vars import COMMAND_HANDLER
home_keyboard_pm = InlineKeyboardMarkup(
[
[
@ -104,13 +104,17 @@ async def start(self, ctx: Message, strings):
strings("help_name").format(mod=HELPABLE[module].__MODULE__)
+ HELPABLE[module].__HELP__
)
await ctx.reply_msg(text, disable_web_page_preview=True, message_effect_id=5104841245755180586)
await ctx.reply_msg(
text,
disable_web_page_preview=True,
message_effect_id=5104841245755180586,
)
if module == "federation":
return await ctx.reply(
text=text,
reply_markup=FED_MARKUP,
disable_web_page_preview=True,
message_effect_id=5104841245755180586
message_effect_id=5104841245755180586,
)
await ctx.reply(
text,
@ -118,13 +122,12 @@ async def start(self, ctx: Message, strings):
[[InlineKeyboardButton("back", callback_data="help_back")]]
),
disable_web_page_preview=True,
message_effect_id=5104841245755180586)
message_effect_id=5104841245755180586,
)
elif name == "help":
text, keyb = await help_parser(ctx.from_user.first_name)
await ctx.reply_msg(
text,
reply_markup=keyb,
message_effect_id=5104841245755180586
text, reply_markup=keyb, message_effect_id=5104841245755180586
)
else:
await self.send_photo(
@ -133,7 +136,7 @@ async def start(self, ctx: Message, strings):
caption=home_text_pm,
reply_markup=home_keyboard_pm,
reply_to_message_id=ctx.id,
message_effect_id=5104841245755180586
message_effect_id=5104841245755180586,
)
@ -144,7 +147,7 @@ async def commands_callbacc(_, cb: CallbackQuery):
cb.message.chat.id,
text=text,
reply_markup=keyb,
message_effect_id=5104841245755180586
message_effect_id=5104841245755180586,
)
await cb.message.delete_msg()
@ -187,19 +190,26 @@ async def help_command(_, ctx: Message, strings):
strings("help_name").format(mod=HELPABLE[name].__MODULE__)
+ HELPABLE[name].__HELP__
)
await ctx.reply_msg(text, disable_web_page_preview=True, message_effect_id=5104841245755180586)
await ctx.reply_msg(
text,
disable_web_page_preview=True,
message_effect_id=5104841245755180586,
)
else:
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,
message_effect_id=5104841245755180586
message_effect_id=5104841245755180586,
)
else:
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, message_effect_id=5104841245755180586
text,
reply_markup=help_keyboard,
disable_web_page_preview=True,
message_effect_id=5104841245755180586,
)

View file

@ -307,7 +307,7 @@ async def kang_sticker(self: Client, ctx: Message, strings):
),
emoji=sticker_emoji,
)
]
],
)
)
except PeerIdInvalid:

View file

@ -1,9 +1,10 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
* @author yasir <yasiramunandar@gmail.com>
* @date 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
# Code in this plugin to learn basic userbot in pyrogram
import os
from datetime import datetime

View file

@ -1,17 +1,18 @@
"""
* @author yasir <yasiramunandar@gmail.com>
* @created 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
* @author yasir <yasiramunandar@gmail.com>
* @created 2022-12-01 09:12:27
* @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved
"""
import contextlib
import httpx
import logging
import re
import sys
import traceback
import cloudscraper
import httpx
from bs4 import BeautifulSoup
from cachetools import TTLCache
from pykeyboard import InlineButton, InlineKeyboard
@ -20,7 +21,7 @@ from pyrogram.types import Message
from database import dbname
from misskaty import app
from misskaty.helper import Cache, Kusonime, fetch, use_chat_lang, post_to_telegraph
from misskaty.helper import Cache, Kusonime, fetch, post_to_telegraph, use_chat_lang
__MODULE__ = "WebScraper"
__HELP__ = """
@ -76,28 +77,28 @@ async def getDataTerbit21(msg, kueri, CurrentPage, strings):
with contextlib.redirect_stdout(sys.stderr):
try:
if kueri:
terbitjson = await fetch.get(f"{web['yasirapi']}/terbit21?q={kueri}")
terbitjson = await fetch.get(
f"{web['yasirapi']}/terbit21?q={kueri}"
)
else:
terbitjson = await fetch.get(f"{web['yasirapi']}/terbit21")
terbitjson.raise_for_status()
except httpx.HTTPError as exc:
await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>")
await msg.edit_msg(
f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>"
)
return None, None
res = terbitjson.json()
if not res.get("result"):
await msg.edit_msg(strings("no_result"), del_in=5)
return None, None
SCRAP_DICT.add(
msg.id, [split_arr(res["result"], 6), kueri], timeout=1800
)
SCRAP_DICT.add(msg.id, [split_arr(res["result"], 6), kueri], timeout=1800)
index = int(CurrentPage - 1)
PageLen = len(SCRAP_DICT[msg.id][0])
if kueri:
TerbitRes = strings("header_with_query").format(web="Terbit21", kueri=kueri)
else:
TerbitRes = strings("header_no_query").format(
web="Terbit21", cmd="terbit21"
)
TerbitRes = strings("header_no_query").format(web="Terbit21", cmd="terbit21")
for c, i in enumerate(SCRAP_DICT[msg.id][0][index], start=1):
TerbitRes += f"<b>{index*6+c}. <a href='{i['link']}'>{i['judul']}</a></b>\n<b>{strings('cat_text')}:</b> <code>{i['kategori']}</code>\n"
TerbitRes += (
@ -119,7 +120,9 @@ async def getDatalk21(msg, kueri, CurrentPage, strings):
lk21json = await fetch.get(f"{web['yasirapi']}/lk21")
lk21json.raise_for_status()
except httpx.HTTPError as exc:
await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>")
await msg.edit_msg(
f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>"
)
return None, None
res = lk21json.json()
if not res.get("result"):
@ -129,9 +132,7 @@ async def getDatalk21(msg, kueri, CurrentPage, strings):
index = int(CurrentPage - 1)
PageLen = len(SCRAP_DICT[msg.id][0])
if kueri:
lkResult = strings("header_with_query").format(
web="Layarkaca21", kueri=kueri
)
lkResult = strings("header_with_query").format(web="Layarkaca21", kueri=kueri)
else:
lkResult = strings("header_no_query").format(web="Layarkaca21", cmd="lk21")
for c, i in enumerate(SCRAP_DICT[msg.id][0][index], start=1):
@ -150,12 +151,18 @@ async def getDataPahe(msg, kueri, CurrentPage, strings):
with contextlib.redirect_stdout(sys.stderr):
try:
if kueri:
pahejson = await fetch.get(f"{web['yasirapi']}/pahe?q={kueri}&domain={web['pahe']}")
pahejson = await fetch.get(
f"{web['yasirapi']}/pahe?q={kueri}&domain={web['pahe']}"
)
else:
pahejson = await fetch.get(f"{web['yasirapi']}/pahe?domain={web['pahe']}")
pahejson = await fetch.get(
f"{web['yasirapi']}/pahe?domain={web['pahe']}"
)
pahejson.raise_for_status()
except httpx.HTTPError as exc:
await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>")
await msg.edit_msg(
f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>"
)
return None, None
res = pahejson.json()
if not res.get("result"):
@ -170,9 +177,7 @@ async def getDataPahe(msg, kueri, CurrentPage, strings):
else strings("header_no_query").format(web="Pahe", cmd="pahe")
)
for c, i in enumerate(SCRAP_DICT[msg.id][0][index], start=1):
paheResult += (
f"<b>{index*6+c}. <a href='{i['link']}'>{i['judul']}</a></b>\n\n"
)
paheResult += f"<b>{index*6+c}. <a href='{i['link']}'>{i['judul']}</a></b>\n\n"
return paheResult, PageLen
@ -187,7 +192,10 @@ async def getDataKuso(msg, kueri, CurrentPage, user, strings):
)
data.raise_for_status()
except httpx.HTTPError as exc:
await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>", disable_web_page_preview=True)
await msg.edit_msg(
f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>",
disable_web_page_preview=True,
)
return None, 0, None, None
res = BeautifulSoup(data, "lxml").find_all("h2", {"class": "episodeye"})
for i in res:
@ -237,7 +245,9 @@ async def getDataMovieku(msg, kueri, CurrentPage, strings):
)
data.raise_for_status()
except httpx.HTTPError as exc:
await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>")
await msg.edit_msg(
f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>"
)
return None, None
r = BeautifulSoup(data, "lxml")
res = r.find_all(class_="bx")
@ -271,11 +281,15 @@ async def getDataNodrakor(msg, kueri, CurrentPage, user, strings):
with contextlib.redirect_stdout(sys.stderr):
try:
data = await fetch.get(
f"{web['nodrakor']}/?s={kueri}", follow_redirects=True,
f"{web['nodrakor']}/?s={kueri}",
follow_redirects=True,
)
data.raise_for_status()
except httpx.HTTPError as exc:
await msg.edit_msg(f"HTTP Exception for {exc.request.url} - <code>{exc}</code>", disable_web_page_preview=True)
await msg.edit_msg(
f"HTTP Exception for {exc.request.url} - <code>{exc}</code>",
disable_web_page_preview=True,
)
return None, 0, None
text = BeautifulSoup(data, "lxml")
entry = text.find_all(class_="entry-header")
@ -319,11 +333,15 @@ async def getDataSavefilm21(msg, kueri, CurrentPage, user, strings):
with contextlib.redirect_stdout(sys.stderr):
try:
data = await fetch.get(
f"{web['savefilm21']}/?s={kueri}", follow_redirects=True,
f"{web['savefilm21']}/?s={kueri}",
follow_redirects=True,
)
data.raise_for_status()
except httpx.HTTPError as exc:
await msg.edit_msg(f"HTTP Exception for {exc.request.url} - <code>{exc}</code>", disable_web_page_preview=True)
await msg.edit_msg(
f"HTTP Exception for {exc.request.url} - <code>{exc}</code>",
disable_web_page_preview=True,
)
return None, 0, None
text = BeautifulSoup(data, "lxml")
entry = text.find_all(class_="entry-header")
@ -367,13 +385,17 @@ async def getDataLendrive(msg, kueri, CurrentPage, user, strings):
try:
if kueri:
data = await fetch.get(
f"{web['lendrive']}/?s={kueri}", follow_redirects=True,
f"{web['lendrive']}/?s={kueri}",
follow_redirects=True,
)
else:
data = await fetch.get(web["lendrive"], follow_redirects=True)
data.raise_for_status()
except httpx.HTTPError as exc:
await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>", disable_web_page_preview=True)
await msg.edit_msg(
f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>",
disable_web_page_preview=True,
)
return None, 0, None
res = BeautifulSoup(data, "lxml")
lenddata = []
@ -391,7 +413,12 @@ async def getDataLendrive(msg, kueri, CurrentPage, user, strings):
else o.find(class_="typez BD")
)
lenddata.append(
{"judul": title, "link": link, "quality": kualitas or "N/A", "status": status}
{
"judul": title,
"link": link,
"quality": kualitas or "N/A",
"status": status,
}
)
if not lenddata:
await msg.edit_msg(strings("no_result"), del_in=5)
@ -422,11 +449,15 @@ async def getDataMelong(msg, kueri, CurrentPage, user, strings):
with contextlib.redirect_stdout(sys.stderr):
try:
data = await fetch.get(
f"{web['melongmovie']}/?s={kueri}", follow_redirects=True,
f"{web['melongmovie']}/?s={kueri}",
follow_redirects=True,
)
data.raise_for_status()
except httpx.HTTPError as exc:
await msg.edit_msg(f"HTTP Exception for {exc.request.url} - <code>{exc}</code>", disable_web_page_preview=True)
await msg.edit_msg(
f"HTTP Exception for {exc.request.url} - <code>{exc}</code>",
disable_web_page_preview=True,
)
return None, 0, None
bs4 = BeautifulSoup(data, "lxml")
melongdata = []
@ -472,7 +503,10 @@ async def getDataGomov(msg, kueri, CurrentPage, user, strings):
)
gomovv.raise_for_status()
except httpx.HTTPError as exc:
await msg.edit_msg(f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>", disable_web_page_preview=True)
await msg.edit_msg(
f"ERROR: Failed to fetch data from {exc.request.url} - <code>{exc}</code>",
disable_web_page_preview=True,
)
return None, 0, None
text = BeautifulSoup(gomovv, "lxml")
entry = text.find_all(class_="entry-header")
@ -634,7 +668,7 @@ async def pahe_s(_, message, strings):
# Gomov CMD
@app.on_cmd(["gomov","klikxxi"], no_channel=True)
@app.on_cmd(["gomov", "klikxxi"], no_channel=True)
@use_chat_lang()
async def gomov_s(self, message, strings):
kueri = " ".join(message.command[1:])
@ -1287,7 +1321,9 @@ async def kusonime_scrap(client, callback_query, strings):
)
try:
if init_url := data_kuso.get(link, False):
await callback_query.message.edit_msg(init_url.get("ph_url"), reply_markup=keyboard)
await callback_query.message.edit_msg(
init_url.get("ph_url"), reply_markup=keyboard
)
tgh = await kuso.telegraph(link, client.me.username)
data_kuso[link] = {"ph_url": tgh}
return await callback_query.message.edit_msg(tgh, reply_markup=keyboard)
@ -1332,9 +1368,14 @@ async def savefilm21_scrap(_, callback_query, strings):
strings("res_scrape").format(link=link, kl=res), reply_markup=keyboard
)
except httpx.HTTPError as exc:
await callback_query.message.edit_msg(f"HTTP Exception for {exc.request.url} - <code>{exc}</code>", reply_markup=keyboard)
await callback_query.message.edit_msg(
f"HTTP Exception for {exc.request.url} - <code>{exc}</code>",
reply_markup=keyboard,
)
except Exception as err:
await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard)
await callback_query.message.edit_msg(
f"ERROR: {err}", reply_markup=keyboard
)
# NoDrakor DDL
@ -1367,26 +1408,35 @@ async def nodrakorddl_scrap(_, callback_query, strings):
html.raise_for_status()
soup = BeautifulSoup(html.text, "lxml")
if "/tv/" in link:
result = soup.find("div", {"entry-content entry-content-single"}).find_all("p")
result = soup.find(
"div", {"entry-content entry-content-single"}
).find_all("p")
msg = "".join(str(f"{i}\n") for i in result)
link = await post_to_telegraph(False, "MissKaty NoDrakor", msg)
return await callback_query.message.edit_msg(
strings("res_scrape").format(link=link, kl=link), reply_markup=keyboard
strings("res_scrape").format(link=link, kl=link),
reply_markup=keyboard,
)
res = soup.find_all(class_="button button-shadow")
res = "".join(f"{i.text}\n{i['href']}\n\n" for i in res)
if len(res) > 3500:
link = await post_to_telegraph(False, "MissKaty NoDrakor", res)
return await callback_query.message.edit_msg(
strings("res_scrape").format(link=link, kl=link), reply_markup=keyboard
strings("res_scrape").format(link=link, kl=link),
reply_markup=keyboard,
)
await callback_query.message.edit_msg(
strings("res_scrape").format(link=link, kl=res), reply_markup=keyboard
)
except httpx.HTTPError as exc:
await callback_query.message.edit_msg(f"HTTP Exception for {exc.request.url} - <code>{exc}</code>", reply_markup=keyboard)
await callback_query.message.edit_msg(
f"HTTP Exception for {exc.request.url} - <code>{exc}</code>",
reply_markup=keyboard,
)
except Exception as err:
await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard)
await callback_query.message.edit_msg(
f"ERROR: {err}", reply_markup=keyboard
)
# Scrape Link Download Movieku.CC
@ -1409,14 +1459,18 @@ async def muviku_scrap(_, message, strings):
data.append({"link": link, "kualitas": kualitas})
if not data:
return await message.reply(strings("no_result"))
res = "".join(f"<b>Host: {i['kualitas']}</b>\n{i['link']}\n\n" for i in data)
res = "".join(
f"<b>Host: {i['kualitas']}</b>\n{i['link']}\n\n" for i in data
)
await message.reply(res)
except IndexError:
return await message.reply(
strings("invalid_cmd_scrape").format(cmd=message.command[0])
)
except httpx.HTTPError as exc:
await message.reply(f"HTTP Exception for {exc.request.url} - <code>{exc}</code>")
await message.reply(
f"HTTP Exception for {exc.request.url} - <code>{exc}</code>"
)
except Exception as e:
await message.reply(f"ERROR: {str(e)}")
@ -1459,9 +1513,14 @@ async def melong_scrap(_, callback_query, strings):
strings("res_scrape").format(link=link, kl=rep), reply_markup=keyboard
)
except httpx.HTTPError as exc:
await callback_query.message.edit_msg(f"HTTP Exception for {exc.request.url} - <code>{exc}</code>", reply_markup=keyboard)
await callback_query.message.edit_msg(
f"HTTP Exception for {exc.request.url} - <code>{exc}</code>",
reply_markup=keyboard,
)
except Exception as err:
await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard)
await callback_query.message.edit_msg(
f"ERROR: {err}", reply_markup=keyboard
)
# Scrape DDL Link Gomov
@ -1503,9 +1562,14 @@ async def gomov_dl(_, callback_query, strings):
strings("res_scrape").format(link=link, kl=hasil), reply_markup=keyboard
)
except httpx.HTTPError as exc:
await callback_query.message.edit_msg(f"HTTP Exception for {exc.request.url} - <code>{exc}</code>", reply_markup=keyboard)
await callback_query.message.edit_msg(
f"HTTP Exception for {exc.request.url} - <code>{exc}</code>",
reply_markup=keyboard,
)
except Exception as err:
await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard)
await callback_query.message.edit_msg(
f"ERROR: {err}", reply_markup=keyboard
)
@app.on_cb("lendriveextract#")
@ -1541,12 +1605,18 @@ 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")
f"[ <a href='{a.get('href')}'>{a.text}</a> ]\n"
for a in i.findAll("a")
)
await callback_query.message.edit_msg(
strings("res_scrape").format(link=link, kl=kl), reply_markup=keyboard
)
except httpx.HTTPError as exc:
await callback_query.message.edit_msg(f"HTTP Exception for {exc.request.url} - <code>{exc}</code>", reply_markup=keyboard)
await callback_query.message.edit_msg(
f"HTTP Exception for {exc.request.url} - <code>{exc}</code>",
reply_markup=keyboard,
)
except Exception as err:
await callback_query.message.edit_msg(f"ERROR: {err}", reply_markup=keyboard)
await callback_query.message.edit_msg(
f"ERROR: {err}", reply_markup=keyboard
)

View file

@ -33,7 +33,9 @@ async def take_ss(_, ctx: Message, strings):
msg = await ctx.reply_msg(strings("wait_str"))
try:
url = f"https://webss.yasirweb.eu.org/api/screenshot?resX=1280&resY=900&outFormat=jpg&waitTime=1000&isFullPage=false&dismissModals=false&url={url}"
downloader = SmartDL(url, download_file_path, progress_bar=False, timeout=15, verify=False)
downloader = SmartDL(
url, download_file_path, progress_bar=False, timeout=15, verify=False
)
downloader.start(blocking=True)
await gather(
*[

View file

@ -27,7 +27,7 @@ from pyrogram.types import (
from misskaty import app
from misskaty.core import pyro_cooldown
from misskaty.core.decorator import capture_err, new_task
from misskaty.helper import fetch, use_chat_lang, isValidURL
from misskaty.helper import fetch, isValidURL, use_chat_lang
from misskaty.vars import COMMAND_HANDLER, LOG_CHANNEL, SUDO
LOGGER = getLogger("MissKaty")
@ -94,7 +94,11 @@ async def ytsearch(_, ctx: Message, strings):
async def ytdownv2(self, ctx: Message, strings):
if not ctx.from_user:
return await ctx.reply_msg(strings("no_channel"))
url = ctx.command[1] if ctx.command and len(ctx.command) > 1 else ctx.text or ctx.caption
url = (
ctx.command[1]
if ctx.command and len(ctx.command) > 1
else ctx.text or ctx.caption
)
if not isValidURL(url):
return await ctx.reply_msg(strings("invalid_link"))
async with iYTDL(log_group_id=0, cache_path="cache", silent=True) as ytdl:

View file

@ -15,7 +15,9 @@ basicConfig(
format="[%(levelname)s] - [%(asctime)s - %(name)s - %(message)s] -> [%(module)s:%(lineno)d]",
datefmt="%d-%b-%y %H:%M:%S",
handlers=[
handlers.RotatingFileHandler("MissKatyLogs.txt", mode="w+", maxBytes=5242880, backupCount=1),
handlers.RotatingFileHandler(
"MissKatyLogs.txt", mode="w+", maxBytes=5242880, backupCount=1
),
StreamHandler(),
],
)

View file

@ -128,7 +128,11 @@ def extract_user(message: Message) -> Union[int, str]:
user_first_name = message.reply_to_message.from_user.first_name
elif len(message.command) > 1:
if message.entities and len(message.entities) > 1 and message.entities[1].type.value == "text_mention":
if (
message.entities
and len(message.entities) > 1
and message.entities[1].type.value == "text_mention"
):
required_entity = message.entities[1]
user_id = required_entity.user.id
user_first_name = required_entity.user.first_name