├── runtime.txt
├── Procfile
├── renovate.json
├── Dockerfile
├── requirements.txt
├── plugins
├── channel.py
├── index.py
├── inline.py
├── commands.py
└── pm_filter.py
├── logging.conf
├── sample_info.py
├── bot.py
├── info.py
├── .gitignore
├── app.json
├── README.md
├── utils.py
└── LICENSE
/runtime.txt:
--------------------------------------------------------------------------------
1 | python-3.8.7
2 |
--------------------------------------------------------------------------------
/Procfile:
--------------------------------------------------------------------------------
1 | worker: python3 bot.py
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3 | "extends": [
4 | "config:base"
5 | ]
6 | }
7 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.8-slim-buster
2 | WORKDIR /app
3 | COPY requirements.txt requirements.txt
4 | RUN pip3 install -r requirements.txt
5 |
6 | COPY . .
7 |
8 | CMD python3 bot.py
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | https://github.com/Mahesh0253/pyrogram/archive/inline.zip
2 | tgcrypto==1.2.2
3 | pymongo[srv]==3.11.4
4 | motor==2.4.0
5 | marshmallow==3.12.2
6 | umongo==3.0.0
7 | pyromod
8 | requests
9 | parse-torrent-name
10 |
--------------------------------------------------------------------------------
/plugins/channel.py:
--------------------------------------------------------------------------------
1 | from pyrogram import Client, filters
2 | from utils import save_file
3 | from info import CHANNELS
4 |
5 | media_filter = filters.document | filters.video | filters.audio
6 |
7 |
8 | @Client.on_message(filters.chat(CHANNELS) & media_filter)
9 | async def media(bot, message):
10 | """Media Handler"""
11 | for file_type in ("document", "video", "audio"):
12 | media = getattr(message, file_type, None)
13 | if media is not None:
14 | break
15 | else:
16 | return
17 |
18 | media.file_type = file_type
19 | media.caption = message.caption
20 | await save_file(media)
21 |
--------------------------------------------------------------------------------
/logging.conf:
--------------------------------------------------------------------------------
1 | [loggers]
2 | keys=root
3 |
4 | [handlers]
5 | keys=consoleHandler,fileHandler
6 |
7 | [formatters]
8 | keys=consoleFormatter,fileFormatter
9 |
10 | [logger_root]
11 | level=DEBUG
12 | handlers=consoleHandler,fileHandler
13 |
14 | [handler_consoleHandler]
15 | class=StreamHandler
16 | level=INFO
17 | formatter=consoleFormatter
18 | args=(sys.stdout,)
19 |
20 | [handler_fileHandler]
21 | class=FileHandler
22 | level=ERROR
23 | formatter=fileFormatter
24 | args=('TelegramBot.log','w',)
25 |
26 | [formatter_consoleFormatter]
27 | format=%(asctime)s - %(lineno)d - %(name)s - %(module)s - %(levelname)s - %(message)s
28 | datefmt=%I:%M:%S %p
29 |
30 | [formatter_fileFormatter]
31 | format=[%(asctime)s:%(name)s:%(lineno)d:%(levelname)s] %(message)s
32 | datefmt=%m/%d/%Y %I:%M:%S %p
--------------------------------------------------------------------------------
/sample_info.py:
--------------------------------------------------------------------------------
1 | # Bot information
2 | SESSION = 'Media_search'
3 | USER_SESSION = 'User_Bot'
4 | API_ID = 12345
5 | API_HASH = '0123456789abcdef0123456789abcdef'
6 | BOT_TOKEN = '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11'
7 | USERBOT_STRING_SESSION = ''
8 |
9 | # Bot settings
10 | CACHE_TIME = 300
11 | USE_CAPTION_FILTER = False
12 |
13 | # Admins, Channels & Users
14 | ADMINS = [12345789, 'admin123', 98765432]
15 | CHANNELS = [-10012345678, -100987654321, 'channelusername']
16 | AUTH_USERS = []
17 | AUTH_CHANNEL = None
18 |
19 | # MongoDB information
20 | DATABASE_URI = "mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb]?retryWrites=true&w=majority"
21 | DATABASE_NAME = 'Telegram'
22 | COLLECTION_NAME = 'channel_files' # If you are using the same database, then use different collection name for each bot
23 |
24 | # Messages
25 | START_MSG = """
26 | **Hi, I'm Media Search bot**
27 |
28 | Here you can search files in inline mode. Just press follwing buttons and start searching.
29 | """
30 |
31 | SHARE_BUTTON_TEXT = 'Checkout {username} for searching files'
32 | INVITE_MSG = 'Please join @.... to use this bot'
--------------------------------------------------------------------------------
/bot.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import logging.config
3 |
4 | # Get logging configurations
5 | logging.config.fileConfig('logging.conf')
6 | logging.getLogger().setLevel(logging.ERROR)
7 |
8 | from pyrogram import Client, __version__
9 | from pyrogram.raw.all import layer
10 | from utils import Media
11 | from info import SESSION, API_ID, API_HASH, BOT_TOKEN
12 | import pyromod.listen
13 |
14 | class Bot(Client):
15 |
16 | def __init__(self):
17 | super().__init__(
18 | session_name=SESSION,
19 | api_id=API_ID,
20 | api_hash=API_HASH,
21 | bot_token=BOT_TOKEN,
22 | workers=50,
23 | plugins={"root": "plugins"},
24 | sleep_threshold=5,
25 | )
26 |
27 | async def start(self):
28 | await super().start()
29 | await Media.ensure_indexes()
30 | me = await self.get_me()
31 | self.username = '@' + me.username
32 | print(f"{me.first_name} with for Pyrogram v{__version__} (Layer {layer}) started on {me.username}.")
33 |
34 | async def stop(self, *args):
35 | await super().stop()
36 | print("Bot stopped. Bye.")
37 |
38 |
39 | app = Bot()
40 | app.run()
41 |
--------------------------------------------------------------------------------
/info.py:
--------------------------------------------------------------------------------
1 | import re
2 | from os import environ
3 |
4 | id_pattern = re.compile(r'^.\d+$')
5 |
6 | # Bot information
7 | SESSION = environ.get('SESSION', 'Media_search')
8 | API_ID = int(environ['API_ID'])
9 | API_HASH = environ['API_HASH']
10 | BOT_TOKEN = environ['BOT_TOKEN']
11 |
12 | # Bot settings
13 | CACHE_TIME = int(environ.get('CACHE_TIME', 300))
14 | USE_CAPTION_FILTER = bool(environ.get('USE_CAPTION_FILTER', False))
15 |
16 | # Admins, Channels & Users
17 | ADMINS = [int(admin) if id_pattern.search(admin) else admin for admin in environ['ADMINS'].split()]
18 | CHANNELS = [int(ch) if id_pattern.search(ch) else ch for ch in environ['CHANNELS'].split()]
19 | auth_users = [int(user) if id_pattern.search(user) else user for user in environ.get('AUTH_USERS', '').split()]
20 | AUTH_USERS = (auth_users + ADMINS) if auth_users else []
21 | auth_channel = environ.get('AUTH_CHANNEL')
22 | AUTH_CHANNEL = int(auth_channel) if auth_channel and id_pattern.search(auth_channel) else auth_channel
23 | AUTH_GROUPS = [int(admin) for admin in environ.get("AUTH_GROUPS", "").split()]
24 |
25 | # MongoDB information
26 | DATABASE_URI = environ['DATABASE_URI']
27 | DATABASE_NAME = environ['DATABASE_NAME']
28 | COLLECTION_NAME = environ.get('COLLECTION_NAME', 'Telegram_files')
29 |
30 | # start Pics
31 | PICS = (environ.get('PICS', 'https://telegra.ph/file/7e56d907542396289fee4.jpg https://telegra.ph/file/9aa8dd372f4739fe02d85.jpg https://telegra.ph/file/adffc5ce502f5578e2806.jpg https://telegra.ph/file/6937b60bc2617597b92fd.jpg https://telegra.ph/file/09a7abaab340143f9c7e7.jpg https://telegra.ph/file/5a82c4a59bd04d415af1c.jpg https://telegra.ph/file/323986d3bd9c4c1b3cb26.jpg https://telegra.ph/file/b8a82dcb89fb296f92ca0.jpg https://telegra.ph/file/31adab039a85ed88e22b0.jpg https://telegra.ph/file/c0e0f4c3ed53ac8438f34.jpg https://telegra.ph/file/eede835fb3c37e07c9cee.jpg https://telegra.ph/file/e17d2d068f71a9867d554.jpg https://telegra.ph/file/8fb1ae7d995e8735a7c25.jpg https://telegra.ph/file/8fed19586b4aa019ec215.jpg https://telegra.ph/file/8e6c923abd6139083e1de.jpg https://telegra.ph/file/0049d801d29e83d68b001.jpg')).split()
32 |
33 | # Messages
34 | default_start_msg = """
35 | **Hi, I'm Media Search Bot or ypu can call me as Auto-Filter Bot**
36 | Here you can search files in Inline mode as well as PM, Use the below buttons to search files or send me the name of file to search.
37 | """
38 | START_MSG = environ.get('START_MSG', default_start_msg)
39 |
40 | FILE_CAPTION = environ.get("CUSTOM_FILE_CAPTION", "")
41 | OMDB_API_KEY = environ.get("OMDB_API_KEY", "")
42 | CUSTOM_FILE_CAPTION = None if FILE_CAPTION.strip() == "" else FILE_CAPTION
43 | API_KEY = None if OMDB_API_KEY.strip() == "" else OMDB_API_KEY
44 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Personal files
2 | *.session
3 | *.session-journal
4 | .vscode
5 | *test*.py
6 | setup.cfg
7 |
8 | # Byte-compiled / optimized / DLL files
9 | __pycache__/
10 | *.py[cod]
11 | *$py.class
12 |
13 | # C extensions
14 | *.so
15 |
16 | # Distribution / packaging
17 | .Python
18 | build/
19 | develop-eggs/
20 | dist/
21 | downloads/
22 | eggs/
23 | .eggs/
24 | lib/
25 | lib64/
26 | parts/
27 | sdist/
28 | var/
29 | wheels/
30 | share/python-wheels/
31 | *.egg-info/
32 | .installed.cfg
33 | *.egg
34 | MANIFEST
35 |
36 | # PyInstaller
37 | # Usually these files are written by a python script from a template
38 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
39 | *.manifest
40 | *.spec
41 |
42 | # Installer logs
43 | pip-log.txt
44 | pip-delete-this-directory.txt
45 |
46 | # Unit test / coverage reports
47 | htmlcov/
48 | .tox/
49 | .nox/
50 | .coverage
51 | .coverage.*
52 | .cache
53 | nosetests.xml
54 | coverage.xml
55 | *.cover
56 | *.py,cover
57 | .hypothesis/
58 | .pytest_cache/
59 | cover/
60 |
61 | # Translations
62 | *.mo
63 | *.pot
64 |
65 | # Django stuff:
66 | *.log
67 | local_settings.py
68 | db.sqlite3
69 | db.sqlite3-journal
70 |
71 | # Flask stuff:
72 | instance/
73 | .webassets-cache
74 |
75 | # Scrapy stuff:
76 | .scrapy
77 |
78 | # Sphinx documentation
79 | docs/_build/
80 |
81 | # PyBuilder
82 | .pybuilder/
83 | target/
84 |
85 | # Jupyter Notebook
86 | .ipynb_checkpoints
87 |
88 | # IPython
89 | profile_default/
90 | ipython_config.py
91 |
92 | # pyenv
93 | # For a library or package, you might want to ignore these files since the code is
94 | # intended to run in multiple environments; otherwise, check them in:
95 | # .python-version
96 |
97 | # pipenv
98 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
99 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
100 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
101 | # install all needed dependencies.
102 | #Pipfile.lock
103 |
104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
105 | __pypackages__/
106 |
107 | # Celery stuff
108 | celerybeat-schedule
109 | celerybeat.pid
110 |
111 | # SageMath parsed files
112 | *.sage.py
113 |
114 | # Environments
115 | .env
116 | .venv
117 | env/
118 | venv/
119 | ENV/
120 | env.bak/
121 | venv.bak/
122 |
123 | # Spyder project settings
124 | .spyderproject
125 | .spyproject
126 |
127 | # Rope project settings
128 | .ropeproject
129 |
130 | # mkdocs documentation
131 | /site
132 |
133 | # mypy
134 | .mypy_cache/
135 | .dmypy.json
136 | dmypy.json
137 |
138 | # Pyre type checker
139 | .pyre/
140 |
141 | # pytype static type analyzer
142 | .pytype/
143 |
144 | # Cython debug symbols
145 | cython_debug/
146 | config.py
147 |
--------------------------------------------------------------------------------
/plugins/index.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import asyncio
3 | from pyrogram import Client, filters
4 | from pyrogram.errors import FloodWait
5 | from info import ADMINS
6 | import os
7 | from utils import save_file
8 | import pyromod.listen
9 | logger = logging.getLogger(__name__)
10 | lock = asyncio.Lock()
11 |
12 |
13 | @Client.on_message(filters.command(['index', 'indexfiles']) & filters.user(ADMINS))
14 | async def index_files(bot, message):
15 | """Save channel or group files"""
16 | if lock.locked():
17 | await message.reply('Wait until previous process complete.')
18 | else:
19 | while True:
20 | last_msg = await bot.ask(text = "Forward me last message of a channel which I should save to my database.\n\nYou can forward posts from any public channel, but for private channels bot should be an admin in the channel.\n\nMake sure to forward with quotes (Not as a copy)", chat_id = message.from_user.id)
21 | try:
22 | last_msg_id = last_msg.forward_from_message_id
23 | chat_id = last_msg.forward_from_chat.username or last_msg.forward_from_chat.id
24 | await bot.get_messages(chat_id, last_msg_id)
25 | break
26 | except Exception as e:
27 | await last_msg.reply_text(f"This Is An Invalid Message, Either the channel is private and bot is not an admin in the forwarded chat, or you forwarded message as copy.\nError caused Due to {e}")
28 | continue
29 |
30 | msg = await message.reply('Processing...⏳')
31 | total_files = 0
32 | async with lock:
33 | try:
34 | total=last_msg_id + 1
35 | current=int(os.environ.get("SKIP", 2))
36 | nyav=0
37 | while True:
38 | try:
39 | message = await bot.get_messages(chat_id=chat_id, message_ids=current, replies=0)
40 | except FloodWait as e:
41 | await asyncio.sleep(e.x)
42 | message = await bot.get_messages(
43 | chat_id,
44 | current,
45 | replies=0
46 | )
47 | except Exception as e:
48 | print(e)
49 | try:
50 | for file_type in ("document", "video", "audio"):
51 | media = getattr(message, file_type, None)
52 | if media is not None:
53 | break
54 | else:
55 | continue
56 | media.file_type = file_type
57 | media.caption = message.caption
58 | await save_file(media)
59 | total_files += 1
60 | except Exception as e:
61 | print(e)
62 | current+=1
63 | nyav+=1
64 | if nyav == 20:
65 | await msg.edit(f"Total messages fetched: {current}\nTotal messages saved: {total_files}")
66 | nyav -= 20
67 | if current == total:
68 | break
69 | else:
70 | continue
71 | except Exception as e:
72 | logger.exception(e)
73 | await msg.edit(f'Error: {e}')
74 | else:
75 | await msg.edit(f'Total {total_files} Saved To DataBase!')
76 |
--------------------------------------------------------------------------------
/plugins/inline.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from pyrogram import Client, emoji, filters
3 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, InlineQueryResultCachedDocument
4 |
5 | from utils import get_search_results, is_subscribed
6 | from info import CACHE_TIME, AUTH_USERS, AUTH_CHANNEL, CUSTOM_FILE_CAPTION
7 |
8 | logger = logging.getLogger(__name__)
9 | cache_time = 0 if AUTH_USERS or AUTH_CHANNEL else CACHE_TIME
10 |
11 |
12 | @Client.on_inline_query(filters.user(AUTH_USERS) if AUTH_USERS else None)
13 | async def answer(bot, query):
14 | """Show search results for given inline query"""
15 |
16 | if AUTH_CHANNEL and not await is_subscribed(bot, query):
17 | await query.answer(results=[],
18 | cache_time=0,
19 | switch_pm_text='You have to subscribe my channel to use the bot',
20 | switch_pm_parameter="subscribe")
21 | return
22 |
23 | results = []
24 | if '|' in query.query:
25 | string, file_type = query.query.split('|', maxsplit=1)
26 | string = string.strip()
27 | file_type = file_type.strip().lower()
28 | else:
29 | string = query.query.strip()
30 | file_type = None
31 |
32 | offset = int(query.offset or 0)
33 | reply_markup = get_reply_markup(query=string)
34 | files, next_offset = await get_search_results(string,
35 | file_type=file_type,
36 | max_results=10,
37 | offset=offset)
38 |
39 | for file in files:
40 | title=file.file_name
41 | size=file.file_size
42 | f_caption=file.caption
43 | if CUSTOM_FILE_CAPTION:
44 | try:
45 | f_caption=CUSTOM_FILE_CAPTION.format(file_name=title, file_size=size, file_caption=f_caption)
46 | except Exception as e:
47 | print(e)
48 | f_caption=f_caption
49 | if f_caption is None:
50 | f_caption = f"{file.file_name}"
51 | results.append(
52 | InlineQueryResultCachedDocument(
53 | title=file.file_name,
54 | file_id=file.file_id,
55 | caption=f_caption,
56 | description=f'Size: {get_size(file.file_size)}\nType: {file.file_type}',
57 | reply_markup=reply_markup))
58 |
59 | if results:
60 | switch_pm_text = f"{emoji.FILE_FOLDER} Results"
61 | if string:
62 | switch_pm_text += f" for {string}"
63 |
64 | try:
65 | await query.answer(results=results,
66 | is_personal = True,
67 | cache_time=cache_time,
68 | switch_pm_text=switch_pm_text,
69 | switch_pm_parameter="start",
70 | next_offset=str(next_offset))
71 | except Exception as e:
72 | logging.exception(str(e))
73 | await query.answer(results=[], is_personal=True,
74 | cache_time=cache_time,
75 | switch_pm_text=str(e)[:63],
76 | switch_pm_parameter="error")
77 | else:
78 |
79 | switch_pm_text = f'{emoji.CROSS_MARK} No results'
80 | if string:
81 | switch_pm_text += f' for "{string}"'
82 |
83 | await query.answer(results=[],
84 | is_personal = True,
85 | cache_time=cache_time,
86 | switch_pm_text=switch_pm_text,
87 | switch_pm_parameter="okay")
88 |
89 |
90 | def get_reply_markup(query):
91 | buttons = [
92 | [
93 | InlineKeyboardButton('Search again', switch_inline_query_current_chat=query),
94 | InlineKeyboardButton('More Bots', url='https://t.me/subin_works/122')
95 | ]
96 | ]
97 | return InlineKeyboardMarkup(buttons)
98 |
99 |
100 | def get_size(size):
101 | """Get size in readable format"""
102 |
103 | units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
104 | size = float(size)
105 | i = 0
106 | while size >= 1024.0 and i < len(units):
107 | i += 1
108 | size /= 1024.0
109 | return "%.2f %s" % (size, units[i])
110 |
111 |
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Media Search bot",
3 | "description": "When you going to send file on telegram channel this bot will save that in database, So you can search that easily in inline mode",
4 | "keywords": [
5 | "telegram",
6 | "auto-filter",
7 | "filter",
8 | "best",
9 | "indian",
10 | "pyrogram",
11 | "media",
12 | "search",
13 | "channel",
14 | "index",
15 | "inline"
16 | ],
17 | "website": "https://github.com/Jinn-Of-Telegram/Media-Search-bot-v2",
18 | "repository": "https://github.com/Jinn-Of-Telegram/Media-Search-bot-v2",
19 | "env": {
20 | "BOT_TOKEN": {
21 | "description": "Your bot token from @BotFather",
22 | "value": ""
23 | },
24 | "API_ID": {
25 | "description": "Get this value from https://my.telegram.org",
26 | "value": ""
27 | },
28 | "API_HASH": {
29 | "description": "Get this value from https://my.telegram.org",
30 | "value": ""
31 | },
32 | "CHANNELS": {
33 | "description": "Username or ID of channel or group. Separate multiple IDs by space.",
34 | "value": ""
35 | },
36 | "ADMINS": {
37 | "description": "Username or ID of Admin. Separate multiple Admins by space.",
38 | "value": "1234567890"
39 | },
40 | "AUTH_USERS": {
41 | "description": "Username or ID of users to give access of inline search. Separate multiple users by space.\nLeave it empty if you don't want to restrict bot usage.",
42 | "value": "",
43 | "required": false
44 | },
45 | "AUTH_CHANNEL": {
46 | "description": "ID of channel.Make sure bot is admin in this channel. Without subscribing this channel users cannot use bot.",
47 | "value": "",
48 | "required": false
49 | },
50 | "START_MSG": {
51 | "description": "Welcome message for start command",
52 | "value": " Add welcome massege, Ex:- Hi i'm Movie group Autofilter Bot... ,how To add link? [link text](link) ex:- [spacious universe](https://t.me/series2day)",
53 | "required": false
54 | },
55 | "USE_CAPTION_FILTER": {
56 | "description": "Whether bot should use captions to improve search results. (True False)",
57 | "value": "False",
58 | "required": false
59 | },
60 | "OMDB_API_KEY": {
61 | "description": "Your OMBD API KEY, Fill if you want to generate a imdb poster of movie in autofilter.",
62 | "value": "",
63 | "required": false
64 | },
65 | "CUSTOM_FILE_CAPTION": {
66 | "description": "A custom file caption for your files. formatable with , file_name, file_caption, file_size, Read Readme.md for better understanding.",
67 | "value": "",
68 | "required": false
69 | },
70 | "AUTH_GROUPS": {
71 | "description": "ID of groups which bot should work as autofilter, bot can only work in thease groups. If not given , bot can be used in any group.",
72 | "value": "",
73 | "required": false
74 | },
75 | "DATABASE_URI": {
76 | "description": "mongoDB URI. Get this value from https://www.mongodb.com. For more help watch this video - https://youtu.be/dsuTn4qV2GA",
77 | "value": ""
78 | },
79 | "DATABASE_NAME": {
80 | "description": "Name of the database in mongoDB. For more help watch this video - https://youtu.be/dsuTn4qV2GA",
81 | "value": ""
82 | },
83 | "COLLECTION_NAME": {
84 | "description": "Name of the collections. Defaults to Telegram_files. If you are using the same database, then use different collection name for each bot",
85 | "value": "Telegram_files",
86 | "required": false
87 | },
88 | "CACHE_TIME": {
89 | "description": "The maximum amount of time in seconds that the result of the inline query may be cached on the server",
90 | "value": "300",
91 | "required": false
92 | }
93 | },
94 | "addons": [],
95 | "buildpacks": [
96 | {
97 | "url": "heroku/python"
98 | }
99 | ],
100 | "formation": {
101 | "worker": {
102 | "quantity": 1,
103 | "size": "free"
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | 
3 |
4 | ## Example Bot [Imdb Bot](https://t.me/Ma_autofilterbot)
5 |
6 | ## Added Features
7 | * Imdb posters for autofilter.
8 | * Custom captions for your files.
9 | * Index command to index all the files in a given channel (No USER_SESSION Required).
10 | * Ability to Index Public Channels without being admin.
11 | * Support Auto-Filter (Both in PM and in Groups)
12 | * Once files saved in Database , exists until you manually deletes. (No Worry if post gets deleted from source channel.)
13 | * Added Force subscribe (Only channel subscribes can use the bot)
14 | * Ability to restrict groups(AUTH_GROUPS)
15 |
16 |
17 | ## If Any Doubts Ask In [Bot Help](https://t.me/Bot2SupportBot)
18 |
19 | ## Installation
20 |
21 | ### Easy Way
22 | [](https://heroku.com/deploy?template=https://github.com/kalanakt/imdb-autofilter-bot)
23 |
24 | ### Hard Way
25 |
26 | ```bash
27 | # Create virtual environment
28 | python3 -m venv env
29 |
30 | # Activate virtual environment
31 | env\Scripts\activate.bat # For Windows
32 | source env/bin/activate # For Linux or MacOS
33 |
34 | # Install Packages
35 | pip3 install -r requirements.txt
36 |
37 | # Edit info.py with variables as given below then run bot
38 | python3 bot.py
39 | ```
40 | Check [`sample_info.py`](sample_info.py) before editing [`info.py`](info.py) file
41 |
42 |
43 | ## Thank You For [Subinps](https://t.me/Subinps_bot)
44 |
45 | ## Variables
46 |
47 | ### Required Variables
48 | * `BOT_TOKEN`: Create a bot using [@BotFather](https://telegram.dog/BotFather), and get the Telegram API token.
49 | * `API_ID`: Get this value from [telegram.org](https://my.telegram.org/apps)
50 | * `API_HASH`: Get this value from [telegram.org](https://my.telegram.org/apps)
51 | * `CHANNELS`: Username or ID of channel or group. Separate multiple IDs by space
52 | * `ADMINS`: Username or ID of Admin. Separate multiple Admins by space
53 | * `DATABASE_URI`: [mongoDB](https://www.mongodb.com) URI. Get this value from [mongoDB](https://www.mongodb.com). For more help watch this [video](https://youtu.be/dsuTn4qV2GA)
54 | * `DATABASE_NAME`: Name of the database in [mongoDB](https://www.mongodb.com). For more help watch this [video](https://youtu.be/dsuTn4qV2GA)
55 |
56 | ### Optional Variables
57 | * `OMDB_API_KEY`: OMBD_API_KEY to generate imdb poster for filter results.Get it from [omdbapi.com](http://www.omdbapi.com/apikey.aspx)
58 | * `CUSTOM_FILE_CAPTION` : A custom caption for your files. You can format it with file_name, file_size, file_caption.(supports html formating)
59 | Example: `Join [XTZ Bots](https://t.me/subin_works) for more useful bots\n\n{file_name}\nSize{file_size}\n{file_caption}.`
60 | * `AUTH_GROUPS` : ID of groups which bot should work as autofilter, bot can only work in thease groups. If not given , bot can be used in any group.
61 | * `COLLECTION_NAME`: Name of the collections. Defaults to Telegram_files. If you going to use same database, then use different collection name for each bot
62 | * `CACHE_TIME`: The maximum amount of time in seconds that the result of the inline query may be cached on the server
63 | * `USE_CAPTION_FILTER`: Whether bot should use captions to improve search results. (True/False)
64 | * `AUTH_USERS`: Username or ID of users to give access of inline search. Separate multiple users by space. Leave it empty if you don't want to restrict bot usage.
65 | * `AUTH_CHANNEL`: ID of channel. Without subscribing this channel users cannot use bot.
66 | * `START_MSG`: Welcome message for start command.
67 |
68 | ## Note
69 | * Currently [API used](http://www.omdbapi.com) here is allowing 1000 requests per day. [You may not get posters if its crossed](https://t.me/ThankTelegram/910168).
70 | Once a poster is fetched from OMDB , poster is saved to DB to reduce duplicate requests.
71 |
72 | ## Admin commands
73 | ```
74 | channel - Get basic infomation about channels
75 | total - Show total of saved files
76 | delete - Delete file from database
77 | index - Index all files from channel.
78 | logger - Get log file
79 | ```
80 |
81 | ## Tips
82 | * You can use `|` to separate query and file type while searching for specific type of file. For example: `Avengers | video`
83 | * If you don't want to create a channel or group, use your chat ID / username as the channel ID. When you send a file to a bot, it will be saved in the database.
84 |
85 |
86 |
87 | ## Thanks to
88 | * [Pyrogram](https://github.com/pyrogram/pyrogram)
89 | * Original [Repo](https://github.com/Mahesh0253/Media-Search-bot)
90 |
91 |
92 | ## Special Note
93 | * this is modifaird verson of main responsibility .All credits should goes to main developers
94 |
95 | ## License
96 | Code released under [The GNU General Public License](LICENSE).
97 |
--------------------------------------------------------------------------------
/utils.py:
--------------------------------------------------------------------------------
1 | import re
2 | import base64
3 | import logging
4 | from struct import pack
5 | from pyrogram.errors import UserNotParticipant
6 | from pyrogram.file_id import FileId
7 | from pymongo.errors import DuplicateKeyError
8 | from umongo import Instance, Document, fields
9 | from motor.motor_asyncio import AsyncIOMotorClient
10 | from marshmallow.exceptions import ValidationError
11 | import os
12 | import PTN
13 | import requests
14 | import json
15 | from info import DATABASE_URI, DATABASE_NAME, COLLECTION_NAME, USE_CAPTION_FILTER, AUTH_CHANNEL, API_KEY
16 | DATABASE_URI_2=os.environ.get('DATABASE_URI_2', DATABASE_URI)
17 | DATABASE_NAME_2=os.environ.get('DATABASE_NAME_2', DATABASE_NAME)
18 | COLLECTION_NAME_2="Posters"
19 | logger = logging.getLogger(__name__)
20 | logger.setLevel(logging.INFO)
21 |
22 | client = AsyncIOMotorClient(DATABASE_URI)
23 | db = client[DATABASE_NAME]
24 | instance = Instance.from_db(db)
25 |
26 | IClient = AsyncIOMotorClient(DATABASE_URI_2)
27 | imdbdb=client[DATABASE_NAME_2]
28 | imdb=Instance.from_db(imdbdb)
29 |
30 | @instance.register
31 | class Media(Document):
32 | file_id = fields.StrField(attribute='_id')
33 | file_ref = fields.StrField(allow_none=True)
34 | file_name = fields.StrField(required=True)
35 | file_size = fields.IntField(required=True)
36 | file_type = fields.StrField(allow_none=True)
37 | mime_type = fields.StrField(allow_none=True)
38 | caption = fields.StrField(allow_none=True)
39 |
40 | class Meta:
41 | collection_name = COLLECTION_NAME
42 |
43 | @imdb.register
44 | class Poster(Document):
45 | imdb_id = fields.StrField(attribute='_id')
46 | title = fields.StrField()
47 | poster = fields.StrField()
48 | year= fields.IntField(allow_none=True)
49 |
50 | class Meta:
51 | collection_name = COLLECTION_NAME_2
52 |
53 | async def save_poster(imdb_id, title, year, url):
54 | try:
55 | data = Poster(
56 | imdb_id=imdb_id,
57 | title=title,
58 | year=int(year),
59 | poster=url
60 | )
61 | except ValidationError:
62 | logger.exception('Error occurred while saving poster in database')
63 | else:
64 | try:
65 | await data.commit()
66 | except DuplicateKeyError:
67 | logger.warning("already saved in database")
68 | else:
69 | logger.info("Poster is saved in database")
70 |
71 | async def save_file(media):
72 | """Save file in database"""
73 |
74 | # TODO: Find better way to get same file_id for same media to avoid duplicates
75 | file_id, file_ref = unpack_new_file_id(media.file_id)
76 |
77 | try:
78 | file = Media(
79 | file_id=file_id,
80 | file_ref=file_ref,
81 | file_name=media.file_name,
82 | file_size=media.file_size,
83 | file_type=media.file_type,
84 | mime_type=media.mime_type,
85 | caption=media.caption.html if media.caption else None,
86 | )
87 | except ValidationError:
88 | logger.exception('Error occurred while saving file in database')
89 | else:
90 | try:
91 | await file.commit()
92 | except DuplicateKeyError:
93 | logger.warning(media.file_name + " is already saved in database")
94 | else:
95 | logger.info(media.file_name + " is saved in database")
96 |
97 |
98 | async def get_search_results(query, file_type=None, max_results=10, offset=0):
99 | """For given query return (results, next_offset)"""
100 |
101 | query = query.strip()
102 | if not query:
103 | raw_pattern = '.'
104 | elif ' ' not in query:
105 | raw_pattern = r'(\b|[\.\+\-_])' + query + r'(\b|[\.\+\-_])'
106 | else:
107 | raw_pattern = query.replace(' ', r'.*[\s\.\+\-_]')
108 |
109 | try:
110 | regex = re.compile(raw_pattern, flags=re.IGNORECASE)
111 | except:
112 | return []
113 |
114 | if USE_CAPTION_FILTER:
115 | filter = {'$or': [{'file_name': regex}, {'caption': regex}]}
116 | else:
117 | filter = {'file_name': regex}
118 |
119 | if file_type:
120 | filter['file_type'] = file_type
121 |
122 | total_results = await Media.count_documents(filter)
123 | next_offset = offset + max_results
124 |
125 | if next_offset > total_results:
126 | next_offset = ''
127 |
128 | cursor = Media.find(filter)
129 | # Sort by recent
130 | cursor.sort('$natural', -1)
131 | # Slice files according to offset and max results
132 | cursor.skip(offset).limit(max_results)
133 | # Get list of files
134 | files = await cursor.to_list(length=max_results)
135 |
136 | return files, next_offset
137 |
138 |
139 | async def get_filter_results(query):
140 | query = query.strip()
141 | if not query:
142 | raw_pattern = '.'
143 | elif ' ' not in query:
144 | raw_pattern = r'(\b|[\.\+\-_])' + query + r'(\b|[\.\+\-_])'
145 | else:
146 | raw_pattern = query.replace(' ', r'.*[\s\.\+\-_]')
147 | try:
148 | regex = re.compile(raw_pattern, flags=re.IGNORECASE)
149 | except:
150 | return []
151 | filter = {'file_name': regex}
152 | total_results = await Media.count_documents(filter)
153 | cursor = Media.find(filter)
154 | cursor.sort('$natural', -1)
155 | files = await cursor.to_list(length=int(total_results))
156 | return files
157 |
158 | async def get_file_details(query):
159 | filter = {'file_id': query}
160 | cursor = Media.find(filter)
161 | filedetails = await cursor.to_list(length=1)
162 | return filedetails
163 |
164 |
165 | async def is_subscribed(bot, query):
166 | try:
167 | user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id)
168 | except UserNotParticipant:
169 | pass
170 | except Exception as e:
171 | logger.exception(e)
172 | else:
173 | if user.status != 'kicked':
174 | return True
175 |
176 | return False
177 |
178 | async def get_poster(movie):
179 | extract = PTN.parse(movie)
180 | try:
181 | title=extract["title"]
182 | except KeyError:
183 | title=movie
184 | try:
185 | year=extract["year"]
186 | year=int(year)
187 | except KeyError:
188 | year=None
189 | if year:
190 | filter = {'$and': [{'title': str(title).lower().strip()}, {'year': int(year)}]}
191 | else:
192 | filter = {'title': str(title).lower().strip()}
193 | cursor = Poster.find(filter)
194 | is_in_db = await cursor.to_list(length=1)
195 | poster=None
196 | if is_in_db:
197 | for nyav in is_in_db:
198 | poster=nyav.poster
199 | else:
200 | if year:
201 | url=f'https://www.omdbapi.com/?s={title}&y={year}&apikey={API_KEY}'
202 | else:
203 | url=f'https://www.omdbapi.com/?s={title}&apikey={API_KEY}'
204 | try:
205 | n = requests.get(url)
206 | a = json.loads(n.text)
207 | if a["Response"] == 'True':
208 | y = a.get("Search")[0]
209 | v=y.get("Title").lower().strip()
210 | poster = y.get("Poster")
211 | year=y.get("Year")[:4]
212 | id=y.get("imdbID")
213 | await get_all(a.get("Search"))
214 | except Exception as e:
215 | logger.exception(e)
216 | return poster
217 |
218 |
219 | async def get_all(list):
220 | for y in list:
221 | v=y.get("Title").lower().strip()
222 | poster = y.get("Poster")
223 | year=y.get("Year")[:4]
224 | id=y.get("imdbID")
225 | await save_poster(id, v, year, poster)
226 |
227 |
228 | def encode_file_id(s: bytes) -> str:
229 | r = b""
230 | n = 0
231 |
232 | for i in s + bytes([22]) + bytes([4]):
233 | if i == 0:
234 | n += 1
235 | else:
236 | if n:
237 | r += b"\x00" + bytes([n])
238 | n = 0
239 |
240 | r += bytes([i])
241 |
242 | return base64.urlsafe_b64encode(r).decode().rstrip("=")
243 |
244 |
245 | def encode_file_ref(file_ref: bytes) -> str:
246 | return base64.urlsafe_b64encode(file_ref).decode().rstrip("=")
247 |
248 |
249 | def unpack_new_file_id(new_file_id):
250 | """Return file_id, file_ref"""
251 | decoded = FileId.decode(new_file_id)
252 | file_id = encode_file_id(
253 | pack(
254 | " 1 and cmd.command[1] == 'subscribe':
82 | invite_link = await bot.create_chat_invite_link(int(AUTH_CHANNEL))
83 | await bot.send_message(
84 | chat_id=cmd.from_user.id,
85 | text="**Please Join My Updates Channel to use this Bot!**",
86 | reply_markup=InlineKeyboardMarkup(
87 | [
88 | [
89 | InlineKeyboardButton("🤖 Join Updates Channel", url=invite_link.invite_link)
90 | ]
91 | ]
92 | )
93 | )
94 | else:
95 | await cmd.reply_text(
96 | START_MSG,
97 | parse_mode="Markdown",
98 | disable_web_page_preview=True,
99 | reply_markup=InlineKeyboardMarkup(
100 | [
101 | [
102 | InlineKeyboardButton("Search Here", url='https://t.me/slmovieshubsl'),
103 | InlineKeyboardButton("Source Code", url='https://github.com/kalanakt/imdb-autofilter-bot'),
104 | ],
105 | [
106 | InlineKeyboardButton("Series Channel", url='https://t.me/timelytvshow'),
107 | InlineKeyboardButton("Support Group", url='https://t.me/slmovieshubsl'),
108 | ],
109 | [
110 | InlineKeyboardButton("About", callback_data="about")
111 | ]
112 | ]
113 | )
114 | )
115 |
116 |
117 | @Client.on_message(filters.command('channel') & filters.user(ADMINS))
118 | async def channel_info(bot, message):
119 | """Send basic information of channel"""
120 | if isinstance(CHANNELS, (int, str)):
121 | channels = [CHANNELS]
122 | elif isinstance(CHANNELS, list):
123 | channels = CHANNELS
124 | else:
125 | raise ValueError("Unexpected type of CHANNELS")
126 |
127 | text = '📑 **Indexed channels/groups**\n'
128 | for channel in channels:
129 | chat = await bot.get_chat(channel)
130 | if chat.username:
131 | text += '\n@' + chat.username
132 | else:
133 | text += '\n' + chat.title or chat.first_name
134 |
135 | text += f'\n\n**Total:** {len(CHANNELS)}'
136 |
137 | if len(text) < 4096:
138 | await message.reply(text)
139 | else:
140 | file = 'Indexed channels.txt'
141 | with open(file, 'w') as f:
142 | f.write(text)
143 | await message.reply_document(file)
144 | os.remove(file)
145 |
146 |
147 | @Client.on_message(filters.command('total') & filters.user(ADMINS))
148 | async def total(bot, message):
149 | """Show total files in database"""
150 | msg = await message.reply("Processing...⏳", quote=True)
151 | try:
152 | total = await Media.count_documents()
153 | await msg.edit(f'📁 Saved files: {total}')
154 | except Exception as e:
155 | logger.exception('Failed to check total files')
156 | await msg.edit(f'Error: {e}')
157 |
158 |
159 | @Client.on_message(filters.command('logger') & filters.user(ADMINS))
160 | async def log_file(bot, message):
161 | """Send log file"""
162 | try:
163 | await message.reply_document('TelegramBot.log')
164 | except Exception as e:
165 | await message.reply(str(e))
166 |
167 |
168 | @Client.on_message(filters.command('delete') & filters.user(ADMINS))
169 | async def delete(bot, message):
170 | """Delete file from database"""
171 | reply = message.reply_to_message
172 | if reply and reply.media:
173 | msg = await message.reply("Processing...⏳", quote=True)
174 | else:
175 | await message.reply('Reply to file with /delete which you want to delete', quote=True)
176 | return
177 |
178 | for file_type in ("document", "video", "audio"):
179 | media = getattr(reply, file_type, None)
180 | if media is not None:
181 | break
182 | else:
183 | await msg.edit('This is not supported file format')
184 | return
185 |
186 | result = await Media.collection.delete_one({
187 | 'file_name': media.file_name,
188 | 'file_size': media.file_size,
189 | 'mime_type': media.mime_type
190 | })
191 | if result.deleted_count:
192 | await msg.edit('File is successfully deleted from database')
193 | else:
194 | await msg.edit('File not found in database')
195 | @Client.on_message(filters.command('about'))
196 | async def bot_info(bot, message):
197 | buttons = [
198 | [
199 | InlineKeyboardButton('Series Channel', url='https://t.me/timelytvshow'),
200 | InlineKeyboardButton('Source Code', url='https://github.com/kalanakt/imdb-autofilter-bot')
201 | ]
202 | ]
203 |
204 | await message.reply(text="Reverse Developer : Hash Minner\nLanguage : Python3\nLibrary : Pyrogram asyncio\nSource Code : Click here\nUpdate Channel : ErrorXBotz ", reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True)
205 |
--------------------------------------------------------------------------------
/plugins/pm_filter.py:
--------------------------------------------------------------------------------
1 | #Kanged From @TroJanZheX
2 | from info import AUTH_CHANNEL, AUTH_USERS, CUSTOM_FILE_CAPTION, API_KEY, AUTH_GROUPS
3 | from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
4 | from pyrogram import Client, filters
5 | import re
6 | import random
7 | from pyrogram.errors import UserNotParticipant
8 | from utils import get_filter_results, get_file_details, is_subscribed, get_poster
9 | BUTTONS = {}
10 | BOT = {}
11 |
12 | RATING = ["5.1 | IMDB", "6.2 | IMDB", "7.3 | IMDB", "8.4 | IMDB", "9.5 | IMDB", ]
13 | GENRES = ["fun, fact",
14 | "Thriller, Comedy",
15 | "Drama, Comedy",
16 | "Family, Drama",
17 | "Action, Adventure",
18 | "Film Noir",
19 | "Documentary"]
20 |
21 | @Client.on_message(filters.text & filters.private & filters.incoming & filters.user(AUTH_USERS) if AUTH_USERS else filters.text & filters.private & filters.incoming)
22 | async def filter(client, message):
23 | if message.text.startswith("/"):
24 | return
25 | if AUTH_CHANNEL:
26 | invite_link = await client.create_chat_invite_link(int(AUTH_CHANNEL))
27 | try:
28 | user = await client.get_chat_member(int(AUTH_CHANNEL), message.from_user.id)
29 | if user.status == "kicked":
30 | await client.send_message(
31 | chat_id=message.from_user.id,
32 | text="Sorry Sir, You are Banned to use me.",
33 | parse_mode="markdown",
34 | disable_web_page_preview=True
35 | )
36 | return
37 | except UserNotParticipant:
38 | await client.send_message(
39 | chat_id=message.from_user.id,
40 | text="**Please Join My Updates Channel to use this Bot!**",
41 | reply_markup=InlineKeyboardMarkup(
42 | [
43 | [
44 | InlineKeyboardButton("🤖 Join Updates Channel", url=invite_link.invite_link)
45 | ]
46 | ]
47 | ),
48 | parse_mode="markdown"
49 | )
50 | return
51 | except Exception:
52 | await client.send_message(
53 | chat_id=message.from_user.id,
54 | text="Something went Wrong.",
55 | parse_mode="markdown",
56 | disable_web_page_preview=True
57 | )
58 | return
59 | if re.findall("((^\/|^,|^!|^\.|^[\U0001F600-\U000E007F]).*)", message.text):
60 | return
61 | if 2 < len(message.text) < 100:
62 | btn = []
63 | search = message.text
64 | files = await get_filter_results(query=search)
65 | if files:
66 | for file in files:
67 | file_id = file.file_id
68 | filename = f"[{get_size(file.file_size)}] {file.file_name}"
69 | btn.append(
70 | [InlineKeyboardButton(text=f"{filename}",callback_data=f"subinps#{file_id}")]
71 | )
72 | else:
73 | await client.send_sticker(chat_id=message.from_user.id, sticker='CAADBQADMwIAAtbcmFelnLaGAZhgBwI')
74 | return
75 |
76 | if not btn:
77 | return
78 |
79 | if len(btn) > 10:
80 | btns = list(split_list(btn, 10))
81 | keyword = f"{message.chat.id}-{message.message_id}"
82 | BUTTONS[keyword] = {
83 | "total" : len(btns),
84 | "buttons" : btns
85 | }
86 | else:
87 | buttons = btn
88 | buttons.append(
89 | [InlineKeyboardButton(text="📜 Pages 1/1",callback_data="pages")]
90 | )
91 | poster=None
92 | if API_KEY:
93 | poster=await get_poster(search)
94 | if poster:
95 | await message.reply_photo(photo=poster, caption=f"Here is What I Found In My Database For Your Request {search} ", reply_markup=InlineKeyboardMarkup(buttons))
96 |
97 | else:
98 | await message.reply_text(f"Here is What I Found In My Database For Your Request {search} ", reply_markup=InlineKeyboardMarkup(buttons))
99 | return
100 |
101 | data = BUTTONS[keyword]
102 | buttons = data['buttons'][0].copy()
103 |
104 | buttons.append(
105 | [InlineKeyboardButton(text="NEXT »»",callback_data=f"next_0_{keyword}")]
106 | )
107 | buttons.append(
108 | [InlineKeyboardButton(text=f"📃 Pages 1/{data['total']}",callback_data="pages")]
109 | )
110 | poster=None
111 | if API_KEY:
112 | poster=await get_poster(search)
113 | if poster:
114 | await message.reply_photo(photo=poster, caption=f"Here is What I Found In My Database For Your Request {search} ", reply_markup=InlineKeyboardMarkup(buttons))
115 | else:
116 | await message.reply_text(f"Here is What I Found In My Database For Your Request{search} ", reply_markup=InlineKeyboardMarkup(buttons))
117 |
118 | @Client.on_message(filters.text & filters.group & filters.incoming & filters.chat(AUTH_GROUPS) if AUTH_GROUPS else filters.text & filters.group & filters.incoming)
119 | async def group(client, message):
120 | if re.findall("((^\/|^,|^!|^\.|^[\U0001F600-\U000E007F]).*)", message.text):
121 | return
122 | if 2 < len(message.text) < 50:
123 | btn = []
124 |
125 | search = message.text
126 | result_txt = f"**🎬 Title:** {search}\n**🌟 Rating:** {random.choice(RATING)}\n**🎭 Genre:** {random.choice(GENRES)}\n**©️ {message.chat.title} 🍿**"
127 |
128 | nyva=BOT.get("username")
129 | if not nyva:
130 | botusername=await client.get_me()
131 | nyva=botusername.username
132 | BOT["username"]=nyva
133 | files = await get_filter_results(query=search)
134 | if not files:
135 | return
136 | for file in files:
137 | file_id = file.file_id
138 | filename = f"🎬 [{get_size(file.file_size)}] 🎥 {file.file_name}"
139 | btn.append(
140 | [InlineKeyboardButton(text=f"{filename}", url=f"https://telegram.dog/{nyva}?start=subinps_-_-_-_{file_id}")]
141 | )
142 | if not btn:
143 | return
144 |
145 | if len(btn) > 10:
146 | btns = list(split_list(btn, 10))
147 | keyword = f"{message.chat.id}-{message.message_id}"
148 | BUTTONS[keyword] = {
149 | "total" : len(btns),
150 | "buttons" : btns
151 | }
152 | else:
153 | buttons = btn
154 | buttons.append(
155 | [InlineKeyboardButton(text="📜 Pages 1/1",callback_data="pages")]
156 | )
157 | poster=None
158 | if API_KEY:
159 | poster=await get_poster(search)
160 | if poster:
161 | await message.reply_photo(photo=poster, caption=result_txt, reply_markup=InlineKeyboardMarkup(buttons))
162 | else:
163 | await message.reply_text(result_txt, reply_markup=InlineKeyboardMarkup(buttons))
164 | return
165 |
166 | data = BUTTONS[keyword]
167 | buttons = data['buttons'][0].copy()
168 |
169 | buttons.append(
170 | [InlineKeyboardButton(text="NEXT »»",callback_data=f"next_0_{keyword}")]
171 | )
172 | buttons.append(
173 | [InlineKeyboardButton(text=f"📜 Pages 1/{data['total']}",callback_data="pages")]
174 | )
175 | poster=None
176 | if API_KEY:
177 | poster=await get_poster(search)
178 | if poster:
179 | await message.reply_photo(photo=poster, caption=result_txt, reply_markup=InlineKeyboardMarkup(buttons))
180 | else:
181 | await message.reply_text(result_txt, reply_markup=InlineKeyboardMarkup(buttons))
182 |
183 |
184 | def get_size(size):
185 | """Get size in readable format"""
186 |
187 | units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
188 | size = float(size)
189 | i = 0
190 | while size >= 1024.0 and i < len(units):
191 | i += 1
192 | size /= 1024.0
193 | return "%.2f %s" % (size, units[i])
194 |
195 | def split_list(l, n):
196 | for i in range(0, len(l), n):
197 | yield l[i:i + n]
198 |
199 |
200 |
201 | @Client.on_callback_query()
202 | async def cb_handler(client: Client, query: CallbackQuery):
203 | clicked = query.from_user.id
204 | try:
205 | typed = query.message.reply_to_message.from_user.id
206 | except:
207 | typed = query.from_user.id
208 | if (clicked == typed):
209 |
210 | if query.data.startswith("next"):
211 | ident, index, keyword = query.data.split("_")
212 | try:
213 | data = BUTTONS[keyword]
214 | except KeyError:
215 | await query.answer("You are using this for one of my old message, please send the request again.",show_alert=True)
216 | return
217 |
218 | if int(index) == int(data["total"]) - 2:
219 | buttons = data['buttons'][int(index)+1].copy()
220 |
221 | buttons.append(
222 | [InlineKeyboardButton("«« BACK", callback_data=f"back_{int(index)+1}_{keyword}")]
223 | )
224 | else:
225 | buttons = data['buttons'][int(index)+1].copy()
226 |
227 | buttons.append(
228 | [InlineKeyboardButton("«« BACK", callback_data=f"back_{int(index)+1}_{keyword}"),InlineKeyboardButton("NEXT »»", callback_data=f"next_{int(index)+1}_{keyword}")]
229 | )
230 | buttons.append(
231 | [InlineKeyboardButton(f"📜 Pages {int(index)+2}/{data['total']}", callback_data="pages")]
232 | )
233 |
234 | await query.edit_message_reply_markup(
235 | reply_markup=InlineKeyboardMarkup(buttons)
236 | )
237 | return
238 | elif query.data.startswith("back"):
239 | ident, index, keyword = query.data.split("_")
240 | try:
241 | data = BUTTONS[keyword]
242 | except KeyError:
243 | await query.answer("You are using this for one of my old message, please send the request again.",show_alert=True)
244 | return
245 |
246 | if int(index) == 1:
247 | buttons = data['buttons'][int(index)-1].copy()
248 |
249 | buttons.append(
250 | [InlineKeyboardButton("NEXT »»", callback_data=f"next_{int(index)-1}_{keyword}")]
251 | )
252 | buttons.append(
253 | [InlineKeyboardButton(f"📜 Pages {int(index)}/{data['total']}", callback_data="pages")]
254 | )
255 |
256 | else:
257 | buttons = data['buttons'][int(index)-1].copy()
258 |
259 | buttons.append(
260 | [InlineKeyboardButton("«« BACK", callback_data=f"back_{int(index)-1}_{keyword}"),InlineKeyboardButton("NEXT »»", callback_data=f"next_{int(index)-1}_{keyword}")]
261 | )
262 | buttons.append(
263 | [InlineKeyboardButton(f"📃 Pages {int(index)}/{data['total']}", callback_data="pages")]
264 | )
265 |
266 | await query.edit_message_reply_markup(
267 | reply_markup=InlineKeyboardMarkup(buttons)
268 | )
269 | return
270 | elif query.data == "about":
271 | buttons = [
272 | [
273 | InlineKeyboardButton('Bot Help', url='https://t.me/kinu6'),
274 | ]
275 | ]
276 | await query.message.edit(text="Reverse Deverloper : Hash Minner\nLanguage : Python3\nLibrary : Pyrogram asyncio\n Update Channel : Bot Support ", reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True)
277 |
278 |
279 |
280 | elif query.data.startswith("subinps"):
281 | ident, file_id = query.data.split("#")
282 | filedetails = await get_file_details(file_id)
283 | for files in filedetails:
284 | title = files.file_name
285 | size=files.file_size
286 | f_caption=files.caption
287 | if CUSTOM_FILE_CAPTION:
288 | try:
289 | f_caption=CUSTOM_FILE_CAPTION.format(file_name=title, file_size=size, file_caption=f_caption)
290 | except Exception as e:
291 | print(e)
292 | f_caption=f_caption
293 | if f_caption is None:
294 | f_caption = f"{files.file_name}"
295 | buttons = [
296 | [
297 | InlineKeyboardButton(' Updates ', url='https://t.me/Series2Day'),
298 | ]
299 | ]
300 |
301 | await query.answer()
302 | await client.send_cached_media(
303 | chat_id=query.from_user.id,
304 | file_id=file_id,
305 | caption=f_caption,
306 | reply_markup=InlineKeyboardMarkup(buttons)
307 | )
308 | elif query.data.startswith("checksub"):
309 | if AUTH_CHANNEL and not await is_subscribed(client, query):
310 | await query.answer("I Like Your Smartness, But Don't Be Oversmart 😒",show_alert=True)
311 | return
312 | ident, file_id = query.data.split("#")
313 | filedetails = await get_file_details(file_id)
314 | for files in filedetails:
315 | title = files.file_name
316 | size=files.file_size
317 | f_caption=files.caption
318 | if CUSTOM_FILE_CAPTION:
319 | try:
320 | f_caption=CUSTOM_FILE_CAPTION.format(file_name=title, file_size=size, file_caption=f_caption)
321 | except Exception as e:
322 | print(e)
323 | f_caption=f_caption
324 | if f_caption is None:
325 | f_caption = f"{title}"
326 | buttons = [
327 | [
328 | InlineKeyboardButton('Group', url='https://t.me/slmovieshubsl '),
329 | InlineKeyboardButton('Tv Series', url='https://t.me/timelytvshow'),
330 | ]
331 | ]
332 |
333 | await query.answer()
334 | await client.send_cached_media(
335 | chat_id=query.from_user.id,
336 | file_id=file_id,
337 | caption=f_caption,
338 | reply_markup=InlineKeyboardMarkup(buttons)
339 | )
340 |
341 |
342 | elif query.data == "pages":
343 | await query.answer()
344 | else:
345 | await query.answer("it's not for you. 🤭😝",show_alert=True)
346 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 |
294 | Copyright (C)
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | , 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------