Merge pull request #115 from yasirarism/develop

Fix IMDB Typo and change motor to async pymongo
This commit is contained in:
yasirarism 2023-06-27 03:52:00 +00:00 committed by GitHub
commit 469ed1ee12
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 76 additions and 105 deletions

View file

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

15
.pep8speaks.toml Normal file
View file

@ -0,0 +1,15 @@
# File : .pep8speaks.yml
scanner:
linter: flake8
flake8:
max-line-length: 100
ignore:
- W503 # line break before binary operator
message:
opened:
header: "@{name}, Thanks for opening this PR."
updated:
header: "@{name}, Thanks for updating this PR."

View file

@ -4,9 +4,8 @@
* @projectName MissKatyPyro * @projectName MissKatyPyro
* Copyright @YasirPedia All rights reserved * Copyright @YasirPedia All rights reserved
""" """
from motor.motor_asyncio import AsyncIOMotorClient as MongoClient from async_pymongo import AsyncClient
from misskaty.vars import DATABASE_URI, DATABASE_NAME
from misskaty.vars import DATABASE_URI mongo = AsyncClient(DATABASE_URI)
dbname = mongo[DATABASE_NAME]
mongo = MongoClient(DATABASE_URI)
dbname = mongo.MissKatyDB

View file

@ -10,8 +10,8 @@
from database import dbname from database import dbname
usersdb = dbname.users usersdb = dbname["users"]
cleandb = dbname.cleanmode cleandb = dbname["cleanmode"]
cleanmode = {} cleanmode = {}

View file

@ -2,7 +2,7 @@ from typing import Dict, List, Union
from database import dbname from database import dbname
filtersdb = dbname.filters filtersdb = dbname["filters"]
async def _get_filters(chat_id: int) -> Dict[str, int]: async def _get_filters(chat_id: int) -> Dict[str, int]:

View file

@ -1,6 +1,6 @@
from database import dbname from database import dbname
gbansdb = dbname.gban gbansdb = dbname["gban"]
async def is_gbanned_user(user_id: int) -> bool: async def is_gbanned_user(user_id: int) -> bool:

View file

@ -1,6 +1,6 @@
from database import dbname from database import dbname
imbd_db = dbname.imdb imbd_db = dbname["imdb"]
async def is_imdbset(user_id: int) -> bool: async def is_imdbset(user_id: int) -> bool:

View file

@ -3,7 +3,7 @@ from typing import Dict, Union
from database import dbname from database import dbname
from misskaty.helper.functions import int_to_alpha from misskaty.helper.functions import int_to_alpha
karmadb = dbname.karma karmadb = dbname["karma"]
async def get_karmas_count() -> dict: async def get_karmas_count() -> dict:

View file

@ -4,7 +4,7 @@ from pyrogram.enums import ChatType
from database import dbname from database import dbname
localesdb = dbname.locale # DB for localization localesdb = dbname["locale"] # DB for localization
group_types: Iterable[ChatType] = (ChatType.GROUP, ChatType.SUPERGROUP) group_types: Iterable[ChatType] = (ChatType.GROUP, ChatType.SUPERGROUP)

View file

@ -2,7 +2,7 @@ from typing import Dict, List, Union
from database import dbname from database import dbname
notesdb = dbname.notes notesdb = dbname["notes"]
async def _get_notes(chat_id: int) -> Dict[str, int]: async def _get_notes(chat_id: int) -> Dict[str, int]:

View file

@ -1,6 +1,6 @@
from database import dbname from database import dbname
matadb = dbname.sangmata matadb = dbname["sangmata"]
# Get Data User # Get Data User

View file

@ -1,14 +1,13 @@
import motor.motor_asyncio from async_pymongo import AsyncClient
from misskaty.vars import DATABASE_NAME, DATABASE_URI from misskaty.vars import DATABASE_NAME, DATABASE_URI
class Database: class UsersData:
def __init__(self, uri, database_name): def __init__(self, uri, database_name):
self._client = motor.motor_asyncio.AsyncIOMotorClient(uri) self._client = AsyncClient(uri)
self.db = self._client[database_name] self.db = self._client[database_name]
self.col = self.db.users self.col = self.db["users"]
self.grp = self.db.groups self.grp = self.db["groups"]
@staticmethod @staticmethod
def new_user(id, name): def new_user(id, name):
@ -109,4 +108,4 @@ class Database:
return (await self.db.command("dbstats"))["dataSize"] return (await self.db.command("dbstats"))["dataSize"]
db = Database(DATABASE_URI, DATABASE_NAME) db = UsersData(DATABASE_URI, DATABASE_NAME)

View file

@ -2,7 +2,7 @@ from typing import Dict, Union
from database import dbname from database import dbname
warnsdb = dbname.warn warnsdb = dbname["warn"]
async def get_warns_count() -> dict: async def get_warns_count() -> dict:

View file

@ -8,7 +8,6 @@ from logging import ERROR, INFO, StreamHandler, basicConfig, getLogger, handlers
from apscheduler.jobstores.mongodb import MongoDBJobStore from apscheduler.jobstores.mongodb import MongoDBJobStore
from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.schedulers.asyncio import AsyncIOScheduler
from async_pymongo import AsyncClient from async_pymongo import AsyncClient
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo import MongoClient from pymongo import MongoClient
from pyrogram import Client from pyrogram import Client
@ -41,7 +40,7 @@ MOD_NOLOAD = ["subscene_dl"]
HELPABLE = {} HELPABLE = {}
cleanmode = {} cleanmode = {}
botStartTime = time.time() botStartTime = time.time()
misskaty_version = "v2.9.1 - Stable" misskaty_version = "v2.9.2 - Stable"
# Pyrogram Bot Client # Pyrogram Bot Client
app = Client( app = Client(

View file

@ -48,7 +48,7 @@ async def start_bot():
LOGGER.info("+===============+===============+===============+===============+") LOGGER.info("+===============+===============+===============+===============+")
LOGGER.info(bot_modules) LOGGER.info(bot_modules)
LOGGER.info("+===============+===============+===============+===============+") LOGGER.info("+===============+===============+===============+===============+")
LOGGER.info(f"[INFO]: BOT STARTED AS @{BOT_USERNAME}!") LOGGER.info("[INFO]: BOT STARTED AS @%s!", BOT_USERNAME)
try: try:
LOGGER.info("[INFO]: SENDING ONLINE STATUS") LOGGER.info("[INFO]: SENDING ONLINE STATUS")

View file

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

View file

@ -5,6 +5,8 @@ from string import ascii_lowercase
from pyrogram import enums from pyrogram import enums
from misskaty import app
def get_urls_from_text(text: str) -> bool: def get_urls_from_text(text: str) -> bool:
regex = r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-] regex = r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]
@ -47,7 +49,6 @@ async def extract_userid(message, text: str):
return int(text) return int(text)
entities = message.entities entities = message.entities
app = message._client
if len(entities) < 2: if len(entities) < 2:
return (await app.get_users(text)).id return (await app.get_users(text)).id
entity = entities[1] entity = entities[1]

View file

@ -140,7 +140,6 @@ async def kusonimeBypass(url: str, slug=None):
err = traceback.format_exc() err = traceback.format_exc()
LOGGER.error(err) LOGGER.error(err)
result |= {"error": True, "error_message": err} result |= {"error": True, "error_message": err}
finally:
await http.delete(_url) await http.delete(_url)
return result return result

View file

@ -5,6 +5,7 @@ from pyrogram.types import InlineKeyboardButton
from misskaty import MOD_LOAD, MOD_NOLOAD from misskaty import MOD_LOAD, MOD_NOLOAD
# skipcq: PYL-W1641
class EqInlineKeyboardButton(InlineKeyboardButton): class EqInlineKeyboardButton(InlineKeyboardButton):
def __eq__(self, other): def __eq__(self, other):
return self.text == other.text return self.text == other.text

View file

@ -854,7 +854,7 @@ async def set_chat_photo(self: Client, ctx: Message):
if file.file_size > 5000000: if file.file_size > 5000000:
return await ctx.reply("File size too large.") return await ctx.reply("File size too large.")
file = await reply.download() photo = await reply.download()
try: try:
await ctx.chat.set_photo(photo=photo) await ctx.chat.set_photo(photo=photo)
await ctx.reply_text("Successfully Changed Group Photo") await ctx.reply_text("Successfully Changed Group Photo")

View file

@ -1,5 +1,5 @@
from pyrogram import Client, filters from pyrogram import Client, filters
from pyrogram.errors import ChannelPrivate from pyrogram.errors import ChannelPrivate, PeerIdInvalid
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from database.users_chats_db import db from database.users_chats_db import db

View file

@ -111,7 +111,7 @@ async def download(client, message):
try: try:
downloader.start(blocking=False) downloader.start(blocking=False)
except Exception as err: except Exception as err:
return await ctx.edit(str(err)) return await message.edit_msg(str(err))
c_time = time.time() c_time = time.time()
while not downloader.isFinished(): while not downloader.isFinished():
total_length = downloader.filesize or None total_length = downloader.filesize or None

View file

@ -133,25 +133,6 @@ async def member_has_joined(c: app, member: ChatMemberUpdated, strings):
except Exception as e: except Exception as e:
LOGGER.info(e) LOGGER.info(e)
userspammer = "" userspammer = ""
# Spamwatch Detection
try:
headers = {
"Authorization": "Bearer XvfzE4AUNXkzCy0DnIVpFDlxZi79lt6EnwKgBj8Quuzms0OSdHvf1k6zSeyzZ_lz"
}
apispamwatch = (
await http.get(
f"https://api.spamwat.ch/banlist/{user.id}", headers=headers
)
).json()
if not apispamwatch.get("error"):
await app.ban_chat_member(
member.chat.id, user.id, datetime.now() + timedelta(seconds=30)
)
userspammer += strings("spamwatch_msg").format(
umention=user.mention, uid=user.id, reas=apispamwatch.get("reason")
)
except Exception as err:
LOGGER.error(f"ERROR in Spamwatch Detection. {err}")
# Combot API Detection # Combot API Detection
try: try:
apicombot = ( apicombot = (
@ -202,25 +183,6 @@ async def greet_group(bot, message, strings):
), ),
) )
userspammer = "" userspammer = ""
# Spamwatch Detection
try:
headers = {
"Authorization": "Bearer XvfzE4AUNXkzCy0DnIVpFDlxZi79lt6EnwKgBj8Quuzms0OSdHvf1k6zSeyzZ_lz"
}
apispamwatch = (
await http.get(
f"https://api.spamwat.ch/banlist/{u.id}", headers=headers
)
).json()
if not apispamwatch.get("error"):
await app.ban_chat_member(
message.chat.id, u.id, datetime.now() + timedelta(seconds=30)
)
userspammer += strings("spamwatch_msg").format(
umention=u.mention, uid=u.id, reas=apispamwatch.get("reason")
)
except Exception as err:
LOGGER.error(f"ERROR in Spamwatch Detection. {err}")
# Combot API Detection # Combot API Detection
try: try:
apicombot = ( apicombot = (

View file

@ -649,7 +649,7 @@ async def imdb_en_callback(self: Client, query: CallbackQuery):
for i in r_json["creator"] for i in r_json["creator"]
if i["@type"] == "Person" if i["@type"] == "Person"
) )
res_str += f"<b>Writer:</b> {creator[-2]}\n" res_str += f"<b>Writer:</b> {creator[:-2]}\n"
if r_json.get("actor"): if r_json.get("actor"):
actors = actors = "".join( actors = actors = "".join(
f"<a href='{i['url']}'>{i['name']}</a>, " for i in r_json["actor"] f"<a href='{i['url']}'>{i['name']}</a>, " for i in r_json["actor"]

View file

@ -11,24 +11,20 @@ from sys import version as pyver
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from deep_translator import GoogleTranslator from deep_translator import GoogleTranslator
from motor import version as mongover
from pykeyboard import InlineButton, InlineKeyboard from pykeyboard import InlineButton, InlineKeyboard
from pyrogram import __version__ as pyrover from pyrogram import __version__ as pyrover
from pyrogram import enums, filters from pyrogram import enums, filters
from pyrogram.errors import MessageIdInvalid, MessageNotModified from pyrogram.errors import MessageIdInvalid, MessageNotModified
from pyrogram.types import ( from pyrogram.types import (InlineKeyboardButton, InlineKeyboardMarkup,
InlineKeyboardButton, InlineQuery, InlineQueryResultArticle,
InlineKeyboardMarkup, InlineQueryResultPhoto, InputTextMessageContent)
InlineQuery,
InlineQueryResultArticle,
InlineQueryResultPhoto,
InputTextMessageContent,
)
from misskaty import BOT_USERNAME, app, user from misskaty import BOT_USERNAME, app, user
from misskaty.core.decorator.ratelimiter import ratelimiter from misskaty.core.decorator.ratelimiter import ratelimiter
from misskaty.helper import GENRES_EMOJI, http, post_to_telegraph, search_jw from misskaty.helper import GENRES_EMOJI, http, post_to_telegraph, search_jw
from misskaty.plugins.dev import shell_exec
from misskaty.plugins.misc_tools import get_content from misskaty.plugins.misc_tools import get_content
from misskaty.vars import USER_SESSION
from utils import demoji from utils import demoji
__MODULE__ = "InlineFeature" __MODULE__ = "InlineFeature"
@ -50,6 +46,7 @@ LOGGER = getLogger()
@app.on_inline_query() @app.on_inline_query()
async def inline_menu(_, inline_query: InlineQuery): async def inline_menu(_, inline_query: InlineQuery):
if inline_query.query.strip().lower().strip() == "": if inline_query.query.strip().lower().strip() == "":
aspymon_ver = (await shell_exec("pip freeze | grep async-pymongo"))[0]
buttons = InlineKeyboard(row_width=2) buttons = InlineKeyboard(row_width=2)
buttons.add( buttons.add(
*[ *[
@ -59,8 +56,8 @@ async def inline_menu(_, inline_query: InlineQuery):
) )
btn = InlineKeyboard(row_width=2) btn = InlineKeyboard(row_width=2)
bot_state = "Alive" if await app.get_me() else "Dead" bot_state = "Alive" if USER_SESSION and await app.get_me() else "Dead"
ubot_state = "Alive" if await user.get_me() else "Dead" ubot_state = "Alive" if USER_SESSION and await user.get_me() else "Dead"
btn.add( btn.add(
InlineKeyboardButton("Stats", callback_data="stats_callback"), InlineKeyboardButton("Stats", callback_data="stats_callback"),
InlineKeyboardButton("Go Inline!", switch_inline_query_current_chat=""), InlineKeyboardButton("Go Inline!", switch_inline_query_current_chat=""),
@ -68,14 +65,16 @@ async def inline_menu(_, inline_query: InlineQuery):
msg = f""" msg = f"""
**[MissKaty](https://github.com/yasirarism):** **[MissKaty](https://github.com/yasirarism):**
**MainBot:** `{bot_state}` **MainBot Stats:** `{bot_state}`
**UserBot:** `{ubot_state}` **UserBot Stats:** `{ubot_state}`
**Python:** `{pyver.split()[0]}` **Python:** `{pyver.split()[0]}`
**Pyrogram:** `{pyrover}` **Pyrogram:** `{pyrover}`
**MongoDB:** `{mongover}` **MongoDB:** `{aspymon_ver}`
**Platform:** `{platform}` **Platform:** `{platform}`
**Profiles:** {(await app.get_me()).username} | {(await user.get_me()).first_name} **Bot:** {(await app.get_me()).first_name}
""" """
if USER_SESSION:
msg += f"**UserBot:** {(await user.get_me()).first_name}"
answerss = [ answerss = [
InlineQueryResultArticle( InlineQueryResultArticle(
title="Inline Commands", title="Inline Commands",
@ -166,6 +165,7 @@ async def inline_menu(_, inline_query: InlineQuery):
reply_markup=buttons, reply_markup=buttons,
) )
) )
is_img = False
for types in parsetypes: for types in parsetypes:
if kueri.lower() in types.lower(): if kueri.lower() in types.lower():
link = parsetypes[types]["href"] link = parsetypes[types]["href"]
@ -191,7 +191,7 @@ async def inline_menu(_, inline_query: InlineQuery):
body_text = f""" body_text = f"""
<pre>{msg}</pre> <pre>{msg}</pre>
""" """
msg = await post_to_telegraph(False, method, body_text) msg = await post_to_telegraph(is_img, method, body_text)
datajson.append( datajson.append(
InlineQueryResultArticle( InlineQueryResultArticle(
title=types, title=types,

View file

@ -13,12 +13,8 @@ from time import time
from urllib.parse import unquote from urllib.parse import unquote
from pyrogram import Client, filters from pyrogram import Client, filters
from pyrogram.types import ( from pyrogram.types import (CallbackQuery, InlineKeyboardButton,
CallbackQuery, InlineKeyboardMarkup, Message)
InlineKeyboardButton,
InlineKeyboardMarkup,
Message,
)
from misskaty import app from misskaty import app
from misskaty.core.decorator.errors import capture_err from misskaty.core.decorator.errors import capture_err
@ -131,7 +127,7 @@ async def convertsrt(self: Client, ctx: Message, strings):
filename = dl.split("/", 3)[3] filename = dl.split("/", 3)[3]
LOGGER.info(f"ConvertSub: {filename} by {ctx.from_user.first_name if ctx.from_user else ctx.sender_chat.title} [{ctx.from_user.id if ctx.from_user else ctx.sender_chat.id}]") LOGGER.info(f"ConvertSub: {filename} by {ctx.from_user.first_name if ctx.from_user else ctx.sender_chat.title} [{ctx.from_user.id if ctx.from_user else ctx.sender_chat.id}]")
suffix = "srt" if ctx.command[0] == "converttosrt" else "ass" suffix = "srt" if ctx.command[0] == "converttosrt" else "ass"
(await shell_exec(f"ffmpeg -i '{dl}' 'downloads/{filename}.{suffix}'"))[0] (await shell_exec(f"ffmpeg -i '{dl}' 'downloads/{filename}.{suffix}'"))[0] # skipcq: PYL-W0106
c_time = time() c_time = time()
await ctx.reply_document( await ctx.reply_document(
f"downloads/{filename}.{suffix}", f"downloads/{filename}.{suffix}",
@ -156,7 +152,7 @@ async def stream_extract(self: Client, update: CallbackQuery, strings):
usr = update.message.reply_to_message usr = update.message.reply_to_message
if update.from_user.id != usr.from_user.id: if update.from_user.id != usr.from_user.id:
return await update.answer(strings("unauth_cb"), True) return await update.answer(strings("unauth_cb"), True)
_, lang, map, codec = cb_data.split("#") _, lang, map_code, codec = cb_data.split("#")
try: try:
link = update.message.reply_to_message.command[1] link = update.message.reply_to_message.command[1]
except: except:
@ -174,7 +170,7 @@ async def stream_extract(self: Client, update: CallbackQuery, strings):
namafile = get_subname(lang, link, ext) namafile = get_subname(lang, link, ext)
try: try:
LOGGER.info(f"ExtractSub: {namafile} by {update.from_user.first_name} [{update.from_user.id}]") LOGGER.info(f"ExtractSub: {namafile} by {update.from_user.first_name} [{update.from_user.id}]")
(await shell_exec(f"ffmpeg -i {link} -map {map} '{namafile}'"))[0] (await shell_exec(f"ffmpeg -i {link} -map {map_code} '{namafile}'"))[0]
timelog = time() - start_time timelog = time() - start_time
c_time = time() c_time = time()
await update.message.reply_document( await update.message.reply_document(

View file

@ -44,7 +44,7 @@ headers = {
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)
SCRAP_DICT = TTLCache(maxsize=1000, ttl=1800) SCRAP_DICT = TTLCache(maxsize=1000, ttl=1800)
data_kuso = TTLCache(maxsize=1000, ttl=1800) data_kuso = TTLCache(maxsize=1000, ttl=1800)
webdb = dbname.web webdb = dbname["web"]
web = { web = {
"yasirapi": "https://yasirapi.eu.org", "yasirapi": "https://yasirapi.eu.org",

View file

@ -4,7 +4,6 @@ tgcrypto
async_pymongo async_pymongo
pymongo pymongo
python-dotenv python-dotenv
motor[srv]>=3.1.2
requests requests
bs4 bs4
aiohttp aiohttp