# File: C:\Users\Shakeel\Desktop\PROFESSOR\app.json { "name": "PROFESSOR-BOT", "description": "The Telegram Autofilter Bot", "logo": "https://graph.org/file/b7e8484f6395a180b6380.jpg", "keywords": ["Telegram", "auto-filter", "MrMKN"], "repository": "https://github.com/MrMKN/PROFESSOR-BOT", "env": { "WEBHOOK": { "description": "True/False if your server is web support required? the value is True else False", "value": "True", "required": true }, "BOT_TOKEN": { "description": "Your bot token.", "required": true }, "API_ID": { "description": "Get this value from https://my.telegram.org", "required": true }, "API_HASH": { "description": "Get this value from https://my.telegram.org", "required": true }, "CHANNELS": { "description": "Username or ID of channel or group. Separate multiple IDs by space.", "required": false }, "ADMINS": { "description": "Username or ID of Admin. Separate multiple Admins by space.", "required": true }, "SHORT_API": { "description": "Api Key Of shortner You Use.", "required": false }, "SHORT_URL": { "description": "Url of shortner site you use.", "required": false }, "PICS": { "description": "Add some telegraph link of pictures .", "required": false }, "LOG_CHANNEL": { "description": "Bot Logs,Give a channel id with -100xxxxxxx", "required": true }, "AUTH_CHANNEL": { "description": "ID of channel.Make sure bot is admin in this channel. Without subscribing this channel users cannot use bot.", "required": false }, "MAX_RIST_BTNS": { "description": "Maximum number of serch result buttons count ⚠️below 10 only ", "value": "10", "required": false }, "CUSTOM_FILE_CAPTION": { "description": "A custom file caption for your files. formatable with , file_name, file_caption, file_size, Read Readme.md for better understanding.", "value": "Hey {mention}👋\n\n{file_name}\n\n🔘 size - {file_size}\n\n╭─── • ❰ @MR_LINK_Z ❱ • ────➤\n┣ ▫️ @MRxSERIES\n┣ ▫️ @MalluMovie_Official\n╰─────── • ◆ • ───────➤", "required": false }, "DATABASE_URL": { "description": "mongoDB URI.", "required": true }, "DATABASE_NAME": { "description": "Name of the database in mongoDB.", "value": "Cluster0", "required": false }, "COLLECTION_NAME": { "description": "Name of the collections. Defaults to Telegram_files. If you are using the same database, then use different collection name for each bot", "value": "Telegram_files", "required": false }, "SUPPORT_CHAT": { "description": "Updated Channel Username Without @ Not Chanel ID", "value": "MKN_BOTZ_DISCUSSION_GROUP", "required": false }, "IMDB": { "description": "Imdb, the view of information when making True/False", "value": "True", "required": false }, "PM_IMDB": { "description": "pm Imdb, the view of information when making True/False", "value": "True", "required": false }, "IMDB_TEMPLATE": { "description": "Custom IMDB Template", "value": "Qᴜᴇʀʏ: {query}\n\n🏷 Tɪᴛʟᴇ: {title}\n🎭 Gᴇɴʀᴇꜱ: {genres}\n📆 Yᴇᴀʀ: {year}\n🌟 Rᴀᴛɪɴɢ: {rating}/10", "required": false }, "IMDB_DELET_TIME": { "description": "bot risult aouto delet time in second do to avoid group copyright issue. default is 300 ", "value": "300", "required": false }, "SINGLE_BUTTON": { "description": "choose b/w single or double buttons https://github.com/Aadhi000/Ajax/issues/22", "value": "True", "required": false }, "START_MESSAGE": { "description": "bot start message text [ {user} = bot startd user name {bot} = your bot name", "value": "✨ Hᴇʟʟᴏ {user}.\n\nMʏ Nᴀᴍᴇ Is {bot}.\n\nI Cᴀɴ Pʀᴏᴠɪᴅᴇ Mᴏᴠɪᴇ Fᴏʀ Yᴏᴜ Jᴜsᴛ Aᴅᴅ Mᴇ Iɴ Yᴏᴜʀ Gʀᴏᴜᴘ Oʀ Jᴏɪɴ Oᴜʀ Gʀᴏᴜᴘ", "required": false }, "FORCE_SUB_TEXT": { "description": "custom force sub text (use ** = bold / use ``= mono)", "value": "Sᴏʀʀʏ Bʀᴏ Yᴏᴜʀ Nᴏᴛ Jᴏɪɴᴇᴅ Mʏ Cʜᴀɴɴᴇʟ Sᴏ Pʟᴇᴀsᴇ Cʟɪᴄᴋ Jᴏɪɴ Bᴜᴛᴛᴏɴ Tᴏ Jᴏɪɴ Mʏ Cʜᴀɴɴᴇʟ Aɴᴅ Tʀʏ Aɢᴀɪɴ", "required": false }, "AUTH_GROUPS": { "description": "Group Id. Only work a specific group/ your bot is public use? please just Skip this", "value": "", "required": false }, "WELCOM_PIC": { "description": "Welcome message pic (telegraph link)", "value": "", "required": false }, "WELCOM_TEXT": { "description": "your group welcome text keyword({user} = joined use & {chat} = your chat name", "value": "Hᴇʏ {user} 💞\nWᴇʟᴄᴏᴍᴇ ᴛᴏ {chat}.\n\nꜱʜᴀʀᴇ & ꜱᴜᴩᴩᴏʀᴛ, ʀᴇqᴜᴇꜱᴛ ʏᴏᴜ ᴡᴀɴᴛᴇᴅ ᴍᴏᴠɪᴇꜱ", "required": false }, "BUTTON_LOCK_TEXT": { "description": "button lock text [User = {query}]", "value": "Hᴇʏ {query}\nTʜɪꜱ Iꜱ Nᴏᴛ Fᴏʀ Yᴏᴜ. Sᴇᴀʀᴄʜ Yᴏᴜʀ Sᴇʟꜰ", "required": false }, "PMFILTER": { "description": "PM AutoFilter. set True to on / False to off", "value": "True", "required": false }, "G_FILTER": { "description": "GlobalFilter set True to on / False to off", "value": "True", "required": false }, "BUTTON_LOCK": { "description": "Button alert set True to on / False to off", "value": "True", "required": false }, "RemoveBG_API": { "description": "background remover website api key. get from https://www.remove.bg/b/background-removal-api", "required": false }, "P_TTI_SHOW_OFF": { "description": "Customize Result Buttons to Callback or Url by (True = url / False = callback)", "value": "True", "required": false } }, "buildpacks": [ {"url": "heroku/python"} ] } ================================================================================ # File: C:\Users\Shakeel\Desktop\PROFESSOR\bot.py import os, math, logging, datetime, pytz, logging.config from aiohttp import web from pyrogram import Client, types from database.users_chats_db import db from database.ia_filterdb import Media from typing import Union, Optional, AsyncGenerator from utils import temp, __repo__, __license__, __copyright__, __version__ from info import API_ID, API_HASH, BOT_TOKEN, LOG_CHANNEL, UPTIME, WEB_SUPPORT, LOG_MSG # Get logging configurations logging.config.fileConfig("logging.conf") logging.getLogger(__name__).setLevel(logging.INFO) logging.getLogger("cinemagoer").setLevel(logging.ERROR) class Bot(Client): def __init__(self): super().__init__( name="Professor-Bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN, plugins=dict(root="plugins") ) async def start(self): b_users, b_chats = await db.get_banned() temp.BANNED_USERS = b_users temp.BANNED_CHATS = b_chats await super().start() await Media.ensure_indexes() me = await self.get_me() temp.U_NAME = me.username temp.B_NAME = me.first_name self.id = me.id self.name = me.first_name self.mention = me.mention self.username = me.username self.log_channel = LOG_CHANNEL self.uptime = UPTIME curr = datetime.datetime.now(pytz.timezone("Asia/Kolkata")) date = curr.strftime('%d %B, %Y') tame = curr.strftime('%I:%M:%S %p') logging.info(LOG_MSG.format(me.first_name, date, tame, __repo__, __version__, __license__, __copyright__)) try: await self.send_message(LOG_CHANNEL, text=LOG_MSG.format(me.first_name, date, tame, __repo__, __version__, __license__, __copyright__), disable_web_page_preview=True) except Exception as e: logging.warning(f"Bot Isn't Able To Send Message To LOG_CHANNEL \n{e}") if bool(WEB_SUPPORT) is True: app = web.AppRunner(web.Application(client_max_size=30000000)) await app.setup() await web.TCPSite(app, "0.0.0.0", 8080).start() logging.info("Web Response Is Running......🕸️") async def stop(self, *args): await super().stop() logging.info(f"Bot Is Restarting ⟳...") async def iter_messages(self, chat_id: Union[int, str], limit: int, offset: int = 0) -> Optional[AsyncGenerator["types.Message", None]]: current = offset while True: new_diff = min(200, limit - current) if new_diff <= 0: return messages = await self.get_messages(chat_id, list(range(current, current+new_diff+1))) for message in messages: yield message current += 1 Bot().run() ================================================================================ # File: C:\Users\Shakeel\Desktop\PROFESSOR\info.py import re, time from os import environ from Script import script id_pattern = re.compile(r'^.\d+$') def is_enabled(value, default): if value.strip().lower() in ["on", "true", "yes", "1", "enable", "y"]: return True elif value.strip().lower() in ["off", "false", "no", "0", "disable", "n"]: return False else: return default # PyroClient Setup API_ID = int(environ['API_ID']) API_HASH = environ['API_HASH'] BOT_TOKEN = environ['BOT_TOKEN'] # Bot settings WEB_SUPPORT = bool(environ.get("WEBHOOK", 'True')) # for web support on/off PICS = (environ.get('PICS' ,'https://graph.org/file/01ddfcb1e8203879a63d7.jpg https://graph.org/file/d69995d9846fd4ad632b8.jpg https://graph.org/file/a125497b6b85a1d774394.jpg https://graph.org/file/43d26c54d37f4afb830f7.jpg https://graph.org/file/60c1adffc7cc2015f771c.jpg https://graph.org/file/d7b520240b00b7f083a24.jpg https://graph.org/file/0f336b0402db3f2a20037.jpg https://graph.org/file/39cc4e15cad4519d8e932.jpg https://graph.org/file/d59a1108b1ed1c6c6c144.jpg https://te.legra.ph/file/3a4a79f8d5955e64cbb8e.jpg https://graph.org/file/d69995d9846fd4ad632b8.jpg')).split() UPTIME = time.time() # Admins, Channels & Users CACHE_TIME = int(environ.get('CACHE_TIME', 300)) ADMINS = [int(admin) if id_pattern.search(admin) else admin for admin in environ.get('ADMINS', '').split()] CHANNELS = [int(ch) if id_pattern.search(ch) else ch for ch in environ.get('CHANNELS', '0').split()] auth_users = [int(user) if id_pattern.search(user) else user for user in environ.get('AUTH_USERS', '').split()] AUTH_USERS = (auth_users + ADMINS) if auth_users else [] auth_channel = environ.get('AUTH_CHANNEL') auth_grp = environ.get('AUTH_GROUP') AUTH_CHANNEL = int(auth_channel) if auth_channel and id_pattern.search(auth_channel) else None AUTH_GROUPS = [int(ch) for ch in auth_grp.split()] if auth_grp else None # MongoDB information DATABASE_URL = environ.get('DATABASE_URL', "") DATABASE_NAME = environ.get('DATABASE_NAME', "Cluster0") FILE_DB_URL = environ.get("FILE_DB_URL", DATABASE_URL) FILE_DB_NAME = environ.get("FILE_DB_NAME", DATABASE_NAME) COLLECTION_NAME = environ.get('COLLECTION_NAME', 'Telegram_files') # Filters Configuration MAX_RIST_BTNS = int(environ.get('MAX_RIST_BTNS', "10")) START_MESSAGE = environ.get('START_MESSAGE', script.START_TXT) BUTTON_LOCK_TEXT = environ.get("BUTTON_LOCK_TEXT", script.BUTTON_LOCK_TEXT) FORCE_SUB_TEXT = environ.get('FORCE_SUB_TEXT', script.FORCE_SUB_TEXT) WELCOM_PIC = environ.get("WELCOM_PIC", "") WELCOM_TEXT = environ.get("WELCOM_TEXT", script.WELCOM_TEXT) PMFILTER = is_enabled(environ.get('PMFILTER', "True"), True) G_FILTER = is_enabled(environ.get("G_FILTER", "True"), True) BUTTON_LOCK = is_enabled(environ.get("BUTTON_LOCK", "True"), True) RemoveBG_API = environ.get("RemoveBG_API", "") # url shortner SHORT_URL = environ.get("SHORT_URL") SHORT_API = environ.get("SHORT_API") # Others IMDB_DELET_TIME = int(environ.get('IMDB_DELET_TIME', "300")) LOG_CHANNEL = int(environ.get('LOG_CHANNEL', 0)) SUPPORT_CHAT = environ.get('SUPPORT_CHAT', 'MKN_BOTZ_DISCUSSION_GROUP') P_TTI_SHOW_OFF = is_enabled(environ.get('P_TTI_SHOW_OFF', "True"), True) PM_IMDB = is_enabled(environ.get('PM_IMDB', "True"), True) IMDB = is_enabled(environ.get('IMDB', "True"), True) SINGLE_BUTTON = is_enabled(environ.get('SINGLE_BUTTON', "True"), True) CUSTOM_FILE_CAPTION = environ.get("CUSTOM_FILE_CAPTION", "{file_name}") BATCH_FILE_CAPTION = environ.get("BATCH_FILE_CAPTION", None) IMDB_TEMPLATE = environ.get("IMDB_TEMPLATE", script.IMDB_TEMPLATE) LONG_IMDB_DESCRIPTION = is_enabled(environ.get("LONG_IMDB_DESCRIPTION", "False"), False) SPELL_CHECK_REPLY = is_enabled(environ.get("SPELL_CHECK_REPLY", "True"), True) MAX_LIST_ELM = environ.get("MAX_LIST_ELM", None) FILE_STORE_CHANNEL = [int(ch) for ch in (environ.get('FILE_STORE_CHANNEL', '')).split()] MELCOW_NEW_USERS = is_enabled(environ.get('MELCOW_NEW_USERS', "True"), True) PROTECT_CONTENT = is_enabled(environ.get('PROTECT_CONTENT', "False"), False) PUBLIC_FILE_STORE = is_enabled(environ.get('PUBLIC_FILE_STORE', "True"), True) LOG_MSG = "{} Iꜱ Rᴇsᴛᴀʀᴛᴇᴅ....✨\n\n🗓️ Dᴀᴛᴇ : {}\n⏰ Tɪᴍᴇ : {}\n\n🖥️ Rᴇᴏᴩ: {}\n🉐 Vᴇʀsɪᴏɴ: {}\n🧾 Lɪᴄᴇɴꜱᴇ: {}\n©️ Cᴏᴩʏʀɪɢʜᴛ: {}" ================================================================================ # File: C:\Users\Shakeel\Desktop\PROFESSOR\README.md 
{}
◉ ᴛᴏᴛᴀʟ ᴜꜱᴇʀꜱ: {}
◉ ᴛᴏᴛᴀʟ ᴄʜᴀᴛꜱ: {}
◉ ᴜꜱᴇᴅ ᴅʙ ꜱɪᴢᴇ: {}
◉ ꜰᴇᴇᴇ ᴅʙ ꜱɪᴢᴇ: {}
"""
LOG_TEXT_G = """#ɴᴇᴡ_ɢʀᴏᴜᴩ
◉ ɢʀᴏᴜᴩ: {a}
◉ ɢ-ɪᴅ: {b}
◉ ʟɪɴᴋ: @{c}
◉ ᴍᴇᴍʙᴇʀꜱ: {d}
◉ ᴀᴅᴅᴇᴅ ʙʏ: {e}
◉ ʙʏ: @{f}"""
LOG_TEXT_P = """#ɴᴇᴡ_ᴜꜱᴇʀ
◉ ᴜꜱᴇʀ-ɪᴅ: {}
◉ ᴀᴄᴄ-ɴᴀᴍᴇ: {}
◉ ᴜꜱᴇʀɴᴀᴍᴇ: @{}
◉ ʙʏ: @{}"""
GROUPMANAGER_TXT = """Hᴇʟᴩ Fᴏʀ GʀᴏᴜᴩMᴀɴᴀɢᴇʀ
Tʜɪꜱ Iꜱ Hᴇʟᴩ Oꜰ Yᴏᴜʀ Gʀᴏᴜᴩ Mᴀɴᴀɢɪɴɢ. Tʜɪꜱ Wɪʟʟ Wᴏʀᴋ Oɴʟʏ Fᴏʀ Gʀᴏᴜᴩ aᴅᴍɪɴꜱ
Cᴏᴍᴍᴀɴᴅ & Uꜱᴀɢᴇ:
• /inkick - Cᴏᴍᴍᴀɴᴅ Wɪᴛʜ Rᴇǫᴜɪʀᴇᴅ Aʀɢᴜᴍᴇɴᴛs Aɴᴅ I Wɪʟʟ Kɪᴄᴋ Mᴇᴍʙᴇʀs Fʀᴏᴍ Gʀᴏᴜᴘ.
• /instatus - Tᴏ Cʜᴇᴄᴋ Cᴜʀʀᴇɴᴛ Sᴛᴀᴛᴜs Oғ Cʜᴀᴛ Mᴇᴍʙᴇʀ Fʀᴏᴍ Gʀᴏᴜᴘ.
• /dkick - Tᴏ Kɪᴄᴋ Dᴇʟᴇᴛᴇᴅ Aᴄᴄᴏᴜɴᴛs
• /ban - To Bᴀɴ A Uꜱᴇʀ Fᴏʀᴍ Tʜᴇ Gʀᴏᴜᴩ
• /unban - Uɴʙᴀɴ Tʜᴇ Bᴀɴɴᴇᴅ Uꜱᴇʀ
• /tban - Tᴇᴍᴩᴏʀᴀʀʏ Bᴀɴ A Uꜱᴇʀ
• /mute - To Mᴜᴛᴇ A Uꜱᴇʀ
• /unmute - To Uɴᴍᴜᴛᴇ Tʜᴇ Mᴜᴛᴇᴅ Uꜱᴇʀ
• /tmute - Wɪᴛʜ Vᴀʟᴜᴇ To Mᴜᴛᴇ Uᴩ To Pᴀʀᴛɪᴄᴜʟᴀʀ Tɪᴍᴇ Eɢ: /tmute 2h
To Mᴜᴛᴇ 2Hᴏᴜʀ Vᴀʟᴜᴇꜱ Iꜱ (m/h/d)
• /pin - Tᴏ Pɪɴ A Mᴇꜱꜱᴀɢᴇ Oɴ Yᴏᴜʀ Cʜᴀᴛ
• /unpin - Tᴏ Uɴᴩɪɴ Tʜᴇ Mᴇꜱꜱᴀɢᴇ Oɴ Yᴏᴜʀ Cʜᴀᴛ
• /purge - Dᴇʟᴇᴛᴇ Aʟʟ Mᴇssᴀɢᴇs Fʀᴏᴍ Tʜᴇ Rᴇᴘʟɪᴇᴅ Tᴏ Mᴇssᴀɢᴇ, Tᴏ Tʜᴇ Cᴜʀʀᴇɴᴛ Mᴇssᴀɢᴇ """
EXTRAMOD_TXT = """Hᴇʟᴩ Fᴏʀ Exᴛʀᴀ Mᴏᴅᴜʟᴇ
Jᴜꜱᴛ Sᴇɴᴅ Aɴʏ Iᴍᴀɢᴇ Tᴏ Eᴅɪᴛ Iᴍᴀɢᴇ ✨
Cᴏᴍᴍᴀɴᴅꜱ & Uꜱᴀɢᴇ:
• /id - Gᴇᴛ Iᴅ Oғ A Sᴘᴇᴄɪғᴇᴅ Usᴇʀ
• /info - Gᴇᴛ Iɴғᴏʀᴍᴀᴛɪᴏɴ Aʙᴏᴜᴛ A Usᴇʀ
• /imdb - Gᴇᴛ Tʜᴇ Fɪʟᴍ Iɴғᴏʀᴍᴀᴛɪᴏɴ Fʀᴏᴍ Iᴍᴅʙ Sᴏᴜʀᴄᴇ
• /paste [ᴛᴇxᴛ] - Pᴀsᴛᴇ Tʜᴇ Gɪᴠᴇɴ Tᴇxᴛ Oɴ Pᴀsᴛʏ
• /tts [ᴛᴇxᴛ] - Cᴏɴᴠᴇʀᴛ Tᴇxᴛ Tᴏ Sᴘᴇᴇᴄʜ
• /telegraph - Sᴇɴᴅ Mᴇ Tʜɪs Cᴏᴍᴍᴀɴᴅ Rᴇᴘʟʏ Wɪᴛʜ Pɪᴄᴛᴜʀᴇ Oʀ Vɪᴅᴇ Uɴᴅᴇʀ (𝟻ᴍʙ)
• /json - Rᴇᴩʟʏ Wɪᴛʜ Aɴʏ Mᴇꜱꜱᴀɢᴇ Tᴏ Gᴇᴛ Mᴇꜱꜱᴀɢᴇ Iɴꜰᴏ (ᴜꜱᴇꜰᴜʟʟ ꜰᴏʀ ɢʀᴏᴜᴩ)
• /written - Rᴇᴩʟʏ Wɪᴛʜ Tᴇxᴛ Tᴏ Gᴇᴛ Fɪʟᴇ (ᴜꜱᴇꜰᴜʟʟ ꜰᴏʀ ᴄᴏᴅᴇʀꜱ)
• /carbon - Rᴇᴘʟʏ Wɪᴛʜ Tᴇxᴛ Tᴏ Gᴇᴛ Cᴀʀʙᴏɴᴀᴛᴇᴅ Iᴍᴀɢᴇ
• /font [ᴛᴇxᴛ] - Tᴏ Cʜᴀɴɢᴇ Yᴏᴜʀ Tᴇxᴛ Fᴏɴᴛs Tᴏ Fᴀɴᴄʏ Fᴏɴᴛ
• /share - Rᴇᴘʟʏ Wɪᴛʜ Tᴇxᴛ Tᴏ Gᴇᴛ Tᴇxᴛ Sʜᴀʀᴀʙʟᴇ Lɪɴᴋ
• /song [ɴᴀᴍᴇ] - Tᴏ Sᴇᴀʀᴄʜ Tʜᴇ Sᴏɴɢ Iɴ YᴏᴜTᴜʙᴇ
• /video [ʟɪɴᴋ] - Tᴏ Dᴏᴡɴʟᴏᴀᴅ Tʜᴇ YᴏᴜTᴜʙᴇ Vɪᴅᴇᴏ"""
CREATOR_REQUIRED = "❗Yᴏᴜ Hᴀᴠᴇ To Bᴇ Tʜᴇ Gʀᴏᴜᴩ Cʀᴇᴀᴛᴏʀ Tᴏ Dᴏ Tʜᴀᴛ"
INPUT_REQUIRED = "❗ **Aʀɢᴜᴍᴇɴ Rqᴜɪʀᴇᴅ**"
KICKED = "✔️ Sᴜᴄᴄᴇꜱꜱꜰᴜʟʟʏ Kɪᴄᴋᴇᴅ {} Mᴇᴍʙᴇʀꜱ Acᴄᴏʀᴅɪɴɢ To Tʜᴇ Aʀɢᴜᴍᴇɴᴛꜱ Prᴏᴠɪᴅᴇᴅ"
START_KICK = "Rᴇᴍᴏᴠɪɴɢ Iɴᴀᴄᴛɪᴠᴇ Mᴇᴍʙᴇʀs Tʜɪs Mᴀʏ Tᴀᴋᴇ A Wʜɪʟᴇ"
ADMIN_REQUIRED = "❗Iᴀᴍ Nᴏᴛ Aᴅᴍɪɴ Iɴ Tʜɪꜱ Cʜᴀᴛ Sᴏ Pʟᴇᴀꜱᴇ Aᴅᴅ Mᴇ Aɢᴀɪɴ Wɪᴛʜ Aʟʟ Pᴅᴍɪɴ Pᴇʀᴍɪꜱꜱɪᴏɴ"
DKICK = "✔️ Kɪᴄᴋᴇᴅ {} Dᴇʟᴇᴛᴇᴅ Aᴄᴄᴏᴜɴᴛꜱ Sᴜᴄᴄᴇꜱꜱꜰᴜʟʟʏ"
FETCHING_INFO = "Wᴀɪᴛ I Wɪʟʟ Tᴀᴋᴇ Tʜᴇ Aʟʟ Iɴꜰᴏ"
SERVER_STATS = """Sᴇʀᴠᴇʀ Sᴛᴀᴛꜱ:
Uᴩᴛɪᴍᴇ: {}
CPU Uꜱᴀɢᴇ: {}%
RAM Uꜱᴀɢᴇ: {}%
Tᴏᴛᴀʟ Dɪꜱᴋ: {}
Uꜱᴇᴅ Dɪꜱᴋ: {} ({}%)
Fʀᴇᴇ Dɪꜱᴋ: {}"""
BUTTON_LOCK_TEXT = "Hᴇʏ {query}\nTʜɪꜱ Iꜱ Nᴏᴛ Fᴏʀ Yᴏᴜ. Sᴇᴀʀᴄʜ Yᴏᴜʀ Sᴇʟꜰ"
FORCE_SUB_TEXT = "Sᴏʀʀʏ Bʀᴏ Yᴏᴜʀ Nᴏᴛ Jᴏɪɴᴇᴅ Mʏ Cʜᴀɴɴᴇʟ Sᴏ Pʟᴇᴀsᴇ Cʟɪᴄᴋ Jᴏɪɴ Bᴜᴛᴛᴏɴ Tᴏ Jᴏɪɴ Mʏ Cʜᴀɴɴᴇʟ Aɴᴅ Tʀʏ Aɢᴀɪɴ"
WELCOM_TEXT = """Hᴇʏ {user} 💞
Wᴇʟᴄᴏᴍᴇ ᴛᴏ {chat}.
ꜱʜᴀʀᴇ & ꜱᴜᴩᴩᴏʀᴛ, ʀᴇqᴜᴇꜱᴛ ʏᴏᴜ ᴡᴀɴᴛᴇᴅ ᴍᴏᴠɪᴇꜱ"""
IMDB_TEMPLATE = """Qᴜᴇʀʏ: {query}
🏷 Tɪᴛʟᴇ: {title}
🎭 Gᴇɴʀᴇꜱ: {genres}
📆 Yᴇᴀʀ: {year}
🌟 Rᴀᴛɪɴɢ: {rating}/10"""
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\utils.py
import logging, os, re, asyncio, requests, aiohttp
from pyrogram.errors import InputUserDeactivated, UserNotParticipant, FloodWait, UserIsBlocked, PeerIdInvalid
from pyrogram.types import Message, InlineKeyboardButton
from pyrogram import filters, enums
from info import AUTH_CHANNEL, LONG_IMDB_DESCRIPTION, MAX_LIST_ELM, SHORT_URL, SHORT_API
from imdb import Cinemagoer
from typing import Union, List
from datetime import datetime, timedelta
from database.users_chats_db import db
from bs4 import BeautifulSoup
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
BTN_URL_REGEX = re.compile(r"(\[([^\[]+?)\]\((buttonurl|buttonalert):(?:/{0,2})(.+?)(:same)?\))")
BANNED = {}
SMART_OPEN = '“'
SMART_CLOSE = '”'
START_CHAR = ('\'', '"', SMART_OPEN)
# temp db for banned
class temp(object):
BANNED_USERS = []
BANNED_CHATS = []
CURRENT = 0
CANCEL = False
MELCOW = {}
U_NAME = None
B_NAME = None
SETTINGS = {}
GP_BUTTONS = {}
PM_BUTTONS = {}
PM_SPELL = {}
GP_SPELL = {}
async def is_subscribed(bot, query):
try:
user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id)
except UserNotParticipant:
pass
except Exception as e:
print(e)
else:
if user.status != enums.ChatMemberStatus.BANNED:
return True
return False
async def get_poster(query, bulk=False, id=False, file=None):
imdb = Cinemagoer()
if not id:
query = (query.strip()).lower()
title = query
year = re.findall(r'[1-2]\d{3}$', query, re.IGNORECASE)
if year:
year = list_to_str(year[:1])
title = (query.replace(year, "")).strip()
elif file is not None:
year = re.findall(r'[1-2]\d{3}', file, re.IGNORECASE)
if year:
year = list_to_str(year[:1])
else:
year = None
try:
movieid = imdb.search_movie(title.lower(), results=10)
except:
return None
if not movieid:
return None
if year:
filtered=list(filter(lambda k: str(k.get('year')) == str(year), movieid))
if not filtered:
filtered = movieid
else:
filtered = movieid
movieid=list(filter(lambda k: k.get('kind') in ['movie', 'tv series'], filtered))
if not movieid:
movieid = filtered
if bulk:
return movieid
movieid = movieid[0].movieID
else:
movieid = query
movie = imdb.get_movie(movieid)
if movie.get("original air date"):
date = movie["original air date"]
elif movie.get("year"):
date = movie.get("year")
else:
date = "N/A"
plot = ""
if not LONG_IMDB_DESCRIPTION:
plot = movie.get('plot')
if plot and len(plot) > 0:
plot = plot[0]
else:
plot = movie.get('plot outline')
if plot and len(plot) > 800:
plot = plot[0:800] + "..."
return {
'title': movie.get('title'),
'votes': movie.get('votes'),
"aka": list_to_str(movie.get("akas")),
"seasons": movie.get("number of seasons"),
"box_office": movie.get('box office'),
'localized_title': movie.get('localized title'),
'kind': movie.get("kind"),
"imdb_id": f"tt{movie.get('imdbID')}",
"cast": list_to_str(movie.get("cast")),
"runtime": list_to_str(movie.get("runtimes")),
"countries": list_to_str(movie.get("countries")),
"certificates": list_to_str(movie.get("certificates")),
"languages": list_to_str(movie.get("languages")),
"director": list_to_str(movie.get("director")),
"writer":list_to_str(movie.get("writer")),
"producer":list_to_str(movie.get("producer")),
"composer":list_to_str(movie.get("composer")) ,
"cinematographer":list_to_str(movie.get("cinematographer")),
"music_team": list_to_str(movie.get("music department")),
"distributors": list_to_str(movie.get("distributors")),
'release_date': date,
'year': movie.get('year'),
'genres': list_to_str(movie.get("genres")),
'poster': movie.get('full-size cover url'),
'plot': plot,
'rating': str(movie.get("rating")),
'url':f'https://www.imdb.com/title/tt{movieid}'
}
def list_to_str(k):
if not k: return "N/A"
elif len(k) == 1: return str(k[0])
elif MAX_LIST_ELM:
k = k[:int(MAX_LIST_ELM)]
return ' '.join(f'{elem}, ' for elem in k)
else:
return ' '.join(f'{elem}, ' for elem in k)
__repo__ = "https://github.com/MrMKN/PROFESSOR-BOT"
__version__ = "PROFESSOR-BOT ᴠ4.5.0"
__license__ = "GNU GENERAL PUBLIC LICENSE V2"
__copyright__ = "Copyright (C) 2023-present MrMKN {cha_t['reason']}
")
await db.disable_chat(int(chat_), reason)
temp.BANNED_CHATS.append(int(chat_))
await message.reply('Cʜᴀᴛ Sᴜᴄᴄᴇꜱꜰᴜʟʟʏ Dɪꜱᴀʙʟᴇᴅ')
try:
buttons = [[InlineKeyboardButton('Sᴜᴩᴩᴏʀᴛ', url=f'https://t.me/{SUPPORT_CHAT}')]]
await bot.send_message(chat_id=chat_, text=f'Hᴇʟʟᴏ Fʀɪᴇɴᴅs, \nᴍʏ Aᴅᴍɪɴ Hᴀs Tᴏʟᴅ Mᴇ Tᴏ Lᴇᴀᴠᴇ Fʀᴏᴍ Gʀᴏᴜᴘ Sᴏ I Gᴏ! Iғ Yᴏᴜ Wᴀɴɴᴀ Aᴅᴅ Mᴇ Aɢᴀɪɴ Cᴏɴᴛᴀᴄᴛ Mʏ Sᴜᴘᴘᴏʀᴛ Gʀᴏᴜᴘ. \nRᴇᴀꜱᴏɴ : {reason}
', reply_markup=InlineKeyboardMarkup(buttons))
await bot.leave_chat(chat_)
except Exception as e:
await message.reply(f"Eʀʀᴏʀ: {e}")
@Client.on_message(filters.command('enable') & filters.user(ADMINS))
async def re_enable_chat(bot, message):
if len(message.command) == 1: return await message.reply('Gɪᴠᴇ Mᴇ A Cʜᴀᴛ Iᴅ')
chat = message.command[1]
try: chat_ = int(chat)
except: return await message.reply('Gɪᴠᴇ Mᴇ A Vᴀʟɪᴅ Cʜᴀᴛ ID')
sts = await db.get_chat(int(chat))
if not sts: return await message.reply("Cʜᴀᴛ Nᴏᴛ Fᴏᴜɴᴅ Iɴ DB")
if not sts.get('is_disabled'):
return await message.reply('Tʜɪꜱ Cʜᴀᴛ Iꜱ Nᴏᴛ Yᴇᴛ Dɪꜱᴀʙʟᴇᴅ')
await db.re_enable_chat(int(chat_))
temp.BANNED_CHATS.remove(int(chat_))
await message.reply("Cʜᴀᴛ Sᴜᴄᴄᴇꜱꜰᴜʟʟʏ Rᴇ-Eɴᴀʙʟᴇᴅ")
@Client.on_message(filters.command('stats') & filters.incoming)
async def get_ststs(bot, message):
rju = await message.reply('Pʟᴇᴀꜱᴇ Wᴀɪᴛ...')
total_users = await db.total_users_count()
totl_chats = await db.total_chat_count()
files = await Media.count_documents()
size = await db.get_db_size()
free = 536870912 - size
size = get_size(size)
free = get_size(free)
await rju.edit(script.STATUS_TXT.format(files, total_users, totl_chats, size, free))
@Client.on_message(filters.command('invite') & filters.user(ADMINS))
async def gen_invite(bot, message):
if len(message.command) == 1: return await message.reply('Gɪᴠᴇ Mᴇ A Cʜᴀᴛ Iᴅ')
chat = message.command[1]
try: chat = int(chat)
except: return await message.reply('Gɪᴠᴇ Mᴇ A Vᴀʟɪᴅ Cʜᴀᴛ ID')
try:
link = await bot.create_chat_invite_link(chat)
except ChatAdminRequired:
return await message.reply("Iɴᴠɪᴛᴇ Lɪɴᴋ Gᴇɴᴇʀᴀᴛɪᴏɴ Fᴀɪʟᴇᴅ, Iᴀᴍ Nᴏᴛ Hᴀᴠɪɴɢ Sᴜғғɪᴄɪᴇɴᴛ Rɪɢʜᴛs")
except Exception as e:
return await message.reply(f'Eʀʀᴏʀ: {e}')
await message.reply(f'Hᴇʀᴇ Iꜱ Yᴏᴜʀ Iɴᴠɪᴛᴇ Lɪɴᴋ: {link.invite_link}')
@Client.on_message(filters.command('ban_user') & filters.user(ADMINS))
async def ban_a_user(bot, message):
if len(message.command) == 1: return await message.reply('Gɪᴠᴇ Mᴇ A Uꜱᴇʀ Iᴅ / Uꜱᴇʀɴᴀᴍᴇ')
r = message.text.split(None)
if len(r) > 2:
reason = message.text.split(None, 2)[2]
chat = message.text.split(None, 2)[1]
else:
chat = message.command[1]
reason = "No reason Provided"
try: chat = int(chat)
except: pass
try: k = await bot.get_users(chat)
except PeerIdInvalid: return await message.reply("Tʜɪs Is Aɴ Iɴᴠᴀʟɪᴅ Usᴇʀ, Mᴀᴋᴇ Sᴜʀᴇ Iᴀ Hᴀᴠᴇ Mᴇᴛ Hɪᴍ Bᴇғᴏʀᴇ")
except IndexError: return await message.reply("Tʜɪs Mɪɢʜᴛ Bᴇ A Cʜᴀɴɴᴇʟ, Mᴀᴋᴇ Sᴜʀᴇ Iᴛs A Usᴇʀ.")
except Exception as e: return await message.reply(f'Eʀʀᴏʀ: {e}')
else:
jar = await db.get_ban_status(k.id)
if jar['is_banned']: return await message.reply(f"{k.mention} Iꜱ Aʟʀᴇᴅʏ Bᴀɴɴᴇᴅ\nRᴇᴀꜱᴏɴ: {jar['ban_reason']}")
await db.ban_user(k.id, reason)
temp.BANNED_USERS.append(k.id)
await message.reply(f"Sᴜᴄᴄᴇꜱꜰᴜʟʟʏ Bᴀɴɴᴇᴅ {k.mention}")
@Client.on_message(filters.command('unban_user') & filters.user(ADMINS))
async def unban_a_user(bot, message):
if len(message.command) == 1: return await message.reply('Gɪᴠᴇ Mᴇ A Uꜱᴇʀ Iᴅ / Uꜱᴇʀɴᴀᴍᴇ')
r = message.text.split(None)
if len(r) > 2:
reason = message.text.split(None, 2)[2]
chat = message.text.split(None, 2)[1]
else:
chat = message.command[1]
reason = "No reason Provided"
try: chat = int(chat)
except: pass
try: k = await bot.get_users(chat)
except PeerIdInvalid: return await message.reply("Tʜɪs Is Aɴ Iɴᴠᴀʟɪᴅ Usᴇʀ, Mᴀᴋᴇ Sᴜʀᴇ Iᴀ Hᴀᴠᴇ Mᴇᴛ Hɪᴍ Bᴇғᴏʀᴇ")
except IndexError: return await message.reply("Tʜɪs Mɪɢʜᴛ Bᴇ A Cʜᴀɴɴᴇʟ, Mᴀᴋᴇ Sᴜʀᴇ Iᴛs A Usᴇʀ.")
except Exception as e: return await message.reply(f'Eʀʀᴏʀ: {e}')
else:
jar = await db.get_ban_status(k.id)
if not jar['is_banned']: return await message.reply(f"{k.mention} Iꜱ Nᴏᴛ Yᴇᴛ Bᴀɴɴᴇᴅ")
await db.remove_ban(k.id)
temp.BANNED_USERS.remove(k.id)
await message.reply(f"Sᴜᴄᴄᴇꜱꜰᴜʟʟʏ Uɴʙᴀɴɴᴇᴅ {k.mention}")
@Client.on_message(filters.command('users') & filters.user(ADMINS))
async def list_users(bot, message):
sps = await message.reply('Gᴇᴛᴛɪɴɢ Lɪꜱᴛ Oꜰ Uꜱᴇʀꜱ')
users = await db.get_all_users()
out = "Uꜱᴇʀꜱ Sᴀᴠᴇᴅ Iɴ DB Aʀᴇ:\n\n"
async for user in users:
out += f"{user['name']}\n"
try:
await sps.edit_text(out)
except MessageTooLong:
with open('users.txt', 'w+') as outfile:
outfile.write(out)
await message.reply_document('users.txt', caption="Lɪꜱᴛ Oꜰ Uꜱᴇʀꜱ")
@Client.on_message(filters.command('chats') & filters.user(ADMINS))
async def list_chats(bot, message):
sps = await message.reply('Gᴇᴛᴛɪɴɢ Lɪꜱᴛ Oꜰ Cʜᴀᴛꜱ')
chats = await db.get_all_chats()
out = "Cʜᴀᴛꜱ Sᴀᴠᴇᴅ Iɴ DB Aʀᴇ:\n\n"
async for chat in chats:
username = chat['username']
username = "private" if not username else "@" + username
out += f"**- Tɪᴛʟᴇ:** `{chat['title']}`\n**- ID:** `{chat['id']}`\n**Uꜱᴇʀɴᴀᴍᴇ:** {username}\n"
try:
await sps.edit_text(out)
except MessageTooLong:
with open('chats.txt', 'w+') as outfile:
outfile.write(out)
await message.reply_document('chats.txt', caption="Lɪꜱᴛ Oꜰ Cʜᴀᴛꜱ")
@Client.on_message(filters.command('id'))
async def show_id(client, message):
chat_type = message.chat.type
if chat_type == enums.ChatType.PRIVATE:
user_id = message.chat.id
first = message.from_user.first_name
last = message.from_user.last_name or ""
username = message.from_user.username
dc_id = message.from_user.dc_id or ""
await message.reply_text(f"➲ ꜰɪʀꜱᴛ ɴᴀᴍᴇ: {first}\n➲ ʟᴀꜱᴛ ɴᴀᴍᴇ: {last}\n➲ ᴜꜱᴇʀɴᴀᴍᴇ: {username}\n➲ ᴛᴇʟᴇɢʀᴀᴍ ɪᴅ: {user_id}
\n➲ ᴅᴄ ɪᴅ: {dc_id}
", quote=True)
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
_id = ""
_id += f"➲ ᴄʜᴀᴛ ɪᴅ: {message.chat.id}
\n"
if message.reply_to_message:
_id += (
"➲ ᴜꜱᴇʀ ɪᴅ: "
f"{message.from_user.id if message.from_user else 'Anonymous'}
\n"
"➲ ʀᴇᴩʟɪᴇᴅ ᴜꜱᴇʀ ɪᴅ: "
f"{message.reply_to_message.from_user.id if message.reply_to_message.from_user else 'Anonymous'}
\n"
)
file_info = get_file_id(message.reply_to_message)
else:
_id += (
"➲ ᴜꜱᴇʀ ɪᴅ: "
f"{message.from_user.id if message.from_user else 'Anonymous'}
\n"
)
file_info = get_file_id(message)
if file_info:
_id += (
f"{file_info.message_type}: "
f"{file_info.file_id}
\n"
)
await message.reply_text(_id, quote=True)
@Client.on_message(filters.command(["info"]))
async def user_info(client, message):
status_message = await message.reply_text("`ᴩʟᴇᴀꜱᴇ ᴡᴀɪᴛ....`")
from_user = None
from_user_id, _ = extract_user(message)
try:
from_user = await client.get_users(from_user_id)
except Exception as error:
return await status_message.edit(str(error))
if from_user is None:
return await status_message.edit("ɴᴏ ᴠᴀʟɪᴅ ᴜsᴇʀ_ɪᴅ / ᴍᴇssᴀɢᴇ sᴘᴇᴄɪғɪᴇᴅ")
message_out_str = ""
message_out_str += f"➲ꜰɪʀꜱᴛ ɴᴀᴍᴇ: {from_user.first_name}\n"
last_name = from_user.last_name or "ɴᴏɴᴇ"
message_out_str += f"➲ʟᴀꜱᴛ ɴᴀᴍᴇ: {last_name}\n"
message_out_str += f"➲ᴛɢ-ɪᴅ: {from_user.id}
\n"
username = from_user.username or "ɴᴏɴᴇ"
dc_id = from_user.dc_id or "[ᴜꜱᴇʀ ᴅᴏꜱᴇ'ᴛ ʜᴀᴠᴇ ᴀ ᴠᴀʟɪᴅ ᴅᴩ]"
message_out_str += f"➲ᴅᴄ-ɪᴅ: {dc_id}
\n"
message_out_str += f"➲ᴜꜱᴇʀɴᴀᴍᴇ: @{username}\n"
message_out_str += f"➲ᴜꜱᴇʀ ʟɪɴᴋ: ᴄʟɪᴄᴋ ʜᴇʀᴇ\n"
if message.chat.type in ((enums.ChatType.SUPERGROUP, enums.ChatType.CHANNEL)):
try:
chat_member_p = await message.chat.get_member(from_user.id)
joined_date = (chat_member_p.joined_date or datetime.now()).strftime("%Y.%m.%d %H:%M:%S")
message_out_str += f"➲ᴊᴏɪɴᴇᴅ ᴛʜɪꜱ ᴄʜᴀᴛ ᴏɴ: {joined_date}
\n"
except UserNotParticipant: pass
chat_photo = from_user.photo
if chat_photo:
local_user_photo = await client.download_media(message=chat_photo.big_file_id)
buttons = [[InlineKeyboardButton('ᴄʟᴏꜱᴇ ✘', callback_data='close_data')]]
await message.reply_photo(
photo=local_user_photo,
quote=True,
reply_markup=InlineKeyboardMarkup(buttons),
caption=message_out_str,
parse_mode=enums.ParseMode.HTML,
disable_notification=True
)
os.remove(local_user_photo)
else:
buttons = [[InlineKeyboardButton('ᴄʟᴏꜱᴇ ✘', callback_data='close_data')]]
await message.reply_text(
text=message_out_str,
reply_markup=InlineKeyboardMarkup(buttons),
quote=True,
parse_mode=enums.ParseMode.HTML,
disable_notification=True
)
await status_message.delete()
@Client.on_message(filters.command(["imdb", 'search']))
async def imdb_search(client, message):
if ' ' in message.text:
k = await message.reply('ꜱᴇᴀʀᴄʜɪɴɢ ɪᴍᴅʙ..')
r, title = message.text.split(None, 1)
movies = await get_poster(title, bulk=True)
if not movies:
return await message.reply("ɴᴏ ʀᴇꜱᴜʟᴛ ꜰᴏᴜɴᴅ")
btn = [[InlineKeyboardButton(f"{movie.get('title')} - {movie.get('year')}", callback_data=f"imdb#{movie.movieID}")] for movie in movies ]
await k.edit('Hᴇʀᴇ Is Wʜᴀᴛ I Fᴏᴜɴᴅ Oɴ Iᴍᴅʙ', reply_markup=InlineKeyboardMarkup(btn))
else:
await message.reply('Gɪᴠᴇ Mᴇ A Mᴏᴠɪᴇ / Sᴇʀɪᴇs Nᴀᴍᴇ')
@Client.on_callback_query(filters.regex('^imdb'))
async def imdb_callback(bot: Client, quer_y: CallbackQuery):
i, movie = quer_y.data.split('#')
imdb = await get_poster(query=movie, id=True)
btn = [[InlineKeyboardButton(f"{imdb.get('title')}", url=imdb['url'])]]
message = quer_y.message.reply_to_message or quer_y.message
if imdb:
caption = IMDB_TEMPLATE.format(
query = imdb['title'],
title = imdb['title'],
votes = imdb['votes'],
aka = imdb["aka"],
seasons = imdb["seasons"],
box_office = imdb['box_office'],
localized_title = imdb['localized_title'],
kind = imdb['kind'],
imdb_id = imdb["imdb_id"],
cast = imdb["cast"],
runtime = imdb["runtime"],
countries = imdb["countries"],
certificates = imdb["certificates"],
languages = imdb["languages"],
director = imdb["director"],
writer = imdb["writer"],
producer = imdb["producer"],
composer = imdb["composer"],
cinematographer = imdb["cinematographer"],
music_team = imdb["music_team"],
distributors = imdb["distributors"],
release_date = imdb['release_date'],
year = imdb['year'],
genres = imdb['genres'],
poster = imdb['poster'],
plot = imdb['plot'],
rating = imdb['rating'],
url = imdb['url'],
**locals()
)
else:
caption = "ɴᴏ ʀᴇꜱᴜʟᴛꜱ"
if imdb.get('poster'):
try:
await quer_y.message.reply_photo(photo=imdb['poster'], caption=caption, reply_markup=InlineKeyboardMarkup(btn))
except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty):
pic = imdb.get('poster')
poster = pic.replace('.jpg', "._V1_UX360.jpg")
await quer_y.message.reply_photo(photo=poster, caption=caption, reply_markup=InlineKeyboardMarkup(btn))
except Exception as e:
logger.exception(e)
await quer_y.message.reply(caption, reply_markup=InlineKeyboardMarkup(btn), disable_web_page_preview=False)
await quer_y.message.delete()
else:
await quer_y.message.edit(caption, reply_markup=InlineKeyboardMarkup(btn), disable_web_page_preview=False)
@Client.on_message(filters.command('logs') & filters.user(ADMINS))
async def log_file(bot, msg):
try: await message.reply_document('BotLog.txt')
except Exception as e: await message.reply(str(e))
@Client.on_message(filters.command("restart") & filters.user(ADMINS))
async def restart_bot(bot, msg):
await msg.reply("Rᴇꜱᴛᴀᴛɪɴɢ........")
await asyncio.sleep(2)
await sts.delete()
os.execl(sys.executable, sys.executable, *sys.argv)
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\banned.py
from pyrogram.types import Message, InlineKeyboardButton, InlineKeyboardMarkup
from pyrogram import Client, filters
from database.users_chats_db import db
from info import SUPPORT_CHAT
from utils import temp
async def banned_users(_, client, message: Message):
if message.from_user.is_bot: return
return (message.from_user is not None or not message.sender_chat) and (message.from_user.id in temp.BANNED_USERS)
async def disabled_chat(_, client, message: Message):
return message.chat.id in temp.BANNED_CHATS
@Client.on_message(filters.private & filters.incoming & filters.create(banned_users))
async def ban_reply(bot, message):
ban = await db.get_ban_status(message.from_user.id)
await message.reply(f"Sᴏʀʀʏ Dᴜᴅᴇ, Yᴏᴜ Aʀᴇ Bᴀɴɴᴇᴅ Tᴏ Usᴇ Mᴇ. \nBᴀɴ Rᴇᴀsᴏɴ: {ban['ban_reason']}")
@Client.on_message(filters.group & filters.incoming & filters.create(disabled_chat))
async def grp_bd(bot, message):
buttons = [[InlineKeyboardButton('Sᴜᴩᴩᴏʀᴛ', url=f'https://t.me/{SUPPORT_CHAT}')]]
chat = await db.get_chat(message.chat.id)
k = await message.reply(text=f"CHAT NOT ALLOWED 🐞\n\nMʏ Aᴅᴍɪɴs Hᴀs Rᴇsᴛʀɪᴄᴛᴇᴅ Mᴇ Fʀᴏᴍ Wᴏʀᴋɪɴɢ Hᴇʀᴇ ! Iғ Yᴏᴜ Wᴀɴᴛ Tᴏ Kɴᴏᴡ Mᴏʀᴇ Aʙᴏᴜᴛ Iᴛ Cᴏɴᴛᴀᴄᴛ Sᴜᴘᴘᴏʀᴛ..\nRᴇᴀꜱᴏɴ : {chat['reason']}
.", reply_markup=InlineKeyboardMarkup(buttons))
try: await k.pin()
except: pass
await bot.leave_chat(message.chat.id)
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\broadcast.py
import datetime, time, os, asyncio,logging
from pyrogram.errors import InputUserDeactivated, UserNotParticipant, FloodWait, UserIsBlocked, PeerIdInvalid
from pyrogram.errors.exceptions.bad_request_400 import MessageTooLong, PeerIdInvalid
from pyrogram.types import Message, InlineKeyboardButton
from pyrogram import Client, filters, enums
from database.users_chats_db import db
from info import ADMINS
@Client.on_message(filters.command("broadcast") & filters.user(ADMINS) & filters.reply)
async def broadcast(bot, message):
users = await db.get_all_users()
b_msg = message.reply_to_message
sts = await message.reply_text('Bʀᴏᴀᴅᴄᴀsᴛɪɴɢ Yᴏᴜʀ Mᴇssᴀɢᴇs...')
start_time = time.time()
total_users = await db.total_users_count()
done = 0
blocked = 0
deleted = 0
failed =0
success = 0
async for user in users:
pti, sh = await broadcast_messages(int(user['id']), b_msg)
if pti:
success += 1
elif pti == False:
if sh == "Blocked":
blocked+=1
elif sh == "Deleted":
deleted += 1
elif sh == "Error":
failed += 1
done += 1
if not done % 20:
await sts.edit(f"Bʀᴏᴀᴅᴄᴀsᴛ Iɴ Pʀᴏɢʀᴇss:\n\nTᴏᴛᴀʟ Uꜱᴇʀꜱ {total_users}\nCᴏᴍᴩʟᴇᴛᴇᴅ: {done} / {total_users}\nSᴜᴄᴄᴇꜱꜱ: {success}\nBʟᴏᴄᴋᴇᴅ: {blocked}\nDᴇʟᴇᴛᴇᴅ: {deleted}")
time_taken = datetime.timedelta(seconds=int(time.time()-start_time))
await sts.delete()
await bot.send_message(message.chat.id, f"Bʀᴏᴀᴅᴄᴀsᴛ Coᴍᴩʟᴇᴛᴇᴅ:\nTɪᴍᴇ Tᴀᴋᴇᴅ{time_taken} Sᴇᴄ\n\nTᴏᴛᴀʟ Uꜱᴇʀꜱ: {total_users}\nCᴏᴍᴩʟᴇᴛᴇᴅ: {done} / {total_users}\nSucᴄᴇꜱꜱ: {success}\nBʟᴏᴄᴋᴇᴅ: {blocked}\nDᴇʟᴇᴛᴇᴅ: {deleted}")
@Client.on_message(filters.command("clear_junk") & filters.user(ADMINS))
async def remove_junkuser__db(bot, message):
users = await db.get_all_users()
b_msg = message
sts = await message.reply_text('IN PROGRESS.......')
start_time = time.time()
total_users = await db.total_users_count()
blocked = 0
deleted = 0
failed = 0
done = 0
async for user in users:
pti, sh = await clear_junk(int(user['id']), b_msg)
if pti == False:
if sh == "Blocked":
blocked+=1
elif sh == "Deleted":
deleted += 1
elif sh == "Error":
failed += 1
done += 1
if not done % 20:
await sts.edit(f"In Progress:\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nBlocked: {blocked}\nDeleted: {deleted}")
time_taken = datetime.timedelta(seconds=int(time.time()-start_time))
await sts.delete()
await bot.send_message(message.chat.id, f"Completed:\nCompleted in {time_taken} seconds.\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nBlocked: {blocked}\nDeleted: {deleted}")
@Client.on_message(filters.command("group_broadcast") & filters.user(ADMINS) & filters.reply)
async def broadcast_group(bot, message):
groups = await db.get_all_chats()
b_msg = message.reply_to_message
sts = await message.reply_text(text='Broadcasting your messages To Groups...')
start_time = time.time()
total_groups = await db.total_chat_count()
done = 0
failed = ""
success = 0
deleted = 0
async for group in groups:
pti, sh, ex = await broadcast_messages_group(int(group['id']), b_msg)
if pti == True:
if sh == "Succes":
success += 1
elif pti == False:
if sh == "deleted":
deleted+=1
failed += ex
try:
await bot.leave_chat(int(group['id']))
except Exception as e:
print(f"{e} > {group['id']}")
done += 1
if not done % 20:
await sts.edit(f"Broadcast in progress:\n\nTotal Groups {total_groups}\nCompleted: {done} / {total_groups}\nSuccess: {success}\nDeleted: {deleted}")
time_taken = datetime.timedelta(seconds=int(time.time()-start_time))
await sts.delete()
try:
await message.reply_text(f"Broadcast Completed:\nCompleted in {time_taken} seconds.\n\nTotal Groups {total_groups}\nCompleted: {done} / {total_groups}\nSuccess: {success}\nDeleted: {deleted}\n\nFiled Reson:- {failed}")
except MessageTooLong:
with open('reason.txt', 'w+') as outfile:
outfile.write(failed)
await message.reply_document('reason.txt', caption=f"Completed:\nCompleted in {time_taken} seconds.\n\nTotal Groups {total_groups}\nCompleted: {done} / {total_groups}\nSuccess: {success}\nDeleted: {deleted}")
os.remove("reason.txt")
@Client.on_message(filters.command(["junk_group", "clear_junk_group"]) & filters.user(ADMINS))
async def junk_clear_group(bot, message):
groups = await db.get_all_chats()
b_msg = message
sts = await message.reply_text(text='..............')
start_time = time.time()
total_groups = await db.total_chat_count()
done = 0
failed = ""
deleted = 0
async for group in groups:
pti, sh, ex = await junk_group(int(group['id']), b_msg)
if pti == False:
if sh == "deleted":
deleted+=1
failed += ex
try:
await bot.leave_chat(int(group['id']))
except Exception as e:
print(f"{e} > {group['id']}")
done += 1
if not done % 20:
await sts.edit(f"in progress:\n\nTotal Groups {total_groups}\nCompleted: {done} / {total_groups}\nDeleted: {deleted}")
time_taken = datetime.timedelta(seconds=int(time.time()-start_time))
await sts.delete()
try:
await bot.send_message(message.chat.id, f"Completed:\nCompleted in {time_taken} seconds.\n\nTotal Groups {total_groups}\nCompleted: {done} / {total_groups}\nDeleted: {deleted}\n\nFiled Reson:- {failed}")
except MessageTooLong:
with open('junk.txt', 'w+') as outfile:
outfile.write(failed)
await message.reply_document('junk.txt', caption=f"Completed:\nCompleted in {time_taken} seconds.\n\nTotal Groups {total_groups}\nCompleted: {done} / {total_groups}\nDeleted: {deleted}")
os.remove("junk.txt")
async def broadcast_messages_group(chat_id, message):
try:
await message.copy(chat_id=chat_id)
return True, "Succes", 'mm'
except FloodWait as e:
await asyncio.sleep(e.value)
return await broadcast_messages_group(chat_id, message)
except Exception as e:
await db.delete_chat(int(chat_id))
logging.info(f"{chat_id} - PeerIdInvalid")
return False, "deleted", f'{e}\n\n'
async def junk_group(chat_id, message):
try:
kk = await message.copy(chat_id=chat_id)
await kk.delete(True)
return True, "Succes", 'mm'
except FloodWait as e:
await asyncio.sleep(e.value)
return await junk_group(chat_id, message)
except Exception as e:
await db.delete_chat(int(chat_id))
logging.info(f"{chat_id} - PeerIdInvalid")
return False, "deleted", f'{e}\n\n'
async def clear_junk(user_id, message):
try:
key = await message.copy(chat_id=user_id)
await key.delete(True)
return True, "Success"
except FloodWait as e:
await asyncio.sleep(e.value)
return await clear_junk(user_id, message)
except InputUserDeactivated:
await db.delete_user(int(user_id))
logging.info(f"{user_id}-Removed from Database, since deleted account.")
return False, "Deleted"
except UserIsBlocked:
logging.info(f"{user_id} -Blocked the bot.")
return False, "Blocked"
except PeerIdInvalid:
await db.delete_user(int(user_id))
logging.info(f"{user_id} - PeerIdInvalid")
return False, "Error"
except Exception as e:
return False, "Error"
async def broadcast_messages(user_id, message):
try:
await message.copy(chat_id=user_id)
return True, "Success"
except FloodWait as e:
await asyncio.sleep(e.value)
return await broadcast_messages(user_id, message)
except InputUserDeactivated:
await db.delete_user(int(user_id))
logging.info(f"{user_id}-Removed from Database, since deleted account.")
return False, "Deleted"
except UserIsBlocked:
logging.info(f"{user_id} -Blocked the bot.")
return False, "Blocked"
except PeerIdInvalid:
await db.delete_user(int(user_id))
logging.info(f"{user_id} - PeerIdInvalid")
return False, "Error"
except Exception as e:
return False, "Error"
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\commands.py
import os, re, json, base64, logging, random, asyncio
from Script import script
from database.users_chats_db import db
from pyrogram import Client, filters, enums
from pyrogram.errors import ChatAdminRequired, FloodWait
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from database.ia_filterdb import Media, get_file_details, unpack_new_file_id
from info import CHANNELS, ADMINS, AUTH_CHANNEL, LOG_CHANNEL, PICS, BATCH_FILE_CAPTION, CUSTOM_FILE_CAPTION, PROTECT_CONTENT, START_MESSAGE, FORCE_SUB_TEXT, SUPPORT_CHAT
from utils import get_settings, get_size, is_subscribed, save_group_settings, temp
from database.connections_mdb import active_connection
logger = logging.getLogger(__name__)
BATCH_FILES = {}
@Client.on_message(filters.command("start") & filters.incoming)
async def start(client, message):
if message.chat.type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
buttons = [[
InlineKeyboardButton('📢 Uᴩᴅᴀᴛᴇꜱ 📢', url=f'https://t.me/{SUPPORT_CHAT}')
],[
InlineKeyboardButton('ℹ️ Hᴇʟᴩ ℹ️', url=f"https://t.me/{temp.U_NAME}?start=help")
]]
await message.reply(START_MESSAGE.format(user=message.from_user.mention if message.from_user else message.chat.title, bot=client.mention), reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True)
await asyncio.sleep(2)
if not await db.get_chat(message.chat.id):
total = await client.get_chat_members_count(message.chat.id)
await client.send_message(LOG_CHANNEL, script.LOG_TEXT_G.format(a=message.chat.title, b=message.chat.id, c=message.chat.username, d=total, f=client.mention, e="Unknown"))
await db.add_chat(message.chat.id, message.chat.title, message.chat.username)
return
if not await db.is_user_exist(message.from_user.id):
await db.add_user(message.from_user.id, message.from_user.first_name)
await client.send_message(LOG_CHANNEL, script.LOG_TEXT_P.format(message.from_user.id, message.from_user.mention, message.from_user.username, temp.U_NAME))
if len(message.command) != 2:
buttons = [[
InlineKeyboardButton("➕️ Aᴅᴅ Mᴇ Tᴏ Yᴏᴜʀ Cʜᴀᴛ ➕", url=f"http://t.me/{temp.U_NAME}?startgroup=true")
],[
InlineKeyboardButton("Sᴇᴀʀᴄʜ 🔎", switch_inline_query_current_chat=''),
InlineKeyboardButton("Cʜᴀɴɴᴇʟ 🔈", url="https://t.me/mkn_bots_updates")
],[
InlineKeyboardButton("Hᴇʟᴩ 🕸️", callback_data="help"),
InlineKeyboardButton("Aʙᴏᴜᴛ ✨", callback_data="about")
]]
m = await message.reply_sticker("CAACAgUAAxkBAAEBvlVk7YKnYxIHVnKW2PUwoibIR2ygGAACBAADwSQxMYnlHW4Ls8gQHgQ")
await asyncio.sleep(2)
await message.reply_photo(photo=random.choice(PICS), caption=START_MESSAGE.format(user=message.from_user.mention, bot=client.mention), reply_markup=InlineKeyboardMarkup(buttons), parse_mode=enums.ParseMode.HTML)
return await m.delete()
if AUTH_CHANNEL and not await is_subscribed(client, message):
try:
invite_link = await client.create_chat_invite_link(int(AUTH_CHANNEL))
except ChatAdminRequired:
logger.error("MAKE SURE BOT IS ADMIN IN FORCESUB CHANNEL")
return
btn = [[InlineKeyboardButton("Jᴏɪɴ Mʏ Cʜᴀɴɴᴇʟ ✨", url=invite_link.invite_link)]]
if message.command[1] != "subscribe":
try:
kk, file_id = message.command[1].split("_", 1)
pre = 'checksubp' if kk == 'filep' else 'checksub'
btn.append([InlineKeyboardButton("⟳ Tʀʏ Aɢᴀɪɴ", callback_data=f"{pre}#{file_id}")])
except (IndexError, ValueError):
btn.append([InlineKeyboardButton("⟳ Tʀʏ Aɢᴀɪɴ", url=f"https://t.me/{temp.U_NAME}?start={message.command[1]}")])
try:
return await client.send_message(chat_id=message.from_user.id, text=FORCE_SUB_TEXT, reply_markup=InlineKeyboardMarkup(btn), parse_mode=enums.ParseMode.DEFAULT)
except Exception as e:
print(f"Force Sub Text Error\n{e}")
return await client.send_message(chat_id=message.from_user.id, text=script.FORCE_SUB_TEXT, reply_markup=InlineKeyboardMarkup(btn), parse_mode=enums.ParseMode.DEFAULT)
if len(message.command) == 2 and message.command[1] in ["subscribe", "error", "okay", "help"]:
buttons = [[
InlineKeyboardButton("➕️ Aᴅᴅ Mᴇ Tᴏ Yᴏᴜʀ Cʜᴀᴛ ➕", url=f"http://t.me/{temp.U_NAME}?startgroup=true")
],[
InlineKeyboardButton("Sᴇᴀʀᴄʜ 🔎", switch_inline_query_current_chat=''),
InlineKeyboardButton("Cʜᴀɴɴᴇʟ 🔈", url="https://t.me/mkn_bots_updates")
],[
InlineKeyboardButton("Hᴇʟᴩ 🕸️", callback_data="help"),
InlineKeyboardButton("Aʙᴏᴜᴛ ✨", callback_data="about")
]]
m = await message.reply_sticker("CAACAgUAAxkBAAEBvlVk7YKnYxIHVnKW2PUwoibIR2ygGAACBAADwSQxMYnlHW4Ls8gQHgQ")
await asyncio.sleep(2)
await message.reply_photo(photo=random.choice(PICS), caption=START_MESSAGE.format(user=message.from_user.mention, bot=client.mention), reply_markup=InlineKeyboardMarkup(buttons), parse_mode=enums.ParseMode.HTML)
return await m.delete()
data = message.command[1]
try:
pre, file_id = data.split('_', 1)
except:
file_id = data
pre = ""
if data.split("-", 1)[0] == "BATCH":
sts = await message.reply("PLEASE WAIT......")
file_id = data.split("-", 1)[1]
msgs = BATCH_FILES.get(file_id)
if not msgs:
file = await client.download_media(file_id)
try:
with open(file) as file_data:
msgs=json.loads(file_data.read())
except:
await sts.edit("FAILED")
return await client.send_message(LOG_CHANNEL, "UNABLE TO OPEN FILE.")
os.remove(file)
BATCH_FILES[file_id] = msgs
for msg in msgs:
title = msg.get("title")
size=get_size(int(msg.get("size", 0)))
f_caption=msg.get("caption", "")
if BATCH_FILE_CAPTION:
try:
f_caption=BATCH_FILE_CAPTION.format(mention=message.from_user.mention, file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='' if f_caption is None else f_caption)
except Exception as e:
logger.exception(e)
f_caption=f_caption
if f_caption is None:
f_caption = f"{title}"
try:
await client.send_cached_media(chat_id=message.from_user.id, file_id=msg.get("file_id"), caption=f_caption, protect_content=msg.get('protect', False))
except FloodWait as e:
await asyncio.sleep(e.value)
await client.send_cached_media(chat_id=message.from_user.id, file_id=msg.get("file_id"), caption=f_caption, protect_content=msg.get('protect', False))
except Exception as e:
logger.warning(e, exc_info=True)
continue
await asyncio.sleep(1)
return await sts.delete()
elif data.split("-", 1)[0] == "DSTORE":
sts = await message.reply("PLEASE WAIT....")
b_string = data.split("-", 1)[1]
decoded = (base64.urlsafe_b64decode(b_string + "=" * (-len(b_string) % 4))).decode("ascii")
try:
f_msg_id, l_msg_id, f_chat_id, protect = decoded.split("_", 3)
except:
f_msg_id, l_msg_id, f_chat_id = decoded.split("_", 2)
protect = "/pbatch" if PROTECT_CONTENT else "batch"
diff = int(l_msg_id) - int(f_msg_id)
async for msg in client.iter_messages(int(f_chat_id), int(l_msg_id), int(f_msg_id)):
if msg.media:
media = getattr(msg, msg.media)
if BATCH_FILE_CAPTION:
try:
f_caption=BATCH_FILE_CAPTION.format(mention=message.from_user.mention, file_name=getattr(media, 'file_name', ''), file_size=getattr(media, 'file_size', ''), file_caption=getattr(msg, 'caption', ''))
except Exception as e:
logger.exception(e)
f_caption = getattr(msg, 'caption', '')
else:
media = getattr(msg, msg.media)
file_name = getattr(media, 'file_name', '')
f_caption = getattr(msg, 'caption', file_name)
try:
await msg.copy(message.chat.id, caption=f_caption, protect_content=True if protect == "/pbatch" else False)
except FloodWait as e:
await asyncio.sleep(e.value)
await msg.copy(message.chat.id, caption=f_caption, protect_content=True if protect == "/pbatch" else False)
except Exception as e:
logger.exception(e)
continue
elif msg.empty:
continue
else:
try:
await msg.copy(message.chat.id, protect_content=True if protect == "/pbatch" else False)
except FloodWait as e:
await asyncio.sleep(e.value)
await msg.copy(message.chat.id, protect_content=True if protect == "/pbatch" else False)
except Exception as e:
logger.exception(e)
continue
await asyncio.sleep(1)
return await sts.delete()
files_ = await get_file_details(file_id)
if not files_:
pre, file_id = ((base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))).decode("ascii")).split("_", 1)
try:
msg = await client.send_cached_media(chat_id=message.from_user.id, file_id=file_id, protect_content=True if pre == 'filep' else False,)
filetype = msg.media
file = getattr(msg, filetype)
title = file.file_name
size=get_size(file.file_size)
f_caption = f"{title}
"
if CUSTOM_FILE_CAPTION:
try: f_caption=CUSTOM_FILE_CAPTION.format(mention=message.from_user.mention, file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='')
except: return
return await msg.edit_caption(f_caption)
except: pass
return await message.reply('NO SUCH FILE EXIST...')
files = files_[0]
title = files.file_name
size=get_size(files.file_size)
f_caption=files.caption
if CUSTOM_FILE_CAPTION:
try:
f_caption=CUSTOM_FILE_CAPTION.format(mention=message.from_user.mention, file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='' if f_caption is None else f_caption)
except Exception as e:
logger.exception(e)
f_caption=f_caption
if f_caption is None:
f_caption = f"{files.file_name}"
await client.send_cached_media(chat_id=message.from_user.id, file_id=file_id, caption=f_caption, protect_content=True if pre == 'filep' else False,)
@Client.on_message(filters.command('channel') & filters.user(ADMINS))
async def channel_info(bot, message):
if isinstance(CHANNELS, (int, str)): channels = [CHANNELS]
elif isinstance(CHANNELS, list): channels = CHANNELS
else: raise ValueError("Unexpected Type Of CHANNELS")
text = '📑 **Indexed channels/groups**\n'
for channel in channels:
chat = await bot.get_chat(channel)
if chat.username: text += '\n@' + chat.username
else: text += '\n' + chat.title or chat.first_name
text += f'\n\n**Total:** {len(CHANNELS)}'
if len(text) < 4096: await message.reply(text)
else:
file = 'Indexed channels.txt'
with open(file, 'w') as f:
f.write(text)
await message.reply_document(file)
os.remove(file)
@Client.on_message(filters.command('delete') & filters.user(ADMINS))
async def delete(bot, message):
reply = message.reply_to_message
if reply and reply.media: msg = await message.reply("Processing...⏳", quote=True)
else: return await message.reply('Reply to file with /delete which you want to delete', quote=True)
for file_type in ("document", "video", "audio"):
media = getattr(reply, file_type, None)
if media is not None: break
else: return await msg.edit('This Is Not Supported File Format')
file_id, file_ref = unpack_new_file_id(media.file_id)
result = await Media.collection.delete_one({'_id': file_id})
if result.deleted_count: await msg.edit('File Is Successfully Deleted From Database')
else:
file_name = re.sub(r"(_|\-|\.|\+)", " ", str(media.file_name))
result = await Media.collection.delete_many({
'file_name': file_name,
'file_size': media.file_size,
'mime_type': media.mime_type
})
if result.deleted_count: await msg.edit('File Is Successfully Deleted From Database')
else:
result = await Media.collection.delete_many({
'file_name': media.file_name,
'file_size': media.file_size,
'mime_type': media.mime_type
})
if result.deleted_count: await msg.edit('File Is Successfully Deleted From Database')
else: await msg.edit('File Not Found In Database')
@Client.on_message(filters.command('deleteall') & filters.user(ADMINS))
async def delete_all_index(bot, message):
button = [[
InlineKeyboardButton("YES", callback_data="autofilter_delete")
],[
InlineKeyboardButton("CANCEL", callback_data="close_data")
]]
await message.reply_text('This Will Delete All Indexed Files.\ndo You Want To Continue??', quote=True, reply_markup=InlineKeyboardMarkup(button))
@Client.on_callback_query(filters.regex(r'^autofilter_delete'))
async def delete_all_index_confirm(bot, message):
await Media.collection.drop()
await message.message.edit('Succesfully Deleted All The Indexed Files.')
@Client.on_message(filters.command('settings'))
async def settings(client, message):
userid = message.from_user.id if message.from_user else None
if not userid: return await message.reply(f"Yᴏᴜ Aʀᴇ Aɴᴏɴʏᴍᴏᴜs Aᴅᴍɪɴ. Usᴇ /connect {message.chat.id} Iɴ PM")
chat_type = message.chat.type
if chat_type == enums.ChatType.PRIVATE:
grpid = await active_connection(str(userid))
if grpid is not None:
grp_id = grpid
try:
chat = await client.get_chat(grpid)
title = chat.title
except:
return await message.reply_text("Mᴀᴋᴇ Sᴜʀᴇ I'ᴍ Pʀᴇsᴇɴᴛ Iɴ Yᴏᴜʀ Gʀᴏᴜᴘ!!", quote=True)
else: return await message.reply_text("I'ᴍ Nᴏᴛ Cᴏɴɴᴇᴄᴛᴇᴅ Tᴏ Aɴʏ Gʀᴏᴜᴘs!", quote=True)
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
grp_id = message.chat.id
title = message.chat.title
else: return
st = await client.get_chat_member(grp_id, userid)
if (
st.status != enums.ChatMemberStatus.ADMINISTRATOR
and st.status != enums.ChatMemberStatus.OWNER
and str(userid) not in ADMINS
): return
settings = await get_settings(grp_id)
if settings is not None:
buttons = [[
InlineKeyboardButton(f"ꜰɪʟᴛᴇʀ ʙᴜᴛᴛᴏɴ : {'sɪɴɢʟᴇ' if settings['button'] else 'ᴅᴏᴜʙʟᴇ'}", f'setgs#button#{settings["button"]}#{str(grp_id)}')
],[
InlineKeyboardButton(f"ꜰɪʟᴇ ɪɴ ᴩᴍ ꜱᴛᴀʀᴛ: {'ᴏɴ' if settings['botpm'] else 'ᴏꜰꜰ'}", f'setgs#botpm#{settings["botpm"]}#{str(grp_id)}')
],[
InlineKeyboardButton(f"ʀᴇꜱᴛʀɪᴄᴛ ᴄᴏɴᴛᴇɴᴛ : {'ᴏɴ' if settings['file_secure'] else 'ᴏꜰꜰ'}", f'setgs#file_secure#{settings["file_secure"]}#{str(grp_id)}')
],[
InlineKeyboardButton(f"ɪᴍᴅʙ ɪɴ ꜰɪʟᴛᴇʀ : {'ᴏɴ' if settings['imdb'] else 'ᴏꜰꜰ'}", f'setgs#imdb#{settings["imdb"]}#{str(grp_id)}')
],[
InlineKeyboardButton(f"ꜱᴩᴇʟʟɪɴɢ ᴄʜᴇᴄᴋ : {'ᴏɴ' if settings['spell_check'] else 'ᴏꜰꜰ'}", f'setgs#spell_check#{settings["spell_check"]}#{str(grp_id)}')
],[
InlineKeyboardButton(f"ᴡᴇʟᴄᴏᴍᴇ ᴍᴇꜱꜱᴀɢᴇ : {'ᴏɴ' if settings['welcome'] else 'ᴏꜰꜰ'}", f'setgs#welcome#{settings["welcome"]}#{str(grp_id)}')
]]
await message.reply_text(
text=f"Cʜᴀɴɢᴇ Yᴏᴜʀ Sᴇᴛᴛɪɴɢꜱ Fᴏʀ {title} Aꜱ Yᴏᴜʀ Wɪꜱʜ ⚙",
reply_markup=InlineKeyboardMarkup(buttons),
quote=True,
disable_web_page_preview=True,
parse_mode=enums.ParseMode.HTML,
)
@Client.on_message(filters.command('set_template'))
async def save_template(client, message):
sts = await message.reply("Cʜᴇᴄᴋɪɴɢ Tᴇᴍᴘʟᴀᴛᴇ")
userid = message.from_user.id if message.from_user else None
if not userid: return await message.reply(f"Yᴏᴜ Aʀᴇ Aɴᴏɴʏᴍᴏᴜs Aᴅᴍɪɴ. Usᴇ /connect {message.chat.id} Iɴ PM")
chat_type = message.chat.type
if chat_type == enums.ChatType.PRIVATE:
grpid = await active_connection(str(userid))
if grpid is not None:
grp_id = grpid
try:
chat = await client.get_chat(grpid)
title = chat.title
except:
return await message.reply_text("Mᴀᴋᴇ Sᴜʀᴇ I'ᴍ Pʀᴇsᴇɴᴛ Iɴ Yᴏᴜʀ Gʀᴏᴜᴘ !!", quote=True)
else:
return await message.reply_text("I'ᴍ Nᴏᴛ Cᴏɴɴᴇᴄᴛᴇᴅ Tᴏ Aɴʏ Gʀᴏᴜᴘs!", quote=True)
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
grp_id = message.chat.id
title = message.chat.title
else: return
st = await client.get_chat_member(grp_id, userid)
if (
st.status != enums.ChatMemberStatus.ADMINISTRATOR
and st.status != enums.ChatMemberStatus.OWNER
and str(userid) not in ADMINS
): return
if len(message.command) < 2: return await sts.edit("No Iɴᴩᴜᴛ!!")
template = message.text.split(" ", 1)[1]
await save_group_settings(grp_id, 'template', template)
await sts.edit(f"Sᴜᴄᴄᴇssғᴜʟʟʏ Cʜᴀɴɢᴇᴅ Tᴇᴍᴘʟᴀᴛᴇ Fᴏʀ {title} Tᴏ\n\n{template}")
@Client.on_message(filters.command('get_template'))
async def geg_template(client, message):
sts = await message.reply("Cʜᴇᴄᴋɪɴɢ Tᴇᴍᴘʟᴀᴛᴇ")
userid = message.from_user.id if message.from_user else None
if not userid: return await message.reply(f"Yᴏᴜ Aʀᴇ Aɴᴏɴʏᴍᴏᴜs Aᴅᴍɪɴ. Usᴇ /connect {message.chat.id} Iɴ PM")
chat_type = message.chat.type
if chat_type == enums.ChatType.PRIVATE:
grpid = await active_connection(str(userid))
if grpid is not None:
grp_id = grpid
try:
chat = await client.get_chat(grpid)
title = chat.title
except:
return await message.reply_text("Mᴀᴋᴇ Sᴜʀᴇ I'ᴍ Pʀᴇsᴇɴᴛ Iɴ Yᴏᴜʀ Gʀᴏᴜᴘ !!", quote=True)
else:
return await message.reply_text("I'ᴍ Nᴏᴛ Cᴏɴɴᴇᴄᴛᴇᴅ Tᴏ Aɴʏ Gʀᴏᴜᴘs!", quote=True)
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
grp_id = message.chat.id
title = message.chat.title
else: return
st = await client.get_chat_member(grp_id, userid)
if (
st.status != enums.ChatMemberStatus.ADMINISTRATOR
and st.status != enums.ChatMemberStatus.OWNER
and str(userid) not in ADMINS
): return
settings = await get_settings(grp_id)
template = settings['template']
await sts.edit(f"Cᴜʀʀᴇɴᴛ Tᴇᴍᴘʟᴀᴛᴇ Fᴏʀ {title} Iꜱ\n\n{template}")
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\connection.py
from pyrogram import filters, Client, enums
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from database.connections_mdb import add_connection, all_connections, if_active, delete_connection
from info import ADMINS
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
@Client.on_message((filters.private | filters.group) & filters.command('connect'))
async def addconnection(client, message):
userid = message.from_user.id if message.from_user else None
if not userid:
return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
chat_type = message.chat.type
if chat_type == enums.ChatType.PRIVATE:
try:
cmd, group_id = message.text.split(" ", 1)
except:
await message.reply_text(
"Enter in correct format!\n\n"
"/connect groupid
\n\n"
"Get your Group id by adding this bot to your group and use /id
",
quote=True
)
return
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
group_id = message.chat.id
try:
st = await client.get_chat_member(group_id, userid)
if (
st.status != enums.ChatMemberStatus.ADMINISTRATOR
and st.status != enums.ChatMemberStatus.OWNER
and userid not in ADMINS
):
return await message.reply_text("You should be an admin in Given group!", quote=True)
except Exception as e:
logger.exception(e)
return await message.reply_text("Invalid Group ID!\n\nIf correct, Make sure I'm present in your group!!", quote=True,)
try:
st = await client.get_chat_member(group_id, "me")
if st.status == enums.ChatMemberStatus.ADMINISTRATOR:
ttl = await client.get_chat(group_id)
title = ttl.title
addcon = await add_connection(str(group_id), str(userid))
if addcon:
await message.reply_text(
f"Successfully connected to **{title}**\nNow manage your group from my pm !",
quote=True,
parse_mode=enums.ParseMode.MARKDOWN
)
if chat_type in ["group", "supergroup"]:
await client.send_message(
userid,
f"Connected to **{title}** !",
parse_mode=enums.ParseMode.MARKDOWN
)
else:
await message.reply_text("You're already connected to this chat!", quote=True)
else:
await message.reply_text("Add me as an admin in group", quote=True)
except Exception as e:
logger.exception(e)
return await message.reply_text('Some error occurred! Try again later.', quote=True)
@Client.on_message((filters.private | filters.group) & filters.command('disconnect'))
async def deleteconnection(client, message):
userid = message.from_user.id if message.from_user else None
if not userid:
return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
chat_type = message.chat.type
if chat_type == enums.ChatType.PRIVATE:
await message.reply_text("Run /connections to view or disconnect from groups!", quote=True)
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
group_id = message.chat.id
st = await client.get_chat_member(group_id, userid)
if (
st.status != enums.ChatMemberStatus.ADMINISTRATOR
and st.status != enums.ChatMemberStatus.OWNER
and str(userid) not in ADMINS
):
return
delcon = await delete_connection(str(userid), str(group_id))
if delcon:
await message.reply_text("Successfully disconnected from this chat", quote=True)
else:
await message.reply_text("This chat isn't connected to me!\nDo /connect to connect.", quote=True)
@Client.on_message(filters.private & filters.command(["connections"]))
async def connections(client, message):
userid = message.from_user.id
groupids = await all_connections(str(userid))
if groupids is None:
return await message.reply_text("There are no active connections!! Connect to some groups first.", quote=True)
buttons = []
for groupid in groupids:
try:
ttl = await client.get_chat(int(groupid))
title = ttl.title
active = await if_active(str(userid), str(groupid))
act = " - ACTIVE" if active else ""
buttons.append([InlineKeyboardButton(f"{title}{act}", callback_data=f"groupcb:{groupid}:{act}")])
except:
pass
if buttons:
await message.reply_text("Your connected group details ;\n\n", reply_markup=InlineKeyboardMarkup(buttons), quote=True)
else:
await message.reply_text("There are no active connections!! Connect to some groups first.", quote=True)
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\file_store.py
import re, os, json, base64, logging
from pyrogram import filters, Client, enums
from pyrogram.errors.exceptions.bad_request_400 import ChannelInvalid, UsernameInvalid, UsernameNotModified
from info import ADMINS, LOG_CHANNEL, FILE_STORE_CHANNEL, PUBLIC_FILE_STORE
from database.ia_filterdb import unpack_new_file_id
from utils import temp
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
async def allowed(_, __, message):
if PUBLIC_FILE_STORE:
return True
if message.from_user and message.from_user.id in ADMINS:
return True
return False
@Client.on_message(filters.command(['link', 'plink']) & filters.create(allowed))
async def gen_link_s(bot, message):
replied = message.reply_to_message
if not replied:
return await message.reply('Reply to a message to get a shareable link.')
file_type = replied.media
if file_type not in [enums.MessageMediaType.VIDEO, enums.MessageMediaType.AUDIO, enums.MessageMediaType.DOCUMENT]:
return await message.reply("Reply to a supported media")
if message.has_protected_content and message.chat.id not in ADMINS:
return await message.reply("okDa")
file_id, ref = unpack_new_file_id((getattr(replied, file_type.value)).file_id)
string = 'filep_' if message.text.lower().strip() == "/plink" else 'file_'
string += file_id
outstr = base64.urlsafe_b64encode(string.encode("ascii")).decode().strip("=")
await message.reply(f"Here is your Link:\nhttps://t.me/{temp.U_NAME}?start={outstr}")
@Client.on_message(filters.command(['batch', 'pbatch']) & filters.create(allowed))
async def gen_link_batch(bot, message):
if " " not in message.text:
return await message.reply("Use correct format.\nExample /batch https://t.me/TeamEvamaria/10 https://t.me/TeamEvamaria/20
.")
links = message.text.strip().split(" ")
if len(links) != 3:
return await message.reply("Use correct format.\nExample /batch https://t.me/TeamEvamaria/10 https://t.me/TeamEvamaria/20
.")
cmd, first, last = links
regex = re.compile("(https://)?(t\.me/|telegram\.me/|telegram\.dog/)(c/)?(\d+|[a-zA-Z_0-9]+)/(\d+)$")
match = regex.match(first)
if not match:
return await message.reply('Invalid link')
f_chat_id = match.group(4)
f_msg_id = int(match.group(5))
if f_chat_id.isnumeric():
f_chat_id = int(("-100" + f_chat_id))
match = regex.match(last)
if not match:
return await message.reply('Invalid link')
l_chat_id = match.group(4)
l_msg_id = int(match.group(5))
if l_chat_id.isnumeric():
l_chat_id = int(("-100" + l_chat_id))
if f_chat_id != l_chat_id:
return await message.reply("Chat ids not matched.")
try:
chat_id = (await bot.get_chat(f_chat_id)).id
except ChannelInvalid:
return await message.reply('This may be a private channel / group. Make me an admin over there to index the files.')
except (UsernameInvalid, UsernameNotModified):
return await message.reply('Invalid Link specified.')
except Exception as e:
return await message.reply(f'Errors - {e}')
sts = await message.reply("Generating link for your message.\nThis may take time depending upon number of messages")
if chat_id in FILE_STORE_CHANNEL:
string = f"{f_msg_id}_{l_msg_id}_{chat_id}_{cmd.lower().strip()}"
b_64 = base64.urlsafe_b64encode(string.encode("ascii")).decode().strip("=")
return await sts.edit(f"Here is your link https://t.me/{temp.U_NAME}?start=DSTORE-{b_64}")
FRMT = "Generating Link...\nTotal Messages: `{total}`\nDone: `{current}`\nRemaining: `{rem}`\nStatus: `{sts}`"
outlist = []
# file store without db channel
og_msg = 0
tot = 0
async for msg in bot.iter_messages(f_chat_id, l_msg_id, f_msg_id):
tot += 1
if msg.empty or msg.service:
continue
if not msg.media:
# only media messages supported.
continue
try:
file_type = msg.media
file = getattr(msg, file_type.value)
caption = getattr(msg, 'caption', '')
if caption:
caption = caption.html
if file:
file = {
"file_id": file.file_id,
"caption": caption,
"title": getattr(file, "file_name", ""),
"size": file.file_size,
"protect": cmd.lower().strip() == "/pbatch",
}
og_msg +=1
outlist.append(file)
except:
pass
if not og_msg % 20:
try:
await sts.edit(FRMT.format(total=l_msg_id-f_msg_id, current=tot, rem=((l_msg_id-f_msg_id) - tot), sts="Saving Messages"))
except:
pass
with open(f"batchmode_{message.from_user.id}.json", "w+") as out:
json.dump(outlist, out)
post = await bot.send_document(LOG_CHANNEL, f"batchmode_{message.from_user.id}.json", file_name="Batch.json", caption="⚠️Generated for filestore.")
os.remove(f"batchmode_{message.from_user.id}.json")
file_id, ref = unpack_new_file_id(post.document.file_id)
await sts.edit(f"Here is your link\nContains `{og_msg}` files.\n https://t.me/{temp.U_NAME}?start=BATCH-{file_id}")
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\filters_global.py
import io
from pyrogram import filters, Client, enums
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from database.filters_mdb import add_filter, get_filters, delete_filter, count_filters
from database.gfilters_mdb import add_gfilter, get_gfilters, delete_gfilter, count_gfilters, del_allg
from database.connections_mdb import active_connection
from utils import get_file_id, parser, split_quotes
from info import ADMINS
@Client.on_message(filters.command(['filter', 'add']) & filters.incoming)
async def addfilter(client, message):
userid = message.from_user.id if message.from_user else None
if not userid:
return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
chat_type = message.chat.type
args = message.text.html.split(None, 1)
if chat_type == enums.ChatType.PRIVATE:
grpid = await active_connection(str(userid))
if grpid is not None:
grp_id = grpid
try:
chat = await client.get_chat(grpid)
title = chat.title
except:
await message.reply_text("Make sure I'm present in your group!!", quote=True)
return
else:
await message.reply_text("I'm not connected to any groups!", quote=True)
return
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
grp_id = message.chat.id
title = message.chat.title
else:
return
st = await client.get_chat_member(grp_id, userid)
if (
st.status != enums.ChatMemberStatus.ADMINISTRATOR
and st.status != enums.ChatMemberStatus.OWNER
and str(userid) not in ADMINS
):
return
if len(args) < 2:
await message.reply_text("Command Incomplete :(", quote=True)
return
extracted = split_quotes(args[1])
text = extracted[0].lower()
if not message.reply_to_message and len(extracted) < 2:
await message.reply_text("Add some content to save your filter!", quote=True)
return
if (len(extracted) >= 2) and not message.reply_to_message:
reply_text, btn, alert = parser(extracted[1], text, "alertmessage")
fileid = None
if not reply_text:
await message.reply_text("You cannot have buttons alone, give some text to go with it!", quote=True)
return
elif message.reply_to_message and message.reply_to_message.reply_markup:
try:
rm = message.reply_to_message.reply_markup
btn = rm.inline_keyboard
msg = get_file_id(message.reply_to_message)
if msg:
fileid = msg.file_id
reply_text = message.reply_to_message.caption.html
else:
reply_text = message.reply_to_message.text.html
fileid = None
alert = None
except:
reply_text = ""
btn = "[]"
fileid = None
alert = None
elif message.reply_to_message and message.reply_to_message.media:
try:
msg = get_file_id(message.reply_to_message)
fileid = msg.file_id if msg else None
reply_text, btn, alert = parser(extracted[1], text, "alertmessage") if message.reply_to_message.sticker else parser(message.reply_to_message.caption.html, text, "alertmessage")
except:
reply_text = ""
btn = "[]"
alert = None
elif message.reply_to_message and message.reply_to_message.text:
try:
fileid = None
reply_text, btn, alert = parser(message.reply_to_message.text.html, text, "alertmessage")
except:
reply_text = ""
btn = "[]"
alert = None
else:
return
await add_filter(grp_id, text, reply_text, btn, fileid, alert)
await message.reply_text(
f"Filter for `{text}` added in **{title}**",
quote=True,
parse_mode=enums.ParseMode.MARKDOWN
)
@Client.on_message(filters.command(['viewfilters', 'filters']) & filters.incoming)
async def get_all(client, message):
chat_type = message.chat.type
userid = message.from_user.id if message.from_user else None
if not userid:
return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
if chat_type == enums.ChatType.PRIVATE:
grpid = await active_connection(str(userid))
if grpid is not None:
grp_id = grpid
try:
chat = await client.get_chat(grpid)
title = chat.title
except:
await message.reply_text("Make sure I'm present in your group!!", quote=True)
return
else:
await message.reply_text("I'm not connected to any groups!", quote=True)
return
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
grp_id = message.chat.id
title = message.chat.title
else:
return
st = await client.get_chat_member(grp_id, userid)
if (
st.status != enums.ChatMemberStatus.ADMINISTRATOR
and st.status != enums.ChatMemberStatus.OWNER
and str(userid) not in ADMINS
):
return
texts = await get_filters(grp_id)
count = await count_filters(grp_id)
if count:
filterlist = f"Total number of filters in **{title}** : {count}\n\n"
for text in texts:
keywords = " × `{}`\n".format(text)
filterlist += keywords
if len(filterlist) > 4096:
with io.BytesIO(str.encode(filterlist.replace("`", ""))) as keyword_file:
keyword_file.name = "keywords.txt"
await message.reply_document(
document=keyword_file,
quote=True
)
return
else:
filterlist = f"There are no active filters in **{title}**"
await message.reply_text(
text=filterlist,
quote=True,
parse_mode=enums.ParseMode.MARKDOWN
)
@Client.on_message(filters.command('del') & filters.incoming)
async def deletefilter(client, message):
userid = message.from_user.id if message.from_user else None
if not userid:
return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
chat_type = message.chat.type
if chat_type == enums.ChatType.PRIVATE:
grpid = await active_connection(str(userid))
if grpid is not None:
grp_id = grpid
try:
chat = await client.get_chat(grpid)
title = chat.title
except:
await message.reply_text("Make sure I'm present in your group!!", quote=True)
return
else:
await message.reply_text("I'm not connected to any groups!", quote=True)
return
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
grp_id = message.chat.id
title = message.chat.title
else:
return
st = await client.get_chat_member(grp_id, userid)
if (
st.status != enums.ChatMemberStatus.ADMINISTRATOR
and st.status != enums.ChatMemberStatus.OWNER
and str(userid) not in ADMINS
):
return
try:
cmd, text = message.text.split(" ", 1)
except:
await message.reply_text(
"Mention the filtername which you wanna delete!\n\n"
"/del filtername
\n\n"
"Use /viewfilters to view all available filters",
quote=True
)
return
query = text.lower()
await delete_filter(message, query, grp_id)
@Client.on_message(filters.command('delall') & filters.incoming)
async def delallconfirm(client, message):
userid = message.from_user.id if message.from_user else None
if not userid:
return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
chat_type = message.chat.type
if chat_type == enums.ChatType.PRIVATE:
grpid = await active_connection(str(userid))
if grpid is not None:
grp_id = grpid
try:
chat = await client.get_chat(grpid)
title = chat.title
except:
await message.reply_text("Make sure I'm present in your group!!", quote=True)
return
else:
await message.reply_text("I'm not connected to any groups!", quote=True)
return
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
grp_id = message.chat.id
title = message.chat.title
else:
return
st = await client.get_chat_member(grp_id, userid)
if (st.status == enums.ChatMemberStatus.OWNER) or (str(userid) in ADMINS):
await message.reply_text(
f"This will delete all filters from '{title}'.\nDo you want to continue??",
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton(text="YES",callback_data="delallconfirm")],
[InlineKeyboardButton(text="CANCEL",callback_data="delallcancel")]
]),
quote=True
)
# Kanged from https://github.com/KDBotz
@Client.on_message(filters.command(['gfilter', 'addg']) & filters.incoming & filters.user(ADMINS))
async def addgfilter(client, message):
args = message.text.html.split(None, 1)
if len(args) < 2:
await message.reply_text("Command Incomplete :(", quote=True)
return
extracted = split_quotes(args[1])
text = extracted[0].lower()
if not message.reply_to_message and len(extracted) < 2:
await message.reply_text("Add some content to save your filter!", quote=True)
return
if (len(extracted) >= 2) and not message.reply_to_message:
reply_text, btn, alert = parser(extracted[1], text, "galert")
fileid = None
if not reply_text:
await message.reply_text("You cannot have buttons alone, give some text to go with it!", quote=True)
return
elif message.reply_to_message and message.reply_to_message.reply_markup:
try:
rm = message.reply_to_message.reply_markup
btn = rm.inline_keyboard
msg = get_file_id(message.reply_to_message)
if msg:
fileid = msg.file_id
reply_text = message.reply_to_message.caption.html
else:
reply_text = message.reply_to_message.text.html
fileid = None
alert = None
except:
reply_text = ""
btn = "[]"
fileid = None
alert = None
elif message.reply_to_message and message.reply_to_message.media:
try:
msg = get_file_id(message.reply_to_message)
fileid = msg.file_id if msg else None
reply_text, btn, alert = parser(extracted[1], text, "galert") if message.reply_to_message.sticker else parser(message.reply_to_message.caption.html, text, "galert")
except:
reply_text = ""
btn = "[]"
alert = None
elif message.reply_to_message and message.reply_to_message.text:
try:
fileid = None
reply_text, btn, alert = parser(message.reply_to_message.text.html, text, "galert")
except:
reply_text = ""
btn = "[]"
alert = None
else:
return
await add_gfilter('gfilters', text, reply_text, btn, fileid, alert)
await message.reply_text(
f"GFilter for `{text}` added",
quote=True,
parse_mode=enums.ParseMode.MARKDOWN
)
@Client.on_message(filters.command(['viewgfilters', 'gfilters']) & filters.incoming & filters.user(ADMINS))
async def get_all_gfilters(client, message):
texts = await get_gfilters('gfilters')
count = await count_gfilters('gfilters')
if count:
gfilterlist = f"Total number of gfilters : {count}\n\n"
for text in texts:
keywords = " × `{}`\n".format(text)
gfilterlist += keywords
if len(gfilterlist) > 4096:
with io.BytesIO(str.encode(gfilterlist.replace("`", ""))) as keyword_file:
keyword_file.name = "keywords.txt"
await message.reply_document(
document=keyword_file,
quote=True
)
return
else:
gfilterlist = f"There are no active gfilters."
await message.reply_text(
text=gfilterlist,
quote=True,
parse_mode=enums.ParseMode.MARKDOWN
)
@Client.on_message(filters.command('delg') & filters.incoming & filters.user(ADMINS))
async def deletegfilter(client, message):
try:
cmd, text = message.text.split(" ", 1)
except:
await message.reply_text(
"Mention the gfiltername which you wanna delete!\n\n"
"/delg gfiltername
\n\n"
"Use /viewgfilters to view all available gfilters",
quote=True
)
return
query = text.lower()
await delete_gfilter(message, query, 'gfilters')
@Client.on_message(filters.command('delallg') & filters.user(ADMINS))
async def delallgfill(client, message):
await message.reply_text(
f"Do you want to continue??",
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton(text="YES",callback_data="gconforme")],
[InlineKeyboardButton(text="CANCEL",callback_data="close_data")]
]),
quote=True
)
@Client.on_callback_query(filters.regex("gconforme"))
async def dellacbd(client, message):
await del_allg(message.message, 'gfilters')
return await message.reply("👍 Done")
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\group_filter.py
import asyncio, re, ast, math, logging
from pyrogram.errors.exceptions.bad_request_400 import MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty
from Script import script
from utils import get_shortlink, admin_filter
import pyrogram
from database.connections_mdb import active_connection, all_connections, delete_connection, if_active, make_active, make_inactive
from info import ADMINS, AUTH_CHANNEL, AUTH_USERS, CUSTOM_FILE_CAPTION, AUTH_GROUPS, P_TTI_SHOW_OFF, IMDB, PM_IMDB, SINGLE_BUTTON, PROTECT_CONTENT, \
SPELL_CHECK_REPLY, IMDB_TEMPLATE, IMDB_DELET_TIME, START_MESSAGE, PMFILTER, G_FILTER, BUTTON_LOCK, BUTTON_LOCK_TEXT, SHORT_URL, SHORT_API
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from pyrogram import Client, filters, enums
from pyrogram.errors import FloodWait, UserIsBlocked, MessageNotModified, PeerIdInvalid
from utils import get_size, is_subscribed, get_poster, search_gagala, temp, get_settings, save_group_settings
from database.users_chats_db import db
from database.ia_filterdb import Media, get_file_details, get_search_results
from database.filters_mdb import del_all, find_filter, get_filters
from database.gfilters_mdb import find_gfilter, get_gfilters
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
FILTER_MODE = {}
G_MODE = {}
SPELL_CHECK = {}
@Client.on_message(filters.command('autofilter') & filters.group & filters.create(admin_filter))
async def fil_mod(client, message):
mode_on = ["yes", "on", "true"]
mode_of = ["no", "off", "false"]
try:
args = message.text.split(None, 1)[1].lower()
except:
return await message.reply("**ɪɴᴄᴏᴍᴩʟᴇᴛᴇ ᴄᴏᴍᴍᴀɴᴅ...**")
m = await message.reply("**ꜱᴇᴛᴛɪɴɢ....**")
if args in mode_on:
FILTER_MODE[str(message.chat.id)] = "True"
await m.edit("**ᴀᴜᴛᴏꜰɪʟᴛᴇʀ ᴇɴᴀʙʟᴇᴅ**")
elif args in mode_of:
FILTER_MODE[str(message.chat.id)] = "False"
await m.edit("**ᴀᴜᴛᴏꜰɪʟᴛᴇʀ ᴅɪꜱᴀʙʟᴇᴅ**")
else:
await m.edit("ᴜꜱᴇ :- `/autofilter on` ᴏʀ `/autofilter off`")
@Client.on_message(filters.command('g_filter') & filters.group & filters.create(admin_filter))
async def g_fil_mod(client, message):
mode_on = ["yes", "on", "true"]
mode_of = ["no", "off", "false"]
try:
args = message.text.split(None, 1)[1].lower()
except:
return await message.reply("**ɪɴᴄᴏᴍᴩʟᴇᴛᴇ ᴄᴏᴍᴍᴀɴᴅ...**")
m = await message.reply("**ꜱᴇᴛᴛɪɴɢ...**")
if args in mode_on:
G_MODE[str(message.chat.id)] = "True"
await m.edit("**ɢʟᴏʙᴀʟ ꜰɪʟᴛᴇʀ ᴇɴᴀʙʟᴇᴅ**")
elif args in mode_of:
G_MODE[str(message.chat.id)] = "False"
await m.edit("**ɢʟᴏʙᴀʟ ꜰɪʟᴛᴇʀ ᴅɪꜱᴀʙʟᴇᴅ**")
else:
await m.edit("ᴜꜱᴇ :- `/g_filter on` ᴏʀ `/g_filter off`")
@Client.on_callback_query(filters.create(lambda _, __, query: query.data.startswith("next")))
async def next_page(bot, query):
ident, req, key, offset = query.data.split("_")
if int(req) not in [query.from_user.id, 0]:
return await query.answer(BUTTON_LOCK_TEXT.format(query.from_user.first_name), show_alert=True)
try: offset = int(offset)
except: offset = 0
search = temp.GP_BUTTONS.get(key)
if not search: return await query.answer("Yᴏᴜ Aʀᴇ Usɪɴɢ Oɴᴇ Oғ Mʏ Oʟᴅ Mᴇssᴀɢᴇs, Pʟᴇᴀsᴇ Sᴇɴᴅ Tʜᴇ Rᴇǫᴜᴇsᴛ Aɢᴀɪɴ", show_alert=True)
files, n_offset, total = await get_search_results(search, offset=offset, filter=True)
try: n_offset = int(n_offset)
except: n_offset = 0
if not files: return
settings = await get_settings(query.message.chat.id)
nxreq = query.from_user.id if query.from_user else 0
if SHORT_URL and SHORT_API:
if settings["button"]:
btn = [[InlineKeyboardButton(text=f"[{get_size(file.file_size)}] {file.file_name}", url=await get_shortlink(f"https://telegram.dog/{temp.U_NAME}?start=files_{file.file_id}"))] for file in files ]
else:
btn = [[InlineKeyboardButton(text=f"{file.file_name}", url=await get_shortlink(f"https://telegram.dog/{temp.U_NAME}?start=files_{file.file_id}")),
InlineKeyboardButton(text=f"{get_size(file.file_size)}", url=await get_shortlink(f"https://telegram.dog/{temp.U_NAME}?start=files_{file.file_id}"))] for file in files ]
else:
if settings["button"]:
btn = [[InlineKeyboardButton(text=f"[{get_size(file.file_size)}] {file.file_name}", callback_data=f'files#{nxreq}#{file.file_id}')] for file in files ]
else:
btn = [[InlineKeyboardButton(text=f"{file.file_name}", callback_data=f'files#{nxreq}#{file.file_id}'),
InlineKeyboardButton(text=f"{get_size(file.file_size)}", callback_data=f'files#{nxreq}#{file.file_id}')] for file in files ]
btn.insert(0, [InlineKeyboardButton("🔗 ʜᴏᴡ ᴛᴏ ᴅᴏᴡɴʟᴏᴀᴅ 🔗", "howdl")])
if 0 < offset <= 10:
off_set = 0
elif offset == 0:
off_set = None
else:
off_set = offset - 10
if n_offset == 0:
btn.append(
[InlineKeyboardButton("⬅️ ʙᴀᴄᴋ", callback_data=f"next_{req}_{key}_{off_set}"),
InlineKeyboardButton(f"❄️ ᴩᴀɢᴇꜱ {math.ceil(int(offset) / 10) + 1} / {math.ceil(total / 10)}", callback_data="pages")]
)
elif off_set is None:
btn.append(
[InlineKeyboardButton(f"❄️ {math.ceil(int(offset) / 10) + 1} / {math.ceil(total / 10)}", callback_data="pages"),
InlineKeyboardButton("ɴᴇxᴛ ➡️", callback_data=f"next_{req}_{key}_{n_offset}")])
else:
btn.append(
[
InlineKeyboardButton("⬅️ ʙᴀᴄᴋ", callback_data=f"next_{req}_{key}_{off_set}"),
InlineKeyboardButton(f"❄️ {math.ceil(int(offset) / 10) + 1} / {math.ceil(total / 10)}", callback_data="pages"),
InlineKeyboardButton("ɴᴇxᴛ ➡️", callback_data=f"next_{req}_{key}_{n_offset}")
],
)
try:
await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(btn))
except MessageNotModified:
pass
await query.answer()
@Client.on_callback_query(filters.create(lambda _, __, query: query.data.startswith("spolling")))
async def advantage_spoll_choker(bot, query):
_, user, movie_ = query.data.split('#')
if int(user) != 0 and query.from_user.id != int(user):
return await query.answer("okDa", show_alert=True)
if movie_ == "close_spellcheck":
return await query.message.delete()
movies = temp.GP_SPELL.get(query.message.reply_to_message.id)
if not movies:
return await query.answer("Yᴏᴜ Aʀᴇ Usɪɴɢ Oɴᴇ Oғ Mʏ Oʟᴅ Mᴇssᴀɢᴇs, Pʟᴇᴀsᴇ Sᴇɴᴅ Tʜᴇ Rᴇǫᴜᴇsᴛ Aɢᴀɪɴ", show_alert=True)
movie = movies[(int(movie_))]
await query.answer('Checking for Movie in database...')
k = await manual_filters(bot, query.message, text=movie)
if k == False:
files, offset, total_results = await get_search_results(movie, offset=0, filter=True)
if files:
k = (movie, files, offset, total_results)
await auto_filter(bot, query, k)
else:
k = await query.message.edit('This Movie Not Found In DataBase')
await asyncio.sleep(10)
await k.delete()
@Client.on_message(filters.group & filters.text & filters.incoming & filters.chat(AUTH_GROUPS) if AUTH_GROUPS else filters.text & filters.incoming & filters.group)
async def give_filter(client, message):
if G_FILTER:
if G_MODE.get(str(message.chat.id)) == "False":
return
else:
kd = await global_filters(client, message)
if kd == False:
k = await manual_filters(client, message)
if k == False:
if FILTER_MODE.get(str(message.chat.id)) == "False":
return
else:
await auto_filter(client, message)
else:
k = await manual_filters(client, message)
if k == False:
if FILTER_MODE.get(str(message.chat.id)) == "False":
return
else:
await auto_filter(client, message)
async def auto_filter(client, msg, spoll=False):
if not spoll:
message = msg
settings = await get_settings(message.chat.id)
if message.text.startswith("/"): return # ignore commands
if re.findall("((^\/|^,|^!|^\.|^[\U0001F600-\U000E007F]).*)", message.text):
return
if 2 < len(message.text) < 100:
search = message.text
files, offset, total_results = await get_search_results(search.lower(), offset=0, filter=True)
if not files:
if settings["spell_check"]:
return await advantage_spell_chok(msg)
else:
return
else:
return
else:
settings = await get_settings(msg.message.chat.id)
message = msg.message.reply_to_message # msg will be callback query
search, files, offset, total_results = spoll
pre = 'filep' if settings['file_secure'] else 'file'
req = message.from_user.id if message.from_user else 0
if SHORT_URL and SHORT_API:
if settings["button"]:
btn = [[InlineKeyboardButton(text=f"[{get_size(file.file_size)}] {file.file_name}", url=await get_shortlink(f"https://telegram.dog/{temp.U_NAME}?start=pre_{file.file_id}"))] for file in files ]
else:
btn = [[InlineKeyboardButton(text=f"{file.file_name}", url=await get_shortlink(f"https://telegram.dog/{temp.U_NAME}?start=pre_{file.file_id}")),
InlineKeyboardButton(text=f"{get_size(file.file_size)}", url=await get_shortlink(f"https://telegram.dog/{temp.U_NAME}?start=pre_{file.file_id}"))] for file in files ]
else:
if settings["button"]:
btn = [[InlineKeyboardButton(text=f"[{get_size(file.file_size)}] {file.file_name}", callback_data=f'{pre}#{req}#{file.file_id}')] for file in files ]
else:
btn = [[InlineKeyboardButton(text=f"{file.file_name}", callback_data=f'{pre}#{req}#{file.file_id}'),
InlineKeyboardButton(text=f"{get_size(file.file_size)}", callback_data=f'{pre}#{req}#{file.file_id}')] for file in files ]
btn.insert(0, [InlineKeyboardButton("🔗 ʜᴏᴡ ᴛᴏ ᴅᴏᴡɴʟᴏᴀᴅ 🔗", "howdl")])
if offset != "":
key = f"{message.chat.id}-{message.id}"
temp.GP_BUTTONS[key] = search
req = message.from_user.id if message.from_user else 0
btn.append(
[InlineKeyboardButton(text=f"❄️ ᴩᴀɢᴇꜱ 1/{math.ceil(int(total_results) / 6)}", callback_data="pages"),
InlineKeyboardButton(text="➡️ ɴᴇxᴛ", callback_data=f"next_{req}_{key}_{offset}")]
)
else:
btn.append(
[InlineKeyboardButton(text="❄️ ᴩᴀɢᴇꜱ 1/1", callback_data="pages")]
)
imdb = await get_poster(search, file=(files[0]).file_name) if settings["imdb"] else None
TEMPLATE = settings['template']
if imdb:
cap = TEMPLATE.format(
group = message.chat.title,
requested = message.from_user.mention,
query = search,
title = imdb['title'],
votes = imdb['votes'],
aka = imdb["aka"],
seasons = imdb["seasons"],
box_office = imdb['box_office'],
localized_title = imdb['localized_title'],
kind = imdb['kind'],
imdb_id = imdb["imdb_id"],
cast = imdb["cast"],
runtime = imdb["runtime"],
countries = imdb["countries"],
certificates = imdb["certificates"],
languages = imdb["languages"],
director = imdb["director"],
writer = imdb["writer"],
producer = imdb["producer"],
composer = imdb["composer"],
cinematographer = imdb["cinematographer"],
music_team = imdb["music_team"],
distributors = imdb["distributors"],
release_date = imdb['release_date'],
year = imdb['year'],
genres = imdb['genres'],
poster = imdb['poster'],
plot = imdb['plot'],
rating = imdb['rating'],
url = imdb['url'],
**locals()
)
else:
cap = f"Hᴇʀᴇ Is Wʜᴀᴛ I Fᴏᴜɴᴅ Fᴏʀ Yᴏᴜʀ Qᴜᴇʀʏ {search}"
if imdb and imdb.get('poster'):
try:
hehe = await message.reply_photo(photo=imdb.get('poster'), caption=cap, reply_markup=InlineKeyboardMarkup(btn))
await asyncio.sleep(IMDB_DELET_TIME)
await hehe.delete()
await message.delete()
except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty):
pic = imdb.get('poster')
poster = pic.replace('.jpg', "._V1_UX360.jpg")
hmm = await message.reply_photo(photo=poster, caption=cap, reply_markup=InlineKeyboardMarkup(btn))
await asyncio.sleep(IMDB_DELET_TIME)
await hmm.delete()
await message.delete()
except Exception as e:
logger.exception(e)
cdb = await message.reply_text(cap, reply_markup=InlineKeyboardMarkup(btn))
await asyncio.sleep(IMDB_DELET_TIME)
await cdb.delete()
await message.delete()
else:
crl = await message.reply_text(cap, reply_markup=InlineKeyboardMarkup(btn))
await asyncio.sleep(IMDB_DELET_TIME)
await crl.delete()
await message.delete()
if spoll:
await msg.message.delete()
async def advantage_spell_chok(msg):
query = re.sub(r"\b(pl(i|e)*?(s|z+|ease|se|ese|(e+)s(e)?)|((send|snd|giv(e)?|gib)(\sme)?)|movie(s)?|new|latest|br((o|u)h?)*|^h(e|a)?(l)*(o)*|mal(ayalam)?|t(h)?amil|file|that|find|und(o)*|kit(t(i|y)?)?o(w)?|thar(u)?(o)*w?|kittum(o)*|aya(k)*(um(o)*)?|full\smovie|any(one)|with\ssubtitle(s)?)","", msg.text, flags=re.IGNORECASE) # plis contribute some common words
query = query.strip() + " movie"
g_s = await search_gagala(query)
g_s += await search_gagala(msg.text)
gs_parsed = []
if not g_s:
k = await msg.reply("I Cᴏᴜʟᴅɴ'ᴛ Fɪɴᴅ Aɴʏ Mᴏᴠɪᴇ Iɴ Tʜᴀᴛ Nᴀᴍᴇ")
await asyncio.sleep(8)
return await k.delete()
regex = re.compile(r".*(imdb|wikipedia).*", re.IGNORECASE) # look for imdb / wiki results
gs = list(filter(regex.match, g_s))
gs_parsed = [re.sub(r'\b(\-([a-zA-Z-\s])\-\simdb|(\-\s)?imdb|(\-\s)?wikipedia|\(|\)|\-|reviews|full|all|episode(s)?|film|movie|series)', '', i, flags=re.IGNORECASE) for i in gs]
if not gs_parsed:
reg = re.compile(r"watch(\s[a-zA-Z0-9_\s\-\(\)]*)*\|.*", re.IGNORECASE) # match something like Watch Niram | Amazon Prime
for mv in g_s:
match = reg.match(mv)
if match:
gs_parsed.append(match.group(1))
user = msg.from_user.id if msg.from_user else 0
movielist = []
gs_parsed = list(dict.fromkeys(gs_parsed)) # removing duplicates https://stackoverflow.com/a/7961425
if len(gs_parsed) > 3:
gs_parsed = gs_parsed[:3]
if gs_parsed:
for mov in gs_parsed:
imdb_s = await get_poster(mov.strip(), bulk=True) # searching each keyword in imdb
if imdb_s:
movielist += [movie.get('title') for movie in imdb_s]
movielist += [(re.sub(r'(\-|\(|\)|_)', '', i, flags=re.IGNORECASE)).strip() for i in gs_parsed]
movielist = list(dict.fromkeys(movielist)) # removing duplicates
if not movielist:
k = await msg.reply("I Cᴏᴜʟᴅɴ'ᴛ Fɪɴᴅ Aɴʏᴛʜɪɴɢ Rᴇʟᴀᴛᴇᴅ Tᴏ Tʜᴀᴛ. Cʜᴇᴄᴋ Yᴏᴜʀ Sᴘᴇʟʟɪɴɢ")
await asyncio.sleep(8)
return await k.delete()
temp.GP_SPELL[msg.id] = movielist
btn = [[InlineKeyboardButton(text=movie.strip(), callback_data=f"spolling#{user}#{k}",)] for k, movie in enumerate(movielist)]
btn.append([InlineKeyboardButton(text="Close", callback_data=f'spolling#{user}#close_spellcheck')])
await msg.reply("I Cᴏᴜʟᴅɴ'ᴛ Fɪɴᴅ Aɴʏᴛʜɪɴɢ Rᴇʟᴀᴛᴇᴅ Tᴏ Tʜᴀᴛ. Dɪᴅ Yᴏᴜ Mᴇᴀɴ Aɴʏ Oɴᴇ Oғ Tʜᴇsᴇ?", reply_markup=InlineKeyboardMarkup(btn))
async def manual_filters(client, message, text=False):
group_id = message.chat.id
name = text or message.text
reply_id = message.reply_to_message.id if message.reply_to_message else message.id
keywords = await get_filters(group_id)
for keyword in reversed(sorted(keywords, key=len)):
pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])"
if re.search(pattern, name, flags=re.IGNORECASE):
reply_text, btn, alert, fileid = await find_filter(group_id, keyword)
if reply_text:
reply_text = reply_text.replace("\\n", "\n").replace("\\t", "\t")
if btn is not None:
try:
if fileid == "None":
if btn == "[]":
await client.send_message(group_id, reply_text, disable_web_page_preview=True, reply_to_message_id=reply_id)
else:
button = eval(btn)
await client.send_message(
group_id,
reply_text,
disable_web_page_preview=True,
reply_markup=InlineKeyboardMarkup(button),
reply_to_message_id=reply_id
)
elif btn == "[]":
await client.send_cached_media(
group_id,
fileid,
caption=reply_text or "",
reply_to_message_id=reply_id
)
else:
button = eval(btn)
await message.reply_cached_media(
fileid,
caption=reply_text or "",
reply_markup=InlineKeyboardMarkup(button),
reply_to_message_id=reply_id
)
except Exception as e:
logger.exception(e)
break
else:
return False
async def global_filters(client, message, text=False):
group_id = message.chat.id
name = text or message.text
reply_id = message.reply_to_message.id if message.reply_to_message else message.id
keywords = await get_gfilters('gfilters')
for keyword in reversed(sorted(keywords, key=len)):
pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])"
if re.search(pattern, name, flags=re.IGNORECASE):
reply_text, btn, alert, fileid = await find_gfilter('gfilters', keyword)
if reply_text:
reply_text = reply_text.replace("\\n", "\n").replace("\\t", "\t")
if btn is not None:
try:
if fileid == "None":
if btn == "[]":
knd3 = await client.send_message(
group_id,
reply_text,
disable_web_page_preview=True,
reply_to_message_id=reply_id
)
await asyncio.sleep(IMDB_DELET_TIME)
await knd3.delete()
await message.delete()
else:
button = eval(btn)
knd2 = await client.send_message(
group_id,
reply_text,
disable_web_page_preview=True,
reply_markup=InlineKeyboardMarkup(button),
reply_to_message_id=reply_id
)
await asyncio.sleep(IMDB_DELET_TIME)
await knd2.delete()
await message.delete()
elif btn == "[]":
knd1 = await client.send_cached_media(
group_id,
fileid,
caption=reply_text or "",
reply_to_message_id=reply_id
)
await asyncio.sleep(IMDB_DELET_TIME)
await knd1.delete()
await message.delete()
else:
button = eval(btn)
knd = await message.reply_cached_media(
fileid,
caption=reply_text or "",
reply_markup=InlineKeyboardMarkup(button),
reply_to_message_id=reply_id
)
await asyncio.sleep(IMDB_DELET_TIME)
await knd.delete()
await message.delete()
except Exception as e:
logger.exception(e)
break
else:
return False
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\index.py
import logging, re, asyncio
from pyrogram import Client, filters, enums
from pyrogram.errors import FloodWait
from pyrogram.errors.exceptions.bad_request_400 import ChannelInvalid, ChatAdminRequired, UsernameInvalid, UsernameNotModified
from info import CHANNELS, LOG_CHANNEL, ADMINS
from database.ia_filterdb import save_file
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from utils import temp
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
lock = asyncio.Lock()
@Client.on_message(filters.chat(CHANNELS) & (filters.document | filters.video | filters.audio))
async def media(bot, message):
for file_type in ("document", "video", "audio"):
media = getattr(message, file_type, None)
if media is not None: break
else: return
media.file_type = file_type
media.caption = message.caption
await save_file(media)
@Client.on_callback_query(filters.regex(r'^index'))
async def index_files(bot, query):
if query.data.startswith('index_cancel'):
temp.CANCEL = True
return await query.answer("Cᴀɴᴄᴇʟʟɪɴɢ Iɴᴅᴇxɪɴɢ", show_alert=True)
perfx, chat, lst_msg_id = query.data.split("#")
if lock.locked():
return await query.answer('Wᴀɪᴛ Uɴᴛɪʟ Pʀᴇᴠɪᴏᴜs Pʀᴏᴄᴇss Cᴏᴍᴘʟᴇᴛᴇ', show_alert=True)
msg = query.message
button = InlineKeyboardMarkup([[
InlineKeyboardButton('🚫 ᴄᴀɴᴄᴇʟʟ', "index_cancel")
]])
await msg.edit("ɪɴᴅᴇxɪɴɢ ɪs sᴛᴀʀᴛᴇᴅ ✨", reply_markup=button)
try: chat = int(chat)
except: chat = chat
await index_files_to_db(int(lst_msg_id), chat, msg, bot)
@Client.on_message((filters.forwarded | (filters.regex("(https://)?(t\.me/|telegram\.me/|telegram\.dog/)(c/)?(\d+|[a-zA-Z_0-9]+)/(\d+)$")) & filters.text ) & filters.private & filters.incoming & filters.user(ADMINS))
async def send_for_index(bot, message):
if message.text:
regex = re.compile("(https://)?(t\.me/|telegram\.me/|telegram\.dog/)(c/)?(\d+|[a-zA-Z_0-9]+)/(\d+)$")
match = regex.match(message.text)
if not match: return await message.reply('Invalid link')
chat_id = match.group(4)
last_msg_id = int(match.group(5))
if chat_id.isnumeric(): chat_id = int(("-100" + chat_id))
elif message.forward_from_chat.type == enums.ChatType.CHANNEL:
last_msg_id = message.forward_from_message_id
chat_id = message.forward_from_chat.username or message.forward_from_chat.id
else: return
try: await bot.get_chat(chat_id)
except ChannelInvalid: return await message.reply('This may be a private channel / group. Make me an admin over there to index the files.')
except (UsernameInvalid, UsernameNotModified): return await message.reply('Invalid Link specified.')
except Exception as e: return await message.reply(f'Errors - {e}')
try: k = await bot.get_messages(chat_id, last_msg_id)
except: return await message.reply('Make Sure That Iam An Admin In The Channel, if channel is private')
if k.empty: return await message.reply('This may be group and iam not a admin of the group.')
buttons = InlineKeyboardMarkup([[
InlineKeyboardButton('✨ ʏᴇꜱ', callback_data=f'index#{chat_id}#{last_msg_id}')
],[
InlineKeyboardButton('🚫 ᴄʟᴏꜱᴇ', callback_data='close_data')
]])
await message.reply(f'Do You Want To Index This Channel/ Group ?\n\nChat ID/ Username: {chat_id}
\nLast Message ID: {last_msg_id}
', reply_markup=buttons)
@Client.on_message(filters.command('setskip') & filters.user(ADMINS))
async def set_skip_number(bot, message):
if len(message.command) == 2:
try: skip = int(message.text.split(" ", 1)[1])
except: return await message.reply("Skip Number Should Be An Integer.")
await message.reply(f"Successfully Set Skip Number As {skip}")
temp.CURRENT = int(skip)
else:
await message.reply("Give Me A Skip Number")
async def index_files_to_db(lst_msg_id, chat, msg, bot):
total_files = 0
duplicate = 0
errors = 0
deleted = 0
no_media = 0
unsupported = 0
async with lock:
try:
current = temp.CURRENT
temp.CANCEL = False
async for message in bot.iter_messages(chat, lst_msg_id, temp.CURRENT):
if temp.CANCEL:
await msg.edit(f"Successfully Cancelled!!\n\nSaved {total_files}
files to dataBase!\nDuplicate Files Skipped: {duplicate}
\nDeleted Messages Skipped: {deleted}
\nNon-Media messages skipped: {no_media + unsupported}
(Unsupported Media - `{unsupported}` )\nErrors Occurred: {errors}
")
break
current += 1
if current % 100 == 0:
can = [[InlineKeyboardButton('Cancel', callback_data='index_cancel')]]
reply = InlineKeyboardMarkup(can)
try:
await msg.edit_text(text=f"Total Messages Fetched: {current}
\nTotal Messages Saved: {total_files}
\nDuplicate Files Skipped: {duplicate}
\nDeleted Messages Skipped: {deleted}
\nNon-Media messages skipped: {no_media + unsupported}
(Unsupported Media - `{unsupported}` )\nErrors Occurred: {errors}
", reply_markup=reply)
except FloodWait as t:
await asyncio.sleep(t.value)
await msg.edit_text(text=f"Total Messages Fetched: {current}
\nTotal Messages Saved: {total_files}
\nDuplicate Files Skipped: {duplicate}
\nDeleted Messages Skipped: {deleted}
\nNon-Media messages skipped: {no_media + unsupported}
(Unsupported Media - `{unsupported}` )\nErrors Occurred: {errors}
", reply_markup=reply)
if message.empty:
deleted += 1
continue
elif not message.media:
no_media += 1
continue
elif message.media not in [enums.MessageMediaType.VIDEO, enums.MessageMediaType.AUDIO, enums.MessageMediaType.DOCUMENT]:
unsupported += 1
continue
media = getattr(message, message.media.value, None)
if not media:
unsupported += 1
continue
media.file_type = message.media.value
media.caption = message.caption
aynav, vnay = await save_file(media)
if aynav:
total_files += 1
elif vnay == 0:
duplicate += 1
elif vnay == 2:
errors += 1
except Exception as e:
logger.exception(e)
await msg.edit(f'Error: {e}')
else:
await msg.edit(f'Succesfully Saved {total_files}
To Database!\nDuplicate Files Skipped: {duplicate}
\nDeleted Messages Skipped: {deleted}
\nNon-Media Messages Skipped: {no_media + unsupported}
(Unsupported Media - `{unsupported}` )\nErrors Occurred: {errors}
')
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\inline.py
import logging
from pyrogram import Client, emoji, filters
from pyrogram.errors.exceptions.bad_request_400 import QueryIdInvalid
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, InlineQueryResultCachedDocument, InlineQuery
from database.ia_filterdb import get_search_results
from utils import is_subscribed, get_size, temp
from info import CACHE_TIME, AUTH_USERS, AUTH_CHANNEL, CUSTOM_FILE_CAPTION
logger = logging.getLogger(__name__)
cache_time = 0 if AUTH_USERS or AUTH_CHANNEL else CACHE_TIME
async def inline_users(query: InlineQuery):
if AUTH_USERS:
if query.from_user and query.from_user.id in AUTH_USERS:
return True
else:
return False
if query.from_user and query.from_user.id not in temp.BANNED_USERS:
return True
return False
@Client.on_inline_query()
async def answer(bot, query):
if not await inline_users(query):
await query.answer(results=[],
cache_time=0,
switch_pm_text='okDa',
switch_pm_parameter="hehe")
return
if AUTH_CHANNEL and not await is_subscribed(bot, query):
await query.answer(results=[],
cache_time=0,
switch_pm_text='You have to subscribe my channel to use the bot',
switch_pm_parameter="subscribe")
return
results = []
if '|' in query.query:
string, file_type = query.query.split('|', maxsplit=1)
string = string.strip()
file_type = file_type.strip().lower()
else:
string = query.query.strip()
file_type = None
offset = int(query.offset or 0)
reply_markup = get_reply_markup(query=string)
files, next_offset, total = await get_search_results(string, file_type=file_type, max_results=10, offset=offset)
for file in files:
title=file.file_name
size=get_size(file.file_size)
f_caption=file.caption
if CUSTOM_FILE_CAPTION:
try:
f_caption=CUSTOM_FILE_CAPTION.format(mention=query.from_user.mention, file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='' if f_caption is None else f_caption)
except Exception as e:
logger.exception(e)
f_caption=f_caption
if f_caption is None:
f_caption = f"{file.file_name}"
results.append(
InlineQueryResultCachedDocument(
title=file.file_name,
document_file_id=file.file_id,
caption=f_caption,
description=f'Size: {get_size(file.file_size)}\nType: {file.file_type}',
reply_markup=reply_markup))
if results:
switch_pm_text = f"{emoji.FILE_FOLDER} Results - {total}"
if string:
switch_pm_text += f" for {string}"
try:
await query.answer(results=results,
is_personal = True,
cache_time=cache_time,
switch_pm_text=switch_pm_text,
switch_pm_parameter="start",
next_offset=str(next_offset))
except QueryIdInvalid:
pass
except Exception as e:
logging.exception(str(e))
else:
switch_pm_text = f'{emoji.CROSS_MARK} No Results'
if string:
switch_pm_text += f' for "{string}"'
await query.answer(results=[],
is_personal = True,
cache_time=cache_time,
switch_pm_text=switch_pm_text,
switch_pm_parameter="okay")
def get_reply_markup(query):
buttons = [[InlineKeyboardButton('⟳ ꜱᴇᴀʀᴄʜ ᴀɢᴀɪɴ', switch_inline_query_current_chat=query)]]
return InlineKeyboardMarkup(buttons)
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\pm_filter.py
import asyncio, re, ast, math, logging, pyrogram
from pyrogram.errors.exceptions.bad_request_400 import MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty
from Script import script
from utils import get_shortlink
from info import AUTH_USERS, PM_IMDB, SINGLE_BUTTON, PROTECT_CONTENT, SPELL_CHECK_REPLY, IMDB_TEMPLATE, IMDB_DELET_TIME, PMFILTER, G_FILTER, SHORT_URL, SHORT_API
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from pyrogram import Client, filters, enums
from pyrogram.errors import FloodWait, UserIsBlocked, MessageNotModified, PeerIdInvalid
from utils import get_size, is_subscribed, get_poster, search_gagala, temp, get_settings, save_group_settings
from database.users_chats_db import db
from database.ia_filterdb import Media, get_file_details, get_search_results
from plugins.group_filter import global_filters
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
@Client.on_message(filters.private & filters.text & filters.chat(AUTH_USERS) if AUTH_USERS else filters.text & filters.private)
async def auto_pm_fill(b, m):
if PMFILTER:
if G_FILTER:
kd = await global_filters(b, m)
if kd == False: await pm_AutoFilter(b, m)
else: await pm_AutoFilter(b, m)
else: return
@Client.on_callback_query(filters.create(lambda _, __, query: query.data.startswith("pmnext")))
async def pm_next_page(bot, query):
ident, req, key, offset = query.data.split("_")
try: offset = int(offset)
except: offset = 0
search = temp.PM_BUTTONS.get(str(key))
if not search: return await query.answer("Yᴏᴜ Aʀᴇ Usɪɴɢ Oɴᴇ Oғ Mʏ Oʟᴅ Mᴇssᴀɢᴇs, Pʟᴇᴀsᴇ Sᴇɴᴅ Tʜᴇ Rᴇǫᴜᴇsᴛ Aɢᴀɪɴ", show_alert=True)
files, n_offset, total = await get_search_results(search.lower(), offset=offset, filter=True)
try: n_offset = int(n_offset)
except: n_offset = 0
if not files: return
if SHORT_URL and SHORT_API:
if SINGLE_BUTTON:
btn = [[InlineKeyboardButton(text=f"[{get_size(file.file_size)}] {file.file_name}", url=await get_shortlink(f"https://telegram.dog/{temp.U_NAME}?start=files_{file.file_id}"))] for file in files ]
else:
btn = [[InlineKeyboardButton(text=f"{file.file_name}", url=await get_shortlink(f"https://telegram.dog/{temp.U_NAME}?start=files_{file.file_id}")),
InlineKeyboardButton(text=f"{get_size(file.file_size)}", url=await get_shortlink(f"https://telegram.dog/{temp.U_NAME}?start=files_{file.file_id}"))] for file in files ]
else:
if SINGLE_BUTTON:
btn = [[InlineKeyboardButton(text=f"[{get_size(file.file_size)}] {file.file_name}", callback_data=f'pmfile#{file.file_id}')] for file in files ]
else:
btn = [[InlineKeyboardButton(text=f"{file.file_name}", callback_data=f'pmfile#{file.file_id}'),
InlineKeyboardButton(text=f"{get_size(file.file_size)}", callback_data=f'pmfile#{file.file_id}')] for file in files ]
btn.insert(0, [InlineKeyboardButton("🔗 ʜᴏᴡ ᴛᴏ ᴅᴏᴡɴʟᴏᴀᴅ 🔗", "howdl")])
if 0 < offset <= 10: off_set = 0
elif offset == 0: off_set = None
else: off_set = offset - 10
if n_offset == 0:
btn.append(
[InlineKeyboardButton("⬅️ ʙᴀᴄᴋ", callback_data=f"pmnext_{req}_{key}_{off_set}"),
InlineKeyboardButton(f"❄️ ᴩᴀɢᴇꜱ {math.ceil(int(offset) / 10) + 1} / {math.ceil(total / 10)}", callback_data="pages")]
)
elif off_set is None:
btn.append(
[InlineKeyboardButton(f"❄️ {math.ceil(int(offset) / 10) + 1} / {math.ceil(total / 10)}", callback_data="pages"),
InlineKeyboardButton("ɴᴇxᴛ ➡️", callback_data=f"pmnext_{req}_{key}_{n_offset}")])
else:
btn.append([
InlineKeyboardButton("⬅️ ʙᴀᴄᴋ", callback_data=f"pmnext_{req}_{key}_{off_set}"),
InlineKeyboardButton(f"❄️ {math.ceil(int(offset) / 10) + 1} / {math.ceil(total / 10)}", callback_data="pages"),
InlineKeyboardButton("ɴᴇxᴛ ➡️", callback_data=f"pmnext_{req}_{key}_{n_offset}")
])
try:
await query.edit_message_reply_markup(reply_markup=InlineKeyboardMarkup(btn))
except MessageNotModified:
pass
await query.answer()
@Client.on_callback_query(filters.create(lambda _, __, query: query.data.startswith("pmspolling")))
async def pm_spoll_tester(bot, query):
_, user, movie_ = query.data.split('#')
if movie_ == "close_spellcheck":
return await query.message.delete()
movies = temp.PM_SPELL.get(str(query.message.reply_to_message.id))
if not movies:
return await query.answer("Yᴏᴜ Aʀᴇ Usɪɴɢ Oɴᴇ Oғ Mʏ Oʟᴅ Mᴇssᴀɢᴇs, Pʟᴇᴀsᴇ Sᴇɴᴅ Tʜᴇ Rᴇǫᴜᴇsᴛ Aɢᴀɪɴ", show_alert=True)
movie = movies[(int(movie_))]
await query.answer('Cʜᴇᴄᴋɪɴɢ Fᴏʀ Mᴏᴠɪᴇ Iɴ Dᴀᴛᴀʙᴀsᴇ...')
files, offset, total_results = await get_search_results(movie, offset=0, filter=True)
if files:
k = (movie, files, offset, total_results)
await pm_AutoFilter(bot, query, k)
else:
k = await query.message.edit('Tʜɪs Mᴏᴠɪᴇ Nᴏᴛ Fᴏᴜɴᴅ Iɴ Dᴀᴛᴀʙᴀsᴇ')
await asyncio.sleep(10)
await k.delete()
async def pm_AutoFilter(client, msg, pmspoll=False):
if not pmspoll:
message = msg
if message.text.startswith("/"): return # ignore commands
if re.findall("((^\/|^,|^!|^\.|^[\U0001F600-\U000E007F]).*)", message.text): return
if 2 < len(message.text) < 100:
search = message.text
files, offset, total_results = await get_search_results(search.lower(), offset=0, filter=True)
if not files: return await pm_spoll_choker(msg)
else: return
else:
message = msg.message.reply_to_message # msg will be callback query
search, files, offset, total_results = pmspoll
pre = 'pmfilep' if PROTECT_CONTENT else 'pmfile'
if SHORT_URL and SHORT_API:
if SINGLE_BUTTON:
btn = [[InlineKeyboardButton(text=f"[{get_size(file.file_size)}] {file.file_name}", url=await get_shortlink(f"https://telegram.dog/{temp.U_NAME}?start=pre_{file.file_id}"))] for file in files ]
else:
btn = [[InlineKeyboardButton(text=f"{file.file_name}", url=await get_shortlink(f"https://telegram.dog/{temp.U_NAME}?start=pre_{file.file_id}")),
InlineKeyboardButton(text=f"{get_size(file.file_size)}", url=await get_shortlink(f"https://telegram.dog/{temp.U_NAME}?start=pre_{file.file_id}"))] for file in files ]
else:
if SINGLE_BUTTON:
btn = [[InlineKeyboardButton(text=f"[{get_size(file.file_size)}] {file.file_name}", callback_data=f'{pre}#{file.file_id}')] for file in files ]
else:
btn = [[InlineKeyboardButton(text=f"{file.file_name}", callback_data=f'{pre}#{req}#{file.file_id}'),
InlineKeyboardButton(text=f"{get_size(file.file_size)}", callback_data=f'{pre}#{file.file_id}')] for file in files ]
btn.insert(0, [InlineKeyboardButton("🔗 ʜᴏᴡ ᴛᴏ ᴅᴏᴡɴʟᴏᴀᴅ 🔗", "howdl")])
if offset != "":
key = f"{message.id}"
temp.PM_BUTTONS[key] = search
req = message.from_user.id if message.from_user else 0
btn.append(
[InlineKeyboardButton(text=f"❄️ ᴩᴀɢᴇꜱ 1/{math.ceil(int(total_results) / 6)}", callback_data="pages"),
InlineKeyboardButton(text="ɴᴇxᴛ ➡️", callback_data=f"pmnext_{req}_{key}_{offset}")]
)
else:
btn.append(
[InlineKeyboardButton(text="❄️ ᴩᴀɢᴇꜱ 1/1", callback_data="pages")]
)
if PM_IMDB:
imdb = await get_poster(search)
else:
imdb = None
TEMPLATE = IMDB_TEMPLATE
if imdb:
cap = TEMPLATE.format(
group = message.chat.title,
requested = message.from_user.mention,
query = search,
title = imdb['title'],
votes = imdb['votes'],
aka = imdb["aka"],
seasons = imdb["seasons"],
box_office = imdb['box_office'],
localized_title = imdb['localized_title'],
kind = imdb['kind'],
imdb_id = imdb["imdb_id"],
cast = imdb["cast"],
runtime = imdb["runtime"],
countries = imdb["countries"],
certificates = imdb["certificates"],
languages = imdb["languages"],
director = imdb["director"],
writer = imdb["writer"],
producer = imdb["producer"],
composer = imdb["composer"],
cinematographer = imdb["cinematographer"],
music_team = imdb["music_team"],
distributors = imdb["distributors"],
release_date = imdb['release_date'],
year = imdb['year'],
genres = imdb['genres'],
poster = imdb['poster'],
plot = imdb['plot'],
rating = imdb['rating'],
url = imdb['url'],
**locals()
)
else:
cap = f"Hᴇʀᴇ Is Wʜᴀᴛ I Fᴏᴜɴᴅ Fᴏʀ Yᴏᴜʀ Qᴜᴇʀʏ {search}"
if imdb and imdb.get('poster'):
try:
hehe = await message.reply_photo(photo=imdb.get('poster'), caption=cap, quote=True, reply_markup=InlineKeyboardMarkup(btn))
await asyncio.sleep(IMDB_DELET_TIME)
await hehe.delete()
except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty):
pic = imdb.get('poster')
poster = pic.replace('.jpg', "._V1_UX360.jpg")
hmm = await message.reply_photo(photo=poster, caption=cap, quote=True, reply_markup=InlineKeyboardMarkup(btn))
await asyncio.sleep(IMDB_DELET_TIME)
await hmm.delete()
except Exception as e:
logger.exception(e)
cdp = await message.reply_text(cap, quote=True, reply_markup=InlineKeyboardMarkup(btn))
await asyncio.sleep(IMDB_DELET_TIME)
await cdp.delete()
else:
abc = await message.reply_text(cap, quote=True, reply_markup=InlineKeyboardMarkup(btn))
await asyncio.sleep(IMDB_DELET_TIME)
await abc.delete()
if pmspoll:
await msg.message.delete()
async def pm_spoll_choker(msg):
query = re.sub(r"\b(pl(i|e)*?(s|z+|ease|se|ese|(e+)s(e)?)|((send|snd|giv(e)?|gib)(\sme)?)|movie(s)?|new|latest|br((o|u)h?)*|^h(e|a)?(l)*(o)*|mal(ayalam)?|t(h)?amil|file|that|find|und(o)*|kit(t(i|y)?)?o(w)?|thar(u)?(o)*w?|kittum(o)*|aya(k)*(um(o)*)?|full\smovie|any(one)|with\ssubtitle(s)?)", "", msg.text, flags=re.IGNORECASE) # plis contribute some common words
query = query.strip() + " movie"
g_s = await search_gagala(query)
g_s += await search_gagala(msg.text)
gs_parsed = []
if not g_s:
k = await msg.reply("I Cᴏᴜʟᴅɴ'ᴛ Fɪɴᴅ Aɴʏ Mᴏᴠɪᴇ Iɴ Tʜᴀᴛ Nᴀᴍᴇ", quote=True)
await asyncio.sleep(10)
return await k.delete()
regex = re.compile(r".*(imdb|wikipedia).*", re.IGNORECASE) # look for imdb / wiki results
gs = list(filter(regex.match, g_s))
gs_parsed = [re.sub(r'\b(\-([a-zA-Z-\s])\-\simdb|(\-\s)?imdb|(\-\s)?wikipedia|\(|\)|\-|reviews|full|all|episode(s)?|film|movie|series)', '', i, flags=re.IGNORECASE) for i in gs]
if not gs_parsed:
reg = re.compile(r"watch(\s[a-zA-Z0-9_\s\-\(\)]*)*\|.*", re.IGNORECASE) # match something like Watch Niram | Amazon Prime
for mv in g_s:
match = reg.match(mv)
if match: gs_parsed.append(match.group(1))
user = msg.from_user.id if msg.from_user else 0
movielist = []
gs_parsed = list(dict.fromkeys(gs_parsed)) # removing duplicates https://stackoverflow.com/a/7961425
if len(gs_parsed) > 3: gs_parsed = gs_parsed[:3]
if gs_parsed:
for mov in gs_parsed:
imdb_s = await get_poster(mov.strip(), bulk=True) # searching each keyword in imdb
if imdb_s: movielist += [movie.get('title') for movie in imdb_s]
movielist += [(re.sub(r'(\-|\(|\)|_)', '', i, flags=re.IGNORECASE)).strip() for i in gs_parsed]
movielist = list(dict.fromkeys(movielist)) # removing duplicates
if not movielist:
k = await msg.reply("I Cᴏᴜʟᴅɴ'ᴛ Fɪɴᴅ Aɴʏᴛʜɪɴɢ Rᴇʟᴀᴛᴇᴅ Tᴏ Tʜᴀᴛ. Cʜᴇᴄᴋ Yᴏᴜʀ Sᴘᴇʟʟɪɴɢ", quote=True)
await asyncio.sleep(10)
return await k.delete()
temp.PM_SPELL[str(msg.id)] = movielist
btn = [[InlineKeyboardButton(text=movie.strip(), callback_data=f"pmspolling#{user}#{k}")] for k, movie in enumerate(movielist)]
btn.append([InlineKeyboardButton(text="Close", callback_data=f'pmspolling#{user}#close_spellcheck')])
await msg.reply("I Cᴏᴜʟᴅɴ'ᴛ Fɪɴᴅ Aɴʏᴛʜɪɴɢ Rᴇʟᴀᴛᴇᴅ Tᴏ Tʜᴀᴛ. Dɪᴅ Yᴏᴜ Mᴇᴀɴ Aɴʏ Oɴᴇ Oғ Tʜᴇsᴇ?", reply_markup=InlineKeyboardMarkup(btn), quote=True)
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\query.py
import asyncio, re, ast, time, math, logging, random, pyrogram, shutil, psutil
# Pyrogram Functions
from pyrogram.errors.exceptions.bad_request_400 import MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery, InputMediaPhoto
from pyrogram import Client, filters, enums
from pyrogram.errors import FloodWait, UserIsBlocked, MessageNotModified, PeerIdInvalid
# Helper Function
from Script import script
from utils import get_size, is_subscribed, get_poster, search_gagala, temp, get_settings, save_group_settings, get_shortlink, get_time, humanbytes
from .ExtraMods.carbon import make_carbon
# Database Function
from database.connections_mdb import active_connection, all_connections, delete_connection, if_active, make_active, make_inactive
from database.ia_filterdb import Media, get_file_details, get_search_results
from database.filters_mdb import del_all, find_filter, get_filters
from database.gfilters_mdb import find_gfilter, get_gfilters
from database.users_chats_db import db
# Image Editor Function
from image.edit_1 import bright, mix, black_white, g_blur, normal_blur, box_blur
from image.edit_2 import circle_with_bg, circle_without_bg, sticker, edge_curved, contrast, sepia_mode, pencil, cartoon
from image.edit_3 import green_border, blue_border, black_border, red_border
from image.edit_4 import rotate_90, rotate_180, rotate_270, inverted, round_sticker, removebg_white, removebg_plain, removebg_sticker
from image.edit_5 import normalglitch_1, normalglitch_2, normalglitch_3, normalglitch_4, normalglitch_5, scanlineglitch_1, scanlineglitch_2, scanlineglitch_3, scanlineglitch_4, scanlineglitch_5
# Configuration
from info import ADMINS, AUTH_CHANNEL, AUTH_USERS, CUSTOM_FILE_CAPTION, AUTH_GROUPS, P_TTI_SHOW_OFF, PICS, IMDB, PM_IMDB, SINGLE_BUTTON, PROTECT_CONTENT, \
SPELL_CHECK_REPLY, IMDB_TEMPLATE, IMDB_DELET_TIME, START_MESSAGE, PMFILTER, G_FILTER, BUTTON_LOCK, BUTTON_LOCK_TEXT, SHORT_URL, SHORT_API
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
@Client.on_callback_query()
async def cb_handler(client: Client, query: CallbackQuery):
if query.data == "close_data":
await query.message.delete()
elif query.data == "delallconfirm":
userid = query.from_user.id
chat_type = query.message.chat.type
if chat_type == enums.ChatType.PRIVATE:
grpid = await active_connection(str(userid))
if grpid is not None:
grp_id = grpid
try:
chat = await client.get_chat(grpid)
title = chat.title
except:
return await query.message.edit_text("Make Sure I'm Present In Your Group!!", quote=True)
else:
return await query.message.edit_text("I'm Not Connected To Any Groups!\ncheck /Connections Or Connect To Any Groups", quote=True)
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
grp_id = query.message.chat.id
title = query.message.chat.title
else: return
st = await client.get_chat_member(grp_id, userid)
if (st.status == enums.ChatMemberStatus.OWNER) or (str(userid) in ADMINS): await del_all(query.message, grp_id, title)
else: await query.answer("You Need To Be Group Owner Or An Auth User To Do That!", show_alert=True)
elif query.data == "delallcancel":
userid = query.from_user.id
chat_type = query.message.chat.type
if chat_type == enums.ChatType.PRIVATE:
await query.message.reply_to_message.delete()
await query.message.delete()
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
grp_id = query.message.chat.id
st = await client.get_chat_member(grp_id, userid)
if (st.status == enums.ChatMemberStatus.OWNER) or (str(userid) in ADMINS):
await query.message.delete()
try: await query.message.reply_to_message.delete()
except: pass
else: await query.answer("Buddy Don't Touch Others Property 😁", show_alert=True)
elif "groupcb" in query.data:
group_id = query.data.split(":")[1]
act = query.data.split(":")[2]
hr = await client.get_chat(int(group_id))
title = hr.title
user_id = query.from_user.id
if act == "":
stat = "Connect"
cb = "connectcb"
else:
stat = "Disconnect"
cb = "disconnect"
keyboard = InlineKeyboardMarkup([[
InlineKeyboardButton(f"{stat}", callback_data=f"{cb}:{group_id}"),
InlineKeyboardButton("Delete", callback_data=f"deletecb:{group_id}")
],[
InlineKeyboardButton("Back", callback_data="backcb")]
])
await query.message.edit_text(f"Group Name:- **{title}**\nGroup Id:- `{group_id}`", reply_markup=keyboard, parse_mode=enums.ParseMode.MARKDOWN)
elif "connectcb" in query.data:
group_id = query.data.split(":")[1]
hr = await client.get_chat(int(group_id))
title = hr.title
user_id = query.from_user.id
mkact = await make_active(str(user_id), str(group_id))
if mkact: await query.message.edit_text(f"Connected To: **{title}**", parse_mode=enums.ParseMode.MARKDOWN,)
else: await query.message.edit_text('Some Error Occurred!!', parse_mode="md")
elif "disconnect" in query.data:
group_id = query.data.split(":")[1]
hr = await client.get_chat(int(group_id))
title = hr.title
user_id = query.from_user.id
mkinact = await make_inactive(str(user_id))
if mkinact: await query.message.edit_text(f"Disconnected From **{title}**", parse_mode=enums.ParseMode.MARKDOWN)
else: await query.message.edit_text(f"Some Error Occurred!!", parse_mode=enums.ParseMode.MARKDOWN)
elif "deletecb" in query.data:
user_id = query.from_user.id
group_id = query.data.split(":")[1]
delcon = await delete_connection(str(user_id), str(group_id))
if delcon: await query.message.edit_text("Successfully Deleted Connection")
else: await query.message.edit_text(f"Some Error Occurred!!", parse_mode=enums.ParseMode.MARKDOWN)
elif query.data == "backcb":
userid = query.from_user.id
groupids = await all_connections(str(userid))
if groupids is None:
return await query.message.edit_text("There Are No Active Connections!! Connect To Some Groups First.")
buttons = []
for groupid in groupids:
try:
ttl = await client.get_chat(int(groupid))
title = ttl.title
active = await if_active(str(userid), str(groupid))
act = " - ACTIVE" if active else ""
buttons.append([InlineKeyboardButton(f"{title}{act}", callback_data=f"groupcb:{groupid}:{act}")])
except: pass
if buttons: await query.message.edit_text("Your Connected Group Details ;\n\n", reply_markup=InlineKeyboardMarkup(buttons))
elif "alertmessage" in query.data:
grp_id = query.message.chat.id
i = query.data.split(":")[1]
keyword = query.data.split(":")[2]
reply_text, btn, alerts, fileid = await find_filter(grp_id, keyword)
if alerts is not None:
alerts = ast.literal_eval(alerts)
alert = alerts[int(i)]
alert = alert.replace("\\n", "\n").replace("\\t", "\t")
await query.answer(alert, show_alert=True)
elif "galert" in query.data:
i = query.data.split(":")[1]
keyword = query.data.split(":")[2]
reply_text, btn, alerts, fileid = await find_gfilter("gfilters", keyword)
if alerts is not None:
alerts = ast.literal_eval(alerts)
alert = alerts[int(i)]
alert = alert.replace("\\n", "\n").replace("\\t", "\t")
await query.answer(alert, show_alert=True)
if query.data.startswith("pmfile"):
ident, file_id = query.data.split("#")
files_ = await get_file_details(file_id)
if not files_: return await query.answer('No Such File Exist.')
files = files_[0]
title = files.file_name
size = get_size(files.file_size)
f_caption = f_caption = f"{title}"
if CUSTOM_FILE_CAPTION:
try: f_caption = CUSTOM_FILE_CAPTION.format(mention=query.from_user.mention, file_name='' if title is None else title, file_size='' if size is None else size, file_caption='' if f_caption is None else f_caption)
except Exception as e: logger.exception(e)
try:
if AUTH_CHANNEL and not await is_subscribed(client, query):
return await query.answer(url=f"https://t.me/{temp.U_NAME}?start={ident}_{file_id}")
else:
await client.send_cached_media(chat_id=query.from_user.id, file_id=file_id, caption=f_caption, protect_content=True if ident == "pmfilep" else False)
except Exception as e:
await query.answer(f"⚠️ Eʀʀᴏʀ {e}", show_alert=True)
if query.data.startswith("file"):
ident, req, file_id = query.data.split("#")
if BUTTON_LOCK:
if int(req) not in [query.from_user.id, 0]:
return await query.answer(BUTTON_LOCK_TEXT.format(query=query.from_user.first_name), show_alert=True)
files_ = await get_file_details(file_id)
if not files_: return await query.answer('No Such File Exist.')
files = files_[0]
title = files.file_name
size = get_size(files.file_size)
f_caption = f_caption = f"{title}"
settings = await get_settings(query.message.chat.id)
if CUSTOM_FILE_CAPTION:
try: f_caption = CUSTOM_FILE_CAPTION.format(mention=query.from_user.mention, file_name='' if title is None else title, file_size='' if size is None else size, file_caption='' if f_caption is None else f_caption)
except Exception as e: logger.exception(e)
try:
if AUTH_CHANNEL and not await is_subscribed(client, query):
return await query.answer(url=f"https://t.me/{temp.U_NAME}?start={ident}_{file_id}")
elif settings['botpm']:
return await query.answer(url=f"https://t.me/{temp.U_NAME}?start={ident}_{file_id}")
else:
await client.send_cached_media(chat_id=query.from_user.id, file_id=file_id, caption=f_caption, protect_content=True if ident == "filep" else False)
await query.answer('Cʜᴇᴄᴋ PM, I Hᴀᴠᴇ Sᴇɴᴛ Fɪʟᴇs Iɴ Pᴍ', show_alert=True)
except UserIsBlocked:
await query.answer('Uɴʙʟᴏᴄᴋ Tʜᴇ Bᴏᴛ Mᴀʜɴ !', show_alert=True)
except PeerIdInvalid:
await query.answer(url=f"https://t.me/{temp.U_NAME}?start={ident}_{file_id}")
except Exception as e:
await query.answer(url=f"https://t.me/{temp.U_NAME}?start={ident}_{file_id}")
elif query.data.startswith("checksub"):
if AUTH_CHANNEL and not await is_subscribed(client, query):
return await query.answer("I Lɪᴋᴇ Yᴏᴜʀ Sᴍᴀʀᴛɴᴇss, Bᴜᴛ Dᴏɴ'ᴛ Bᴇ Oᴠᴇʀsᴍᴀʀᴛ Oᴋᴀʏ 😏", show_alert=True)
ident, file_id = query.data.split("#")
files_ = await get_file_details(file_id)
if not files_: return await query.answer('NO SUCH FILE EXIST....')
files = files_[0]
title = files.file_name
size = get_size(files.file_size)
f_caption = f_caption = f"{title}"
if CUSTOM_FILE_CAPTION:
try: f_caption = CUSTOM_FILE_CAPTION.format(mention=query.from_user.mention, file_name='' if title is None else title, file_size='' if size is None else size, file_caption='' if f_caption is None else f_caption)
except Exception as e: logger.exception(e)
await client.send_cached_media(chat_id=query.from_user.id, file_id=file_id, caption=f_caption, protect_content=True if ident == 'checksubp' else False)
elif query.data == "removebg":
buttons = [[
InlineKeyboardButton(text="𝖶𝗂𝗍𝗁 𝖶𝗁𝗂𝗍𝖾 𝖡𝖦", callback_data="rmbgwhite"),
InlineKeyboardButton(text="𝖶𝗂𝗍𝗁𝗈𝗎𝗍 𝖡𝖦", callback_data="rmbgplain"),
],[
InlineKeyboardButton(text="𝖲𝗍𝗂𝖼𝗄𝖾𝗋", callback_data="rmbgsticker"),
],[
InlineKeyboardButton('𝙱𝙰𝙲𝙺', callback_data='photo')
]]
await query.message.edit_text("**Select Required Mode**", reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "stick":
buttons = [[
InlineKeyboardButton(text="𝖭𝗈𝗋𝗆𝖺𝗅", callback_data="stkr"),
InlineKeyboardButton(text="𝖤𝖽𝗀𝖾 𝖢𝗎𝗋𝗏𝖾𝖽", callback_data="cur_ved"),
],[
InlineKeyboardButton(text="𝖢𝗂𝗋𝖼𝗅𝖾", callback_data="circle_sticker")
],[
InlineKeyboardButton('𝙱𝙰𝙲𝙺', callback_data='photo')
]]
await query.message.edit("**Select A Type**", reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "rotate":
buttons = [[
InlineKeyboardButton(text="180", callback_data="180"),
InlineKeyboardButton(text="90", callback_data="90")
],[
InlineKeyboardButton(text="270", callback_data="270")
],[
InlineKeyboardButton('𝙱𝙰𝙲𝙺', callback_data='photo')
]]
await query.message.edit_text("**Select The Degree**", reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "glitch":
buttons = [[
InlineKeyboardButton(text="𝖭𝗈𝗋𝗆𝖺𝗅", callback_data="normalglitch"),
InlineKeyboardButton(text="𝖲𝖼𝖺𝗇 𝖫𝖺𝗂𝗇𝗌", callback_data="scanlineglitch")
],[
InlineKeyboardButton('𝙱𝙰𝙲𝙺', callback_data='photo')
]]
await query.message.edit_text("**Select Required Mode**", reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "normalglitch":
buttons = [[
InlineKeyboardButton(text="1", callback_data="normalglitch1"),
InlineKeyboardButton(text="2", callback_data="normalglitch2"),
InlineKeyboardButton(text="3", callback_data="normalglitch3"),
],[
InlineKeyboardButton(text="4", callback_data="normalglitch4"),
InlineKeyboardButton(text="5", callback_data="normalglitch5"),
],[
InlineKeyboardButton('𝙱𝙰𝙲𝙺', callback_data='glitch')
]]
await query.message.edit_text(text="**Select Glitch Power Level**", reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "scanlineglitch":
buttons = [[
InlineKeyboardButton(text="1", callback_data="scanlineglitch1"),
InlineKeyboardButton(text="2", callback_data="scanlineglitch2"),
InlineKeyboardButton(text="3", callback_data="scanlineglitch3"),
],[
InlineKeyboardButton(text="4", callback_data="scanlineglitch4"),
InlineKeyboardButton(text="5", callback_data="scanlineglitch5"),
],[
InlineKeyboardButton('𝙱𝙰𝙲𝙺', callback_data='glitch')
]]
await query.message.edit_text("**Select Glitch Power Level**", reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "blur":
buttons = [[
InlineKeyboardButton(text="𝖡𝗈𝗑", callback_data="box"),
InlineKeyboardButton(text="𝖭𝗈𝗋𝗆𝖺𝗅", callback_data="normal"),
],[
InlineKeyboardButton(text="𝖦𝖺𝗎𝗌𝗌𝗂𝖺𝗇", callback_data="gas")
],[
InlineKeyboardButton('𝙱𝙰𝙲𝙺', callback_data='photo')
]]
await query.message.edit("**Select A Type**", reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "circle":
buttons = [[
InlineKeyboardButton(text="𝖶𝗂𝗍𝗁 𝖡𝖦", callback_data="circlewithbg"),
InlineKeyboardButton(text="𝖶𝗂𝗍𝗁𝗈𝗎𝗍 𝖡𝖦", callback_data="circlewithoutbg"),
],[
InlineKeyboardButton('𝙱𝙰𝙲𝙺', callback_data='photo')
]]
await query.message.edit_text("**Select Required Mode**", reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "border":
buttons = [[
InlineKeyboardButton(text="𝖱𝖾𝖽", callback_data="red"),
InlineKeyboardButton(text="𝖦𝗋𝖾𝖾𝗇", callback_data="green"),
],[
InlineKeyboardButton(text="𝖡𝗅𝖺𝖼𝗄", callback_data="black"),
InlineKeyboardButton(text="𝖡𝗅𝗎𝖾", callback_data="blue"),
],[
InlineKeyboardButton('𝙱𝙰𝙲𝙺', callback_data='photo')
]]
await query.message.edit("**Select Border**", reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "photo":
buttons = [[
InlineKeyboardButton(text="𝖡𝗋𝗂𝗀𝗍𝗁", callback_data="bright"),
InlineKeyboardButton(text="𝖬𝗂𝗑𝖾𝖽", callback_data="mix"),
InlineKeyboardButton(text="𝖡 & 𝖶", callback_data="b|w"),
],[
InlineKeyboardButton(text="𝖢𝗂𝗋𝖼𝗅𝖾", callback_data="circle"),
InlineKeyboardButton(text="𝖡𝗅𝗎𝗋", callback_data="blur"),
InlineKeyboardButton(text="𝖡𝗈𝗋𝖽𝖾𝗋", callback_data="border"),
],[
InlineKeyboardButton(text="𝖲𝗍𝗂𝖼𝗄𝖾𝗋", callback_data="stick"),
InlineKeyboardButton(text="𝖱𝗈𝗍𝖺𝗍𝖾", callback_data="rotate"),
InlineKeyboardButton(text="𝖢𝗈𝗇𝗍𝗋𝖺𝗌𝗍", callback_data="contrast"),
],[
InlineKeyboardButton(text="𝖲𝖾𝗉𝗂𝖺", callback_data="sepia"),
InlineKeyboardButton(text="𝖯𝖾𝗇𝖼𝗂𝗅", callback_data="pencil"),
InlineKeyboardButton(text="𝖢𝖺𝗋𝗍𝗈𝗈𝗇", callback_data="cartoon"),
],[
InlineKeyboardButton(text="𝖨𝗇𝗏𝖾𝗋𝗍", callback_data="inverted"),
InlineKeyboardButton(text="𝖦𝗅𝗂𝗍𝖼𝗁", callback_data="glitch"),
InlineKeyboardButton(text="𝖱𝖾𝗆𝗈𝗏𝖾 𝖡𝖦", callback_data="removebg")
],[
InlineKeyboardButton(text="𝖢𝗅𝗈𝗌𝖾", callback_data="close_data")
]]
await query.message.edit_text("Sᴇʟᴇᴄᴛ Yᴏᴜʀ Rᴇǫᴜɪʀᴇᴅ Mᴏᴅᴇ Fʀᴏᴍ Bᴇʟᴏᴡ!", reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "bright":
await bright(client, query.message)
elif query.data == "mix":
await mix(client, query.message)
elif query.data == "b|w":
await black_white(client, query.message)
elif query.data == "circlewithbg":
await circle_with_bg(client, query.message)
elif query.data == "circlewithoutbg":
await circle_without_bg(client, query.message)
elif query.data == "green":
await green_border(client, query.message)
elif query.data == "blue":
await blue_border(client, query.message)
elif query.data == "red":
await red_border(client, query.message)
elif query.data == "black":
await black_border(client, query.message)
elif query.data == "circle_sticker":
await round_sticker(client, query.message)
elif query.data == "inverted":
await inverted(client, query.message)
elif query.data == "stkr":
await sticker(client, query.message)
elif query.data == "cur_ved":
await edge_curved(client, query.message)
elif query.data == "90":
await rotate_90(client, query.message)
elif query.data == "180":
await rotate_180(client, query.message)
elif query.data == "270":
await rotate_270(client, query.message)
elif query.data == "contrast":
await contrast(client, query.message)
elif query.data == "box":
await box_blur(client, query.message)
elif query.data == "gas":
await g_blur(client, query.message)
elif query.data == "normal":
await normal_blur(client, query.message)
elif query.data == "sepia":
await sepia_mode(client, query.message)
elif query.data == "pencil":
await pencil(client, query.message)
elif query.data == "cartoon":
await cartoon(client, query.message)
elif query.data == "normalglitch1":
await normalglitch_1(client, query.message)
elif query.data == "normalglitch2":
await normalglitch_2(client, query.message)
elif query.data == "normalglitch3":
await normalglitch_3(client, query.message)
elif query.data == "normalglitch4":
await normalglitch_4(client, query.message)
elif query.data == "normalglitch5":
await normalglitch_5(client, query.message)
elif query.data == "scanlineglitch1":
await scanlineglitch_1(client, query.message)
elif query.data == "scanlineglitch2":
await scanlineglitch_2(client, query.message)
elif query.data == "scanlineglitch3":
await scanlineglitch_3(client, query.message)
elif query.data == "scanlineglitch4":
await scanlineglitch_4(client, query.message)
elif query.data == "scanlineglitch5":
await scanlineglitch_5(client, query.message)
elif query.data == "rmbgwhite":
await removebg_white(client, query.message)
elif query.data == "rmbgplain":
await removebg_plain(client, query.message)
elif query.data == "rmbgsticker":
await removebg_sticker(client, query.message)
elif query.data == "pages":
await query.answer("🤨 Cᴜʀɪᴏsɪᴛʏ Is A Lɪᴛᴛʟᴇ Mᴏʀᴇ, Isɴ'ᴛ Iᴛ? 😁", show_alert=True)
elif query.data == "howdl":
try: await query.answer(script.HOW_TO_DOWNLOAD.format(query.from_user.first_name), show_alert=True)
except: await query.message.edit(script.HOW_TO_DOWNLOAD.format(query.from_user.first_name))
elif query.data == "start":
buttons = [[
InlineKeyboardButton("➕️ Aᴅᴅ Mᴇ Tᴏ Yᴏᴜʀ Cʜᴀᴛ ➕", url=f"http://t.me/{temp.U_NAME}?startgroup=true")
],[
InlineKeyboardButton("Sᴇᴀʀᴄʜ 🔎", switch_inline_query_current_chat=''),
InlineKeyboardButton("Cʜᴀɴɴᴇʟ 🔈", url="https://t.me/mkn_bots_updates")
],[
InlineKeyboardButton("Hᴇʟᴩ 🕸️", callback_data="help"),
InlineKeyboardButton("Aʙᴏᴜᴛ ✨", callback_data="about")
]]
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), START_MESSAGE.format(user=query.from_user.mention, bot=client.mention), enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "help":
buttons = [[
InlineKeyboardButton('⚙️ Aᴅᴍɪɴ Pᴀɴᴇʟ ⚙️', 'admin')
],[
InlineKeyboardButton('Fɪʟᴛᴇʀꜱ', 'openfilter'),
InlineKeyboardButton('Cᴏɴɴᴇᴄᴛ', 'coct')
],[
InlineKeyboardButton('Fɪʟᴇ Sᴛᴏʀᴇ', 'newdata'),
InlineKeyboardButton('Exᴛʀᴀ Mᴏᴅᴇ', 'extmod')
],[
InlineKeyboardButton('Gʀᴏᴜᴩ Mᴀɴᴀɢᴇʀ', 'gpmanager'),
InlineKeyboardButton('Bᴏᴛ Sᴛᴀᴛᴜꜱ ❄️', 'stats')
],[
InlineKeyboardButton('✘ Cʟᴏꜱᴇ', 'close_data'),
InlineKeyboardButton('« Bᴀᴄᴋ', 'start')
]]
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), script.HELP_TXT.format(query.from_user.mention), enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "about":
buttons= [[
InlineKeyboardButton('Sᴏᴜʀᴄᴇ Cᴏᴅᴇ 📜', 'source')
],[
InlineKeyboardButton('✘ Cʟᴏꜱᴇ', 'close_data'),
InlineKeyboardButton('« Bᴀᴄᴋ', 'start')
]]
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), script.ABOUT_TXT.format(temp.B_NAME), enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "source":
buttons = [[
InlineKeyboardButton('ꜱᴏᴜʀᴄᴇ ᴄᴏᴅᴇ', url='https://github.com/MrMKN/PROFESSOR-BOT')
],[
InlineKeyboardButton('‹ Bᴀᴄᴋ', 'about')
]]
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), script.SOURCE_TXT, enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "admin":
buttons = [[
InlineKeyboardButton('✘ Cʟᴏꜱᴇ', 'close_data'),
InlineKeyboardButton('« Bᴀᴄᴋ', 'help')
]]
if query.from_user.id not in ADMINS:
return await query.answer("Sᴏʀʀʏ Tʜɪs Mᴇɴᴜ Oɴʟʏ Fᴏʀ Mʏ Aᴅᴍɪɴs ⚒️", show_alert=True)
await query.message.edit("Pʀᴏᴄᴇꜱꜱɪɴɢ Wᴀɪᴛ Fᴏʀ 15 ꜱᴇᴄ...")
total, used, free = shutil.disk_usage(".")
stats = script.SERVER_STATS.format(get_time(time.time() - client.uptime), psutil.cpu_percent(), psutil.virtual_memory().percent, humanbytes(total), humanbytes(used), psutil.disk_usage('/').percent, humanbytes(free))
stats_pic = await make_carbon(stats, True)
await query.edit_message_media(InputMediaPhoto(stats_pic, script.ADMIN_TXT, enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "openfilter":
buttons = [[
InlineKeyboardButton('AᴜᴛᴏFɪʟᴛᴇʀ', 'autofilter'),
InlineKeyboardButton('MᴀɴᴜᴀʟFɪʟᴛᴇʀ', 'manuelfilter')
],[
InlineKeyboardButton('GʟᴏʙᴀʟFɪʟᴛᴇʀ', 'globalfilter')
],[
InlineKeyboardButton('✘ Cʟᴏꜱᴇ', 'close_data'),
InlineKeyboardButton('« Bᴀᴄᴋ', 'help')
]]
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), script.FILTER_TXT, enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "autofilter":
buttons = [[
InlineKeyboardButton('✘ Cʟᴏꜱᴇ', 'close_data'),
InlineKeyboardButton('« Bᴀᴄᴋ', 'openfilter')
]]
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), script.AUTOFILTER_TXT, enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "manuelfilter":
buttons = [[
InlineKeyboardButton('Bᴜᴛᴛᴏɴ Fᴏʀᴍᴀᴛ', 'button')
],[
InlineKeyboardButton('✘ Cʟᴏꜱᴇ', 'close_data'),
InlineKeyboardButton('« Bᴀᴄᴋ', 'openfilter')
]]
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), script.MANUELFILTER_TXT, enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "globalfilter":
buttons = [[
InlineKeyboardButton('Bᴜᴛᴛᴏɴ Fᴏʀᴍᴀᴛ', 'buttong')
],[
InlineKeyboardButton('✘ Cʟᴏꜱᴇ', 'close_data'),
InlineKeyboardButton('« Bᴀᴄᴋ', 'openfilter')
]]
if query.from_user.id not in ADMINS:
return await query.answer("Sᴏʀʀʏ Tʜɪs Mᴇɴᴜ Oɴʟʏ Fᴏʀ Mʏ Aᴅᴍɪɴs ⚒️", show_alert=True)
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), script.GLOBALFILTER_TXT, enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data.startswith("button"):
buttons = [[
InlineKeyboardButton('✘ Cʟᴏꜱᴇ', 'close_data'),
InlineKeyboardButton('« Bᴀᴄᴋ', f"{'manuelfilter' if query.data == 'button' else 'globalfilter'}")
]]
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), script.BUTTON_TXT, enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "coct":
buttons = [[
InlineKeyboardButton('✘ Cʟᴏꜱᴇ', 'close_data'),
InlineKeyboardButton('« Bᴀᴄᴋ', 'help')
]]
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), script.CONNECTION_TXT, enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "newdata":
buttons = [[
InlineKeyboardButton('✘ Cʟᴏꜱᴇ', 'close_data'),
InlineKeyboardButton('« Bᴀᴄᴋ', 'help')
]]
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), script.FILE_TXT, enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "extmod":
buttons = [[
InlineKeyboardButton('✘ Cʟᴏꜱᴇ', 'close_data'),
InlineKeyboardButton('« Bᴀᴄᴋ', 'help')
]]
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), script.EXTRAMOD_TXT, enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "gpmanager":
buttons = [[
InlineKeyboardButton('✘ Cʟᴏꜱᴇ', 'close_data'),
InlineKeyboardButton('« Bᴀᴄᴋ', 'help')
]]
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), script.GROUPMANAGER_TXT, enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data == "stats":
buttons = [[
InlineKeyboardButton('⟳ Rᴇꜰʀᴇꜱʜ', 'stats'),
InlineKeyboardButton('« Bᴀᴄᴋ', 'help')
]]
total = await Media.count_documents()
users = await db.total_users_count()
chats = await db.total_chat_count()
monsize = await db.get_db_size()
free = 536870912 - monsize
monsize = get_size(monsize)
free = get_size(free)
await query.message.edit('ʟᴏᴀᴅɪɴɢ....')
await query.edit_message_media(InputMediaPhoto(random.choice(PICS), script.STATUS_TXT.format(total, users, chats, monsize, free), enums.ParseMode.HTML), reply_markup=InlineKeyboardMarkup(buttons))
elif query.data.startswith("setgs"):
ident, set_type, status, grp_id = query.data.split("#")
grpid = await active_connection(str(query.from_user.id))
if str(grp_id) != str(grpid):
return await query.message.edit("Yᴏᴜʀ Aᴄᴛɪᴠᴇ Cᴏɴɴᴇᴄᴛɪᴏɴ Hᴀs Bᴇᴇɴ Cʜᴀɴɢᴇᴅ. Gᴏ Tᴏ /settings")
if status == "True": await save_group_settings(grpid, set_type, False)
else: await save_group_settings(grpid, set_type, True)
settings = await get_settings(grpid)
if settings is not None:
buttons = [[
InlineKeyboardButton(f"ꜰɪʟᴛᴇʀ ʙᴜᴛᴛᴏɴ : {'sɪɴɢʟᴇ' if settings['button'] else 'ᴅᴏᴜʙʟᴇ'}", f'setgs#button#{settings["button"]}#{str(grp_id)}')
],[
InlineKeyboardButton(f"ꜰɪʟᴇ ɪɴ ᴩᴍ ꜱᴛᴀʀᴛ: {'ᴏɴ' if settings['botpm'] else 'ᴏꜰꜰ'}", f'setgs#botpm#{settings["botpm"]}#{str(grp_id)}')
],[
InlineKeyboardButton(f"ʀᴇꜱᴛʀɪᴄᴛ ᴄᴏɴᴛᴇɴᴛ : {'ᴏɴ' if settings['file_secure'] else 'ᴏꜰꜰ'}", f'setgs#file_secure#{settings["file_secure"]}#{str(grp_id)}')
],[
InlineKeyboardButton(f"ɪᴍᴅʙ ɪɴ ꜰɪʟᴛᴇʀ : {'ᴏɴ' if settings['imdb'] else 'ᴏꜰꜰ'}", f'setgs#imdb#{settings["imdb"]}#{str(grp_id)}')
],[
InlineKeyboardButton(f"ꜱᴩᴇʟʟɪɴɢ ᴄʜᴇᴄᴋ : {'ᴏɴ' if settings['spell_check'] else 'ᴏꜰꜰ'}", f'setgs#spell_check#{settings["spell_check"]}#{str(grp_id)}')
],[
InlineKeyboardButton(f"ᴡᴇʟᴄᴏᴍᴇ ᴍᴇꜱꜱᴀɢᴇ : {'ᴏɴ' if settings['welcome'] else 'ᴏꜰꜰ'}", f'setgs#welcome#{settings["welcome"]}#{str(grp_id)}')
]]
await query.message.edit_reply_markup(InlineKeyboardMarkup(buttons))
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\ExtraMods\carbon.py
from pyrogram import Client, filters
from pyrogram.types import *
from aiohttp import ClientSession
from telegraph import upload_file
from io import BytesIO
ai_client = ClientSession()
async def make_carbon(code, tele=False):
url = "https://carbonara.solopov.dev/api/cook"
async with ai_client.post(url, json={"code": code}) as resp:
image = BytesIO(await resp.read())
image.name = "carbon.png"
if tele:
uf = upload_file(image)
image.close()
return f"https://graph.org{uf[0]}"
return image
@Client.on_message(filters.command("carbon"))
async def carbon_func(b, message):
if not message.reply_to_message:
return await message.reply_text("ʀᴇᴘʟʏ ᴛᴏ ᴀ ᴛᴇxᴛ ᴍᴇssᴀɢᴇ ᴛᴏ ᴍᴀᴋᴇ ᴄᴀʀʙᴏɴ.")
if not message.reply_to_message.text:
return await message.reply_text("ʀᴇᴘʟʏ ᴛᴏ ᴀ ᴛᴇxᴛ ᴍᴇssᴀɢᴇ ᴛᴏ ᴍᴀᴋᴇ ᴄᴀʀʙᴏɴ.")
user_id = message.from_user.id
m = await message.reply_text("ᴘʀᴏᴄᴇssɪɴɢ...")
carbon = await make_carbon(message.reply_to_message.text)
await m.edit("ᴜᴘʟᴏᴀᴅɪɴɢ..")
await message.reply_photo(
photo=carbon,
caption="**ᴍᴀᴅᴇ ʙʏ: @mkn_bots_updates**",
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("ꜱᴜᴩᴩᴏʀᴛ ᴜꜱ", url="https://t.me/mkn_bots_updates")]]),
)
await m.delete()
carbon.close()
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\ExtraMods\font.py
import os
from image.font_string import Fonts
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
@Client.on_message(filters.private & filters.command(["font"]))
async def style_buttons(c, m, cb=False):
buttons = [[
InlineKeyboardButton('𝚃𝚢𝚙𝚎𝚠𝚛𝚒𝚝𝚎𝚛', callback_data='style+typewriter'),
InlineKeyboardButton('𝕆𝕦𝕥𝕝𝕚𝕟𝕖', callback_data='style+outline'),
InlineKeyboardButton('𝐒𝐞𝐫𝐢𝐟', callback_data='style+serif'),
],[
InlineKeyboardButton('𝑺𝒆𝒓𝒊𝒇', callback_data='style+bold_cool'),
InlineKeyboardButton('𝑆𝑒𝑟𝑖𝑓', callback_data='style+cool'),
InlineKeyboardButton('Sᴍᴀʟʟ Cᴀᴘs', callback_data='style+small_cap'),
],[
InlineKeyboardButton('𝓈𝒸𝓇𝒾𝓅𝓉', callback_data='style+script'),
InlineKeyboardButton('𝓼𝓬𝓻𝓲𝓹𝓽', callback_data='style+script_bolt'),
InlineKeyboardButton('ᵗⁱⁿʸ', callback_data='style+tiny'),
],[
InlineKeyboardButton('ᑕOᗰIᑕ', callback_data='style+comic'),
InlineKeyboardButton('𝗦𝗮𝗻𝘀', callback_data='style+sans'),
InlineKeyboardButton('𝙎𝙖𝙣𝙨', callback_data='style+slant_sans'),
],[
InlineKeyboardButton('𝘚𝘢𝘯𝘴', callback_data='style+slant'),
InlineKeyboardButton('𝖲𝖺𝗇𝗌', callback_data='style+sim'),
InlineKeyboardButton('Ⓒ︎Ⓘ︎Ⓡ︎Ⓒ︎Ⓛ︎Ⓔ︎Ⓢ︎', callback_data='style+circles')
],[
InlineKeyboardButton('🅒︎🅘︎🅡︎🅒︎🅛︎🅔︎🅢︎', callback_data='style+circle_dark'),
InlineKeyboardButton('𝔊𝔬𝔱𝔥𝔦𝔠', callback_data='style+gothic'),
InlineKeyboardButton('𝕲𝖔𝖙𝖍𝖎𝖈', callback_data='style+gothic_bolt'),
],[
InlineKeyboardButton('C͜͡l͜͡o͜͡u͜͡d͜͡s͜͡', callback_data='style+cloud'),
InlineKeyboardButton('H̆̈ă̈p̆̈p̆̈y̆̈', callback_data='style+happy'),
InlineKeyboardButton('S̑̈ȃ̈d̑̈', callback_data='style+sad'),
],[
InlineKeyboardButton('Next ➡️', callback_data="nxt")
]]
if not cb:
if ' ' in m.text:
title = m.text.split(" ", 1)[1]
await m.reply_text(title, reply_markup=InlineKeyboardMarkup(buttons), reply_to_message_id=m.id)
else:
await m.reply_text(text="Ente Any Text Eg:- `/font [text]`")
else:
await m.answer()
await m.message.edit_reply_markup(InlineKeyboardMarkup(buttons))
@Client.on_callback_query(filters.regex('^nxt'))
async def nxt(c, m):
if m.data == "nxt":
buttons = [[
InlineKeyboardButton('🇸 🇵 🇪 🇨 🇮 🇦 🇱 ', callback_data='style+special'),
InlineKeyboardButton('🅂🅀🅄🄰🅁🄴🅂', callback_data='style+squares'),
InlineKeyboardButton('🆂︎🆀︎🆄︎🅰︎🆁︎🅴︎🆂︎', callback_data='style+squares_bold'),
],[
InlineKeyboardButton('ꪖꪀᦔꪖꪶꪊᥴ𝓲ꪖ', callback_data='style+andalucia'),
InlineKeyboardButton('爪卂几ᘜ卂', callback_data='style+manga'),
InlineKeyboardButton('S̾t̾i̾n̾k̾y̾', callback_data='style+stinky'),
],[
InlineKeyboardButton('B̥ͦu̥ͦb̥ͦb̥ͦl̥ͦe̥ͦs̥ͦ', callback_data='style+bubbles'),
InlineKeyboardButton('U͟n͟d͟e͟r͟l͟i͟n͟e͟', callback_data='style+underline'),
InlineKeyboardButton('꒒ꍏꀷꌩꌃꀎꁅ', callback_data='style+ladybug'),
],[
InlineKeyboardButton('R҉a҉y҉s҉', callback_data='style+rays'),
InlineKeyboardButton('B҈i҈r҈d҈s҈', callback_data='style+birds'),
InlineKeyboardButton('S̸l̸a̸s̸h̸', callback_data='style+slash'),
],[
InlineKeyboardButton('s⃠t⃠o⃠p⃠', callback_data='style+stop'),
InlineKeyboardButton('S̺͆k̺͆y̺͆l̺͆i̺͆n̺͆e̺͆', callback_data='style+skyline'),
InlineKeyboardButton('A͎r͎r͎o͎w͎s͎', callback_data='style+arrows'),
],[
InlineKeyboardButton('ዪሀክቿነ', callback_data='style+qvnes'),
InlineKeyboardButton('S̶t̶r̶i̶k̶e̶', callback_data='style+strike'),
InlineKeyboardButton('F༙r༙o༙z༙e༙n༙', callback_data='style+frozen')
],[
InlineKeyboardButton('⬅️ Back', callback_data='nxt+0')
]]
await m.answer()
await m.message.edit_reply_markup(InlineKeyboardMarkup(buttons))
else:
await style_buttons(c, m, cb=True)
@Client.on_callback_query(filters.regex('^style'))
async def style(c, m):
await m.answer()
cmd, style = m.data.split('+')
if style == 'typewriter':
cls = Fonts.typewriter
if style == 'outline':
cls = Fonts.outline
if style == 'serif':
cls = Fonts.serief
if style == 'bold_cool':
cls = Fonts.bold_cool
if style == 'cool':
cls = Fonts.cool
if style == 'small_cap':
cls = Fonts.smallcap
if style == 'script':
cls = Fonts.script
if style == 'script_bolt':
cls = Fonts.bold_script
if style == 'tiny':
cls = Fonts.tiny
if style == 'comic':
cls = Fonts.comic
if style == 'sans':
cls = Fonts.san
if style == 'slant_sans':
cls = Fonts.slant_san
if style == 'slant':
cls = Fonts.slant
if style == 'sim':
cls = Fonts.sim
if style == 'circles':
cls = Fonts.circles
if style == 'circle_dark':
cls = Fonts.dark_circle
if style == 'gothic':
cls = Fonts.gothic
if style == 'gothic_bolt':
cls = Fonts.bold_gothic
if style == 'cloud':
cls = Fonts.cloud
if style == 'happy':
cls = Fonts.happy
if style == 'sad':
cls = Fonts.sad
if style == 'special':
cls = Fonts.special
if style == 'squares':
cls = Fonts.square
if style == 'squares_bold':
cls = Fonts.dark_square
if style == 'andalucia':
cls = Fonts.andalucia
if style == 'manga':
cls = Fonts.manga
if style == 'stinky':
cls = Fonts.stinky
if style == 'bubbles':
cls = Fonts.bubbles
if style == 'underline':
cls = Fonts.underline
if style == 'ladybug':
cls = Fonts.ladybug
if style == 'rays':
cls = Fonts.rays
if style == 'birds':
cls = Fonts.birds
if style == 'slash':
cls = Fonts.slash
if style == 'stop':
cls = Fonts.stop
if style == 'skyline':
cls = Fonts.skyline
if style == 'arrows':
cls = Fonts.arrows
if style == 'qvnes':
cls = Fonts.rvnes
if style == 'strike':
cls = Fonts.strike
if style == 'frozen':
cls = Fonts.frozen
r, oldtxt = m.message.reply_to_message.text.split(None, 1)
new_text = cls(oldtxt)
try:
await m.message.edit_text(f"`{new_text}`\n\n👆 Click To Copy", reply_markup=m.message.reply_markup)
except Exception as e:
print(e)
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\ExtraMods\group_manager.py
from pyrogram.types import *
from pyrogram.errors import FloodWait
from pyrogram import Client, filters, enums
from pyrogram.errors.exceptions.forbidden_403 import ChatWriteForbidden
from pyrogram.errors.exceptions.bad_request_400 import ChatAdminRequired, UserAdminInvalid
from utils import extract_time, extract_user, admin_check, admin_filter
from info import ADMINS
from Script import script
from time import time
import asyncio
@Client.on_message(filters.command("ban"))
async def ban_user(_, message):
is_admin = await admin_check(message)
if not is_admin: return
user_id, user_first_name = extract_user(message)
try: await message.chat.ban_member(user_id=user_id)
except Exception as error: await message.reply_text(str(error))
else:
if str(user_id).lower().startswith("@"):
await message.reply_text(f"Someone else is dusting off..! \n{user_first_name} \nIs forbidden.")
else:
await message.reply_text(f"Someone else is dusting off..! \n{user_first_name} Is forbidden")
@Client.on_message(filters.command("tban"))
async def temp_ban_user(_, message):
is_admin = await admin_check(message)
if not is_admin: return
if not len(message.command) > 1: return
user_id, user_first_name = extract_user(message)
until_date_val = extract_time(message.command[1])
if until_date_val is None: return await message.reply_text(text=f"Invalid time type specified. \nExpected m, h, or d, Got it: {message.command[1][-1]}")
try: await message.chat.ban_member(user_id=user_id, until_date=until_date_val)
except Exception as error: await message.reply_text(str(error))
else:
if str(user_id).lower().startswith("@"):
await message.reply_text(f"Someone else is dusting off..!\n{user_first_name}\nbanned for {message.command[1]}!")
else:
await message.reply_text(f"Someone else is dusting off..!\nLavane\n banned for {message.command[1]}!")
@Client.on_message(filters.command(["unban", "unmute"]))
async def un_ban_user(_, message):
is_admin = await admin_check(message)
if not is_admin: return
user_id, user_first_name = extract_user(message)
try: await message.chat.unban_member(user_id=user_id)
except Exception as error: await message.reply_text(str(error))
else:
if str(user_id).lower().startswith("@"):
await message.reply_text(f"Okay, changed ... now {user_first_name} To You can join the group!")
else:
await message.reply_text(f"Okay, changed ... now {user_first_name} To You can join the group!")
@Client.on_message(filters.command("mute"))
async def mute_user(_, message):
is_admin = await admin_check(message)
if not is_admin: return
user_id, user_first_name = extract_user(message)
try: await message.chat.restrict_member(user_id=user_id, permissions=ChatPermissions())
except Exception as error: await message.reply_text(str(error))
else:
if str(user_id).lower().startswith("@"):
await message.reply_text(f"👍🏻 {user_first_name} Lavender's mouth is shut! 🤐")
else:
await message.reply_text(f"👍🏻 Of lavender The mouth is closed! 🤐")
@Client.on_message(filters.command("tmute"))
async def temp_mute_user(_, message):
is_admin = await admin_check(message)
if not is_admin: return
if not len(message.command) > 1: return
user_id, user_first_name = extract_user(message)
until_date_val = extract_time(message.command[1])
if until_date_val is None:
return await message.reply_text(f"Invalid time type specified. Expected m, h, or d, Got it: {message.command[1][-1]}")
try:
await message.chat.restrict_member(user_id=user_id, permissions=ChatPermissions(), until_date=until_date_val)
except Exception as error:
await message.reply_text(str(error))
else:
if str(user_id).lower().startswith("@"):
await message.reply_text(f"Be quiet for a while! 😠 {user_first_name} muted for {message.command[1]}!")
else:
await message.reply_text(f"Be quiet for a while! 😠 Of lavender Mouth muted for {message.command[1]}!")
@Client.on_message(filters.command("pin") & filters.create(admin_filter))
async def pin(_, message: Message):
if not message.reply_to_message: return
await message.reply_to_message.pin()
@Client.on_message(filters.command("unpin") & filters.create(admin_filter))
async def unpin(_, message: Message):
if not message.reply_to_message: return
await message.reply_to_message.unpin()
@Client.on_message(filters.command("purge") & (filters.group | filters.channel))
async def purge(client, message):
if message.chat.type not in ((enums.ChatType.SUPERGROUP, enums.ChatType.CHANNEL)): return
is_admin = await admin_check(message)
if not is_admin: return
status_message = await message.reply_text("...", quote=True)
await message.delete()
message_ids = []
count_del_etion_s = 0
if message.reply_to_message:
for a_s_message_id in range(message.reply_to_message.id, message.id):
message_ids.append(a_s_message_id)
if len(message_ids) == "100":
await client.delete_messages(chat_id=message.chat.id, message_ids=message_ids, revoke=True)
count_del_etion_s += len(message_ids)
message_ids = []
if len(message_ids) > 0:
await client.delete_messages(chat_id=message.chat.id, message_ids=message_ids, revoke=True)
count_del_etion_s += len(message_ids)
await status_message.edit_text(f"deleted {count_del_etion_s} messages")
await status_message.delete()
@Client.on_message(filters.group & filters.command('inkick'))
async def inkick(client, message):
user = await client.get_chat_member(message.chat.id, message.from_user.id)
if user.status not in (enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER):
note = await message.reply_text(script.CREATOR_REQUIRED)
await asyncio.sleep(3)
await note.delete()
return await message.delete()
if len(message.command) > 1:
input_str = message.command
sent_message = await message.reply_text(script.START_KICK)
await asyncio.sleep(2)
await message.delete()
count = 0
for member in client.get_chat_members(message.chat.id):
if member.user.status in input_str and not member.status in (enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER):
try:
client.ban_chat_member(message.chat.id, member.user.id, int(time() + 45))
count += 1
except (ChatAdminRequired, UserAdminInvalid):
await sent_message.edit(script.ADMIN_REQUIRED)
await client.leave_chat(message.chat.id)
break
except FloodWait as e:
await asyncio.sleep(e.value)
try:
await sent_message.edit(script.KICKED.format(count))
except ChatWriteForbidden: pass
else:
await message.reply_text(script.INPUT_REQUIRED)
@Client.on_message(filters.group & filters.command('dkick'))
async def dkick(client, message):
user = await client.get_chat_member(message.chat.id, message.from_user.id)
if user.status not in (enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER):
note = await message.reply_text(script.CREATOR_REQUIRED)
await asyncio.sleep(3)
await note.delete()
return await message.delete()
sent_message = await message.reply_text(script.START_KICK)
await message.delete()
count = 0
for member in client.get_chat_members(message.chat.id):
if member.user.is_deleted and not member.status in (enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER):
try:
await client.ban_chat_member(message.chat.id, member.user.id, int(time() + 45))
count += 1
except (ChatAdminRequired, UserAdminInvalid):
await sent_message.edit(script.ADMIN_REQUIRED)
await client.leave_chat(message.chat.id)
break
except FloodWait as e:
await asyncio.sleep(e.value)
try:
await sent_message.edit(script.DKICK.format(count))
except ChatWriteForbidden: pass
@Client.on_message((filters.channel | filters.group) & filters.command('instatus'))
async def instatus(client, message):
user = await client.get_chat_member(message.chat.id, message.from_user.id)
if user.status not in (enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER, ADMINS):
note = await message.reply("you are not administrator in this chat")
await asyncio.sleep(3)
await message.delete()
return await note.delete()
sent_message = await message.reply_text("🔁 Processing.....")
recently = 0
within_week = 0
within_month = 0
long_time_ago = 0
deleted_acc = 0
uncached = 0
bot = 0
for member in client.get_chat_members(message.chat.id):
if member.user.is_deleted: deleted_acc += 1
elif member.user.is_bot: bot += 1
elif member.user.status == enums.UserStatus.RECENTLY: recently += 1
elif member.user.status == enums.UserStatus.LAST_WEEK: within_week += 1
elif member.user.status == enums.UserStatus.LAST_MONTH: within_month += 1
elif member.user.status == enums.UserStatus.LONG_AGO: long_time_ago += 1
else: uncached += 1
if message.chat.type == enums.ChatType.CHANNEL:
await sent_message.edit(f"{message.chat.title}\nChat Member Status\n\nRecently - {recently}\nWithin Week - {within_week}\nWithin Month - {within_month}\nLong Time Ago - {long_time_ago}\n\nDeleted Account - {deleted_acc}\nBot - {bot}\nUnCached - {uncached}")
elif message.chat.type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
await sent_message.edit(f"{message.chat.title}\nChat Member Status\n\nRecently - {recently}\nWithin Week - {within_week}\nWithin Month - {within_month}\nLong Time Ago - {long_time_ago}\n\nDeleted Account - {deleted_acc}\nBot - {bot}\nUnCached - {uncached}")
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\ExtraMods\json.py
import os
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message, CallbackQuery
@Client.on_message(filters.command(["json", 'js']))
async def jsonify(_, message):
the_real_message = None
reply_to_id = None
pk = InlineKeyboardMarkup([[InlineKeyboardButton(text="𝙲𝙻𝙾𝚂𝙴", callback_data="close_data")]])
if message.reply_to_message:
the_real_message = message.reply_to_message
else:
the_real_message = message
try:
await message.reply_text(f"{the_real_message}
", reply_markup=pk, quote=True)
except Exception as e:
with open("json.text", "w+", encoding="utf8") as out_file:
out_file.write(str(the_real_message))
await message.reply_document(
document="json.text",
caption=str(e),
disable_notification=True,
quote=True,
reply_markup=reply_markup
)
os.remove("json.text")
@Client.on_message(filters.command("written"))
async def create_file(c, message):
content = message.reply_to_message.text
file_name = message.text.split(" ", 1)[1]
try:
with open(str(file_name), "w+") as out:
out.write(str(content))
await message.reply_document(
document=str(file_name),
caption="out put file"
)
os.remove(str(file_name))
except Exception as e:
await message.reply(e)
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\ExtraMods\lyrics.py
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
import requests, os
API = "https://apis.xditya.me/lyrics?song="
@Client.on_message(filters.text & filters.command(["lyrics"]))
async def sng(bot, message):
if not message.reply_to_message:
await message.reply_text("Pʟᴇᴀꜱᴇ Rᴇᴩʟʏ To A Mᴇꜱꜱᴀɢᴇ")
else:
mee = await message.reply_text("`Sᴇᴀʀᴄʜɪɴɢ 🔎`")
song = message.reply_to_message.text
chat_id = message.from_user.id
rpl = lyrics(song)
await mee.delete()
try:
await mee.delete()
await bot.send_message(chat_id, text = rpl, reply_to_message_id = message.id, reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton("ᴜᴘᴅᴀᴛᴇs", url = f"t.me/mkn_bots_updates")]]))
except Exception as e:
await message.reply_text(f"I Cᴀɴ'ᴛ Fɪɴᴅ A Sᴏɴɢ Wɪᴛʜ `{song}`", quote = True, reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton("ᴜᴘᴅᴀᴛᴇs", url = f"t.me/mkn_bots_updates")]]))
def search(song):
r = requests.get(API + song)
find = r.json()
return find
def lyrics(song):
fin = search(song)
text = f'**🎶 Sᴜᴄᴄᴇꜱꜰᴜʟʟy Exᴛʀᴀᴄᴛᴇᴅ Lyɪʀɪᴄꜱ Oꜰ {song}**\n\n'
text += f'`{fin["lyrics"]}`'
text += '\n\n\n**Mᴀᴅᴇ Bʏ AI**'
return text
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\ExtraMods\password.py
import random, os
from pyrogram import Client, filters, enums
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
@Client.on_message(filters.command(["genpassword", 'genpw']))
async def password(bot, update):
message = await update.reply_text(text="`Pʀᴏᴄᴇꜱꜱɪɴɢ..`")
password = "abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+".lower()
if len(update.command) > 1:
qw = update.text.split(" ", 1)[1]
else:
ST = ["5", "7", "6", "9", "10", "12", "14", "8", "13"]
qw = random.choice(ST)
limit = int(qw)
random_value = "".join(random.sample(password, limit))
txt = f"Lɪᴍɪᴛ: {str(limit)} \nPᴀꜱꜱᴡᴏʀᴅ: {random_value}
"
btn = InlineKeyboardMarkup([[InlineKeyboardButton('Mᴋɴ Bᴏᴛᴢ™️', url='https://t.me/mkn_bots_updates')]])
await message.edit_text(text=txt, reply_markup=btn, parse_mode=enums.ParseMode.HTML)
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\ExtraMods\paste.py
import os, re, json, aiohttp, requests
from pyrogram import Client, filters
#Headers
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36",
"content-type": "application/json",
}
#Pastebins
async def p_paste(message, extension=None):
siteurl = "https://pasty.lus.pm/api/v1/pastes"
data = {"content": message}
try:
response = requests.post(url=siteurl, data=json.dumps(data), headers=headers)
except Exception as e:
return {"error": str(e)}
if response.ok:
response = response.json()
purl = (
f"https://pasty.lus.pm/{response['id']}.{extension}"
if extension
else f"https://pasty.lus.pm/{response['id']}.txt"
)
return {
"url": purl,
"raw": f"https://pasty.lus.pm/{response['id']}/raw",
"bin": "Pasty",
}
return {"error": "UNABLE TO REACH pasty.lus.pm"}
@Client.on_message(filters.command(["tgpaste", "pasty", "paste"]))
async def pasty(client, message):
pablo = await message.reply_text("`Pʟᴇᴀꜱᴇ Wᴀɪᴛ...`")
tex_t = message.text
if ' ' in message.text:
message_s = message.text.split(" ", 1)[1]
elif message.reply_to_message:
message_s = message.reply_to_message.text
else:
await message.reply("Sᴏʀʀʏ No Iɴ Pᴜᴛ. Pʟᴇᴀꜱᴇ Rᴇᴩʟʏ To A Tᴇxᴛ Oʀ /paste Wɪᴛʜ Tᴇxᴛ")
if not tex_t:
if not message.reply_to_message:
await pablo.edit("Oɴʟʏ Tᴇxᴛ Aɴᴅ Dᴏᴄᴜᴍᴇɴᴛs Aʀᴇ Sᴜᴘᴘᴏʀᴛᴇᴅ")
return
if not message.reply_to_message.text:
file = await message.reply_to_message.download()
m_list = open(file, "r").read()
message_s = m_list
os.remove(file)
elif message.reply_to_message.text:
message_s = message.reply_to_message.text
ext = "py"
x = await p_paste(message_s, ext)
p_link = x["url"]
p_raw = x["raw"]
pasted = f"**Sᴜᴄᴄᴇssғᴜʟʟʏ Pᴀsᴛᴇ Tᴏ Pᴀsᴛʏ**\n\n**Lɪɴᴋ:** • [CʟɪᴄᴋHᴇʀᴇ]({p_link})\n\n**Rᴀᴡ Lɪɴᴋ:** • [CʟɪᴄᴋHᴇʀᴇ]({p_raw})"
await pablo.edit(pasted, disable_web_page_preview=True)
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\ExtraMods\photo.py
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from pyrogram import Client, filters
@Client.on_message(filters.photo & filters.private)
async def photo_handler(client, message):
buttons = [[
InlineKeyboardButton(text="𝖡𝗋𝗂𝗀𝗍𝗁", callback_data="bright"),
InlineKeyboardButton(text="𝖬𝗂𝗑𝖾𝖽", callback_data="mix"),
InlineKeyboardButton(text="𝖡 & 𝖶", callback_data="b|w"),
],[
InlineKeyboardButton(text="𝖢𝗂𝗋𝖼𝗅𝖾", callback_data="circle"),
InlineKeyboardButton(text="𝖡𝗅𝗎𝗋", callback_data="blur"),
InlineKeyboardButton(text="𝖡𝗈𝗋𝖽𝖾𝗋", callback_data="border"),
],[
InlineKeyboardButton(text="𝖲𝗍𝗂𝖼𝗄𝖾𝗋", callback_data="stick"),
InlineKeyboardButton(text="𝖱𝗈𝗍𝖺𝗍𝖾", callback_data="rotate"),
InlineKeyboardButton(text="𝖢𝗈𝗇𝗍𝗋𝖺𝗌𝗍", callback_data="contrast"),
],[
InlineKeyboardButton(text="𝖲𝖾𝗉𝗂𝖺", callback_data="sepia"),
InlineKeyboardButton(text="𝖯𝖾𝗇𝖼𝗂𝗅", callback_data="pencil"),
InlineKeyboardButton(text="𝖢𝖺𝗋𝗍𝗈𝗈𝗇", callback_data="cartoon"),
],[
InlineKeyboardButton(text="𝖨𝗇𝗏𝖾𝗋𝗍", callback_data="inverted"),
InlineKeyboardButton(text="𝖦𝗅𝗂𝗍𝖼𝗁", callback_data="glitch"),
InlineKeyboardButton(text="𝖱𝖾𝗆𝗈𝗏𝖾 𝖡𝖦", callback_data="removebg"),
],[
InlineKeyboardButton(text="𝖢𝗅𝗈𝗌𝖾", callback_data="close_data"),
]]
try:
await message.reply(text="Select Your Required Mode From Below", quote=True, reply_markup=InlineKeyboardMarkup(buttons))
except Exception as e:
print(e)
if "USER_IS_BLOCKED" in str(e): return
try: await message.reply_text(f"{e} \nSomething Went Wrong!", quote=True)
except Exception: return
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\ExtraMods\share_text.py
import os
from pyrogram import Client, filters
from urllib.parse import quote
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
@Client.on_message(filters.command(["share_text", "share", "sharetext",]))
async def share_text(client, message):
reply = message.reply_to_message
reply_id = message.reply_to_message.id if message.reply_to_message else message.id
input_split = message.text.split(None, 1)
if len(input_split) == 2:
input_text = input_split[1]
elif reply and (reply.text or reply.caption):
input_text = reply.text or reply.caption
else:
await message.reply_text(
text=f"**Notice:**\n\n1. Reply Any Messages.\n2. No Media Support\n\n**Any Question Join Support Chat**",
reply_to_message_id=reply_id,
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Support Chat", url=f"https://t.me/MKN_BOTZ_DISCUSSION_GROUP")]])
)
return
await message.reply_text(
text=f"**Here is Your Sharing Text 👇**\n\nhttps://t.me/share/url?url=" + quote(input_text),
reply_to_message_id=reply_id,
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("♂️ Share", url=f"https://t.me/share/url?url={quote(input_text)}")]])
)
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\ExtraMods\telegraph.py
import os, asyncio
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message, CallbackQuery
from telegraph import upload_file
from utils import get_file_id
@Client.on_message(filters.command("telegraph") & filters.private)
async def telegraph_upload(bot, update):
# Service Stopped
return await update.reply("🥲 This service is stopped due to https://t.me/durov/343")
replied = update.reply_to_message
if not replied:
return await update.reply_text("Rᴇᴘʟʏ Tᴏ A Pʜᴏᴛᴏ Oʀ Vɪᴅᴇᴏ Uɴᴅᴇʀ 5ᴍʙ")
file_info = get_file_id(replied)
if not file_info:
return await update.reply_text("Not Supported!")
text = await update.reply_text(text="Downloading To My Server ...
", disable_web_page_preview=True)
media = await update.reply_to_message.download()
await text.edit_text(text="Downloading Completed. Now I am Uploading to telegra.ph Link ...
", disable_web_page_preview=True)
try:
response = upload_file(media)
except Exception as error:
print(error)
await text.edit_text(text=f"Error :- {error}", disable_web_page_preview=True)
return
try:
os.remove(media)
except Exception as error:
print(error)
return
await text.edit_text(
text=f"Link :-\n\nhttps://graph.org{response[0]}
",
disable_web_page_preview=True,
reply_markup=InlineKeyboardMarkup( [[
InlineKeyboardButton(text="Open Link", url=f"https://graph.org{response[0]}"),
InlineKeyboardButton(text="Share Link", url=f"https://telegram.me/share/url?url=https://graph.org{response[0]}")
],[
InlineKeyboardButton(text="✗ Close ✗", callback_data="close")
]])
)
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\ExtraMods\tts.py
import traceback
from asyncio import get_running_loop
from io import BytesIO
from googletrans import Translator
from gtts import gTTS
from pyrogram import Client, filters
from pyrogram.types import Message
def convert(text):
audio = BytesIO()
i = Translator().translate(text, dest="en")
lang = i.src
tts = gTTS(text, lang=lang)
audio.name = lang + ".mp3"
tts.write_to_fp(audio)
return audio
@Client.on_message(filters.command("tts"))
async def text_to_speech(_, message: Message):
if not message.reply_to_message:
return await message.reply_text("Reply To Some Text FFS.")
if not message.reply_to_message.text:
return await message.reply_text("Reply To Some TextFFS.")
m = await message.reply_text("Processing")
text = message.reply_to_message.text
try:
loop = get_running_loop()
audio = await loop.run_in_executor(None, convert, text)
await message.reply_audio(audio)
await m.delete()
audio.close()
except Exception as e:
await m.edit(e)
e = traceback.format_exc()
print(e)
================================================================================
# File: C:\Users\Shakeel\Desktop\PROFESSOR\plugins\ExtraMods\yt_dl.py
from __future__ import unicode_literals
import os, requests, asyncio, math, time, wget
from pyrogram import filters, Client
from pyrogram.types import Message
from youtube_search import YoutubeSearch
from youtubesearchpython import SearchVideos
from yt_dlp import YoutubeDL
@Client.on_message(filters.command(['song', 'mp3']) & filters.private)
async def song(client, message):
user_id = message.from_user.id
user_name = message.from_user.first_name
rpk = "["+user_name+"](tg://user?id="+str(user_id)+")"
query = ''
for i in message.command[1:]:
query += ' ' + str(i)
print(query)
m = await message.reply(f"**ѕєαrchíng чσur ѕσng...!\n {query}**")
ydl_opts = {"format": "bestaudio[ext=m4a]"}
try:
results = YoutubeSearch(query, max_results=1).to_dict()
link = f"https://youtube.com{results[0]['url_suffix']}"
title = results[0]["title"][:40]
thumbnail = results[0]["thumbnails"][0]
thumb_name = f'thumb{title}.jpg'
thumb = requests.get(thumbnail, allow_redirects=True)
open(thumb_name, 'wb').write(thumb.content)
performer = f"[Mᴋɴ Bᴏᴛᴢ™]"
duration = results[0]["duration"]
url_suffix = results[0]["url_suffix"]
views = results[0]["views"]
except Exception as e:
print(str(e))
return await m.edit("**𝙵𝙾𝚄𝙽𝙳 𝙽𝙾𝚃𝙷𝙸𝙽𝙶 𝙿𝙻𝙴𝙰𝚂𝙴 𝙲𝙾𝚁𝚁𝙴𝙲𝚃 𝚃𝙷𝙴 𝚂𝙿𝙴𝙻𝙻𝙸𝙽𝙶 𝙾𝚁 𝙲𝙷𝙴𝙲𝙺 𝚃𝙷𝙴 𝙻𝙸𝙽𝙺**")
await m.edit("**dσwnlσαdíng чσur ѕσng...!**")
try:
with YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(link, download=False)
audio_file = ydl.prepare_filename(info_dict)
ydl.process_info(info_dict)
cap = "**BY›› [Mᴋɴ Bᴏᴛᴢ™](https://t.me/mkn_bots_updates)**"
secmul, dur, dur_arr = 1, 0, duration.split(':')
for i in range(len(dur_arr)-1, -1, -1):
dur += (int(dur_arr[i]) * secmul)
secmul *= 60
await message.reply_audio(
audio_file,
caption=cap,
quote=False,
title=title,
duration=dur,
performer=performer,
thumb=thumb_name
)
await m.delete()
except Exception as e:
await m.edit("**🚫 𝙴𝚁𝚁𝙾𝚁 🚫**")
print(e)
try:
os.remove(audio_file)
os.remove(thumb_name)
except Exception as e:
print(e)
def get_text(message: Message) -> [None,str]:
text_to_return = message.text
if message.text is None:
return None
if " " not in text_to_return:
return None
try:
return message.text.split(None, 1)[1]
except IndexError:
return None
@Client.on_message(filters.command(["video", "mp4"]))
async def vsong(client, message: Message):
urlissed = get_text(message)
pablo = await client.send_message(message.chat.id, f"**𝙵𝙸𝙽𝙳𝙸𝙽𝙶 𝚈𝙾𝚄𝚁 𝚅𝙸𝙳𝙴𝙾** `{urlissed}`")
if not urlissed:
return await pablo.edit("Invalid Command Syntax Please Check help Menu To Know More!")
search = SearchVideos(f"{urlissed}", offset=1, mode="dict", max_results=1)
mi = search.result()
mio = mi["search_result"]
mo = mio[0]["link"]
thum = mio[0]["title"]
fridayz = mio[0]["id"]
mio[0]["channel"]
kekme = f"https://img.youtube.com/vi/{fridayz}/hqdefault.jpg"
await asyncio.sleep(0.6)
url = mo
sedlyf = wget.download(kekme)
opts = {
"format": "best",
"addmetadata": True,
"key": "FFmpegMetadata",
"prefer_ffmpeg": True,
"geo_bypass": True,
"nocheckcertificate": True,
"postprocessors": [{"key": "FFmpegVideoConvertor", "preferedformat": "mp4"}],
"outtmpl": "%(id)s.mp4",
"logtostderr": False,
"quiet": True,
}
try:
with YoutubeDL(opts) as ytdl:
ytdl_data = ytdl.extract_info(url, download=True)
except Exception as e:
return await pablo.edit_text(f"**𝙳𝚘𝚠𝚗𝚕𝚘𝚊𝚍 𝙵𝚊𝚒𝚕𝚎𝚍 𝙿𝚕𝚎𝚊𝚜𝚎 𝚃𝚛𝚢 𝙰𝚐𝚊𝚒𝚗..♥️** \n**Error :** `{str(e)}`")
file_stark = f"{ytdl_data['id']}.mp4"
capy = f"""**𝚃𝙸𝚃𝙻𝙴 :** [{thum}]({mo})\n**𝚁𝙴𝚀𝚄𝙴𝚂𝚃𝙴𝙳 𝙱𝚈 :** {message.from_user.mention}"""
await client.send_video(
message.chat.id,
video=open(file_stark, "rb"),
duration=int(ytdl_data["duration"]),
file_name=str(ytdl_data["title"]),
thumb=sedlyf,
caption=capy,
supports_streaming=True,
reply_to_message_id=message.id
)
await pablo.delete()
for files in (sedlyf, file_stark):
if files and os.path.exists(files):
os.remove(files)
================================================================================