├── .gitignore ├── Config.py ├── Database ├── Database.py └── __init__.py ├── Dockerfile ├── LICENSE ├── LuciferMoringstar_Robot ├── Broadcast │ ├── Broadcast.py │ └── __init__.py ├── Channel │ ├── Channel.py │ ├── Index.py │ ├── Log_Channel.py │ └── __init__.py ├── Commands.py ├── Filter │ ├── Inline.py │ └── Main.py ├── Utils.py └── __init__.py ├── Procfile ├── README.md ├── app.json ├── logging.conf ├── mt_botz.py ├── requirements.txt ├── runtime.txt └── sample_info.py /.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 | -------------------------------------------------------------------------------- /Config.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | from os import environ 4 | 5 | id_pattern = re.compile(r'^.\d+$') 6 | 7 | # Bot information 8 | SESSION = environ.get('SESSION', 'LuciferMoringstar_Robot') 9 | API_ID = int(environ['API_ID']) 10 | API_HASH = environ['API_HASH'] 11 | BOT_TOKEN = environ['BOT_TOKEN'] 12 | 13 | # Bot settings 14 | CACHE_TIME = int(environ.get('CACHE_TIME', 300)) 15 | USE_CAPTION_FILTER = bool(environ.get('USE_CAPTION_FILTER', False)) 16 | 17 | BROADCAST_CHANNEL = int(os.environ.get("BROADCAST_CHANNEL", "")) 18 | ADMIN_ID = set(int(x) for x in os.environ.get("ADMIN_ID", "").split()) 19 | DB_URL = os.environ.get("DATABASE_1", "") 20 | BROADCAST_AS_COPY = bool(os.environ.get("BROADCAST", True)) 21 | 22 | # Admins, Channels & Users 23 | ADMINS = [int(admin) if id_pattern.search(admin) else admin for admin in environ['ADMINS'].split()] 24 | CHANNELS = [int(ch) if id_pattern.search(ch) else ch for ch in environ['CHANNELS'].split()] 25 | auth_users = [int(user) if id_pattern.search(user) else user for user in environ.get('AUTH_USERS', '').split()] 26 | AUTH_USERS = (auth_users + ADMINS) if auth_users else [] 27 | auth_channel = environ.get('FORCES_SUB') 28 | AUTH_CHANNEL = int(auth_channel) if auth_channel and id_pattern.search(auth_channel) else auth_channel 29 | AUTH_GROUPS = [int(admin) for admin in environ.get("AUTH_GROUPS", "").split()] 30 | TUTORIAL = "https://youtu.be/5hnYOKBzyi8" 31 | # MongoDB information 32 | DATABASE_URI = environ['DATABASE_2'] 33 | DATABASE_NAME = environ['BOT_NAME'] 34 | COLLECTION_NAME = environ.get('COLLECTION_NAME', 'Telegram_files') 35 | 36 | # Messages 37 | default_start_msg = """ 38 | **Hi, I'm Auto Filter V3** 39 | 40 | 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. 41 | """ 42 | START_MSG = environ.get('START_MSG', default_start_msg) 43 | 44 | FILE_CAPTION = environ.get("CUSTOM_FILE_CAPTION", "") 45 | OMDB_API_KEY = environ.get("OMDB_API_KEY", "http://www.omdbapi.com/?i=tt3896198&apikey=4f08a979") 46 | if FILE_CAPTION.strip() == "": 47 | CUSTOM_FILE_CAPTION=None 48 | else: 49 | CUSTOM_FILE_CAPTION=FILE_CAPTION 50 | if OMDB_API_KEY.strip() == "": 51 | API_KEY=None 52 | else: 53 | API_KEY=OMDB_API_KEY 54 | -------------------------------------------------------------------------------- /Database/Database.py: -------------------------------------------------------------------------------- 1 | # (c) PR0FESS0R-99 2 | 3 | import datetime 4 | 5 | import motor.motor_asyncio 6 | 7 | class Database: 8 | def __init__(self, uri, database_name): 9 | self._client = motor.motor_asyncio.AsyncIOMotorClient(uri) 10 | self.db = self._client[database_name] 11 | self.col = self.db.users 12 | 13 | def new_user(self, id): 14 | return dict( 15 | id=id, 16 | join_date=datetime.date.today().isoformat(), 17 | notif=True, 18 | ban_status=dict( 19 | is_banned=False, 20 | ban_duration=0, 21 | banned_on=datetime.date.max.isoformat(), 22 | ban_reason="", 23 | ), 24 | ) 25 | 26 | async def add_user(self, id): 27 | user = self.new_user(id) 28 | await self.col.insert_one(user) 29 | 30 | async def is_user_exist(self, id): 31 | user = await self.col.find_one({"id": int(id)}) 32 | return True if user else False 33 | 34 | async def total_users_count(self): 35 | count = await self.col.count_documents({}) 36 | return count 37 | 38 | async def get_all_users(self): 39 | all_users = self.col.find({}) 40 | return all_users 41 | 42 | async def delete_user(self, user_id): 43 | await self.col.delete_many({"id": int(user_id)}) 44 | 45 | async def remove_ban(self, id): 46 | ban_status = dict( 47 | is_banned=False, 48 | ban_duration=0, 49 | banned_on=datetime.date.max.isoformat(), 50 | ban_reason="", 51 | ) 52 | await self.col.update_one({"id": id}, {"$set": {"ban_status": ban_status}}) 53 | 54 | async def ban_user(self, user_id, ban_duration, ban_reason): 55 | ban_status = dict( 56 | is_banned=True, 57 | ban_duration=ban_duration, 58 | banned_on=datetime.date.today().isoformat(), 59 | ban_reason=ban_reason, 60 | ) 61 | await self.col.update_one({"id": user_id}, {"$set": {"ban_status": ban_status}}) 62 | 63 | async def get_ban_status(self, id): 64 | default = dict( 65 | is_banned=False, 66 | ban_duration=0, 67 | banned_on=datetime.date.max.isoformat(), 68 | ban_reason="", 69 | ) 70 | user = await self.col.find_one({"id": int(id)}) 71 | return user.get("ban_status", default) 72 | 73 | async def get_all_banned_users(self): 74 | banned_users = self.col.find({"ban_status.is_banned": True}) 75 | return banned_users 76 | 77 | async def set_notif(self, id, notif): 78 | await self.col.update_one({"id": id}, {"$set": {"notif": notif}}) 79 | 80 | async def get_notif(self, id): 81 | user = await self.col.find_one({"id": int(id)}) 82 | return user.get("notif", False) 83 | 84 | async def get_all_notif_user(self): 85 | notif_users = self.col.find({"notif": True}) 86 | return notif_users 87 | 88 | async def total_notif_users_count(self): 89 | count = await self.col.count_documents({"notif": True}) 90 | return count 91 | -------------------------------------------------------------------------------- /Database/__init__.py: -------------------------------------------------------------------------------- 1 | from .Database import Database 2 | -------------------------------------------------------------------------------- /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 mt_botz.py 9 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /LuciferMoringstar_Robot/Broadcast/Broadcast.py: -------------------------------------------------------------------------------- 1 | # (c) PR0FESS0R-99 2 | 3 | import asyncio 4 | import datetime 5 | import os 6 | import random 7 | import string 8 | import time 9 | import traceback 10 | 11 | import aiofiles 12 | from pyrogram.errors import ( 13 | FloodWait, 14 | InputUserDeactivated, 15 | PeerIdInvalid, 16 | UserIsBlocked, 17 | ) 18 | 19 | from Config import BROADCAST_AS_COPY 20 | 21 | broadcast_ids = {} 22 | 23 | BROADCAST_AS_COPY = BROADCAST_AS_COPY 24 | 25 | 26 | async def send_msg(user_id, message): 27 | try: 28 | if BROADCAST_AS_COPY is False: 29 | await message.forward(chat_id=user_id) 30 | elif BROADCAST_AS_COPY is True: 31 | await message.copy(chat_id=user_id) 32 | return 200, None 33 | except FloodWait as e: 34 | await asyncio.sleep(e.x) 35 | return send_msg(user_id, message) 36 | except InputUserDeactivated: 37 | return 400, f"{user_id} : deactivated\n" 38 | except UserIsBlocked: 39 | return 400, f"{user_id} : blocked the bot\n" 40 | except PeerIdInvalid: 41 | return 400, f"{user_id} : user id invalid\n" 42 | except Exception: 43 | return 500, f"{user_id} : {traceback.format_exc()}\n" 44 | 45 | 46 | async def broadcast(m, db): 47 | all_users = await db.get_all_notif_user() 48 | broadcast_msg = m.reply_to_message 49 | while True: 50 | broadcast_id = "".join([random.choice(string.ascii_letters) for i in range(3)]) 51 | if not broadcast_ids.get(broadcast_id): 52 | break 53 | out = await m.reply_text( 54 | text=f"Broadcast Started! You will be notified with log file when all the users are notified." 55 | ) 56 | start_time = time.time() 57 | total_users = await db.total_users_count() 58 | done = 0 59 | failed = 0 60 | success = 0 61 | broadcast_ids[broadcast_id] = dict( 62 | total=total_users, current=done, failed=failed, success=success 63 | ) 64 | async with aiofiles.open("broadcast.txt", "w") as broadcast_log_file: 65 | async for user in all_users: 66 | sts, msg = await send_msg(user_id=int(user["id"]), message=broadcast_msg) 67 | if msg is not None: 68 | await broadcast_log_file.write(msg) 69 | if sts == 200: 70 | success += 1 71 | else: 72 | failed += 1 73 | if sts == 400: 74 | await db.delete_user(user["id"]) 75 | done += 1 76 | if broadcast_ids.get(broadcast_id) is None: 77 | break 78 | else: 79 | broadcast_ids[broadcast_id].update( 80 | dict(current=done, failed=failed, success=success) 81 | ) 82 | if broadcast_ids.get(broadcast_id): 83 | broadcast_ids.pop(broadcast_id) 84 | completed_in = datetime.timedelta(seconds=int(time.time() - start_time)) 85 | await asyncio.sleep(3) 86 | await out.delete() 87 | if failed == 0: 88 | await m.reply_text( 89 | text=f"broadcast completed in `{completed_in}`\n\nTotal users {total_users}.\nTotal done {done}, {success} success and {failed} failed.", 90 | quote=True, 91 | ) 92 | else: 93 | await m.reply_document( 94 | document="broadcast.txt", 95 | caption=f"broadcast completed in `{completed_in}`\n\nTotal users {total_users}.\nTotal done {done}, {success} success and {failed} failed.", 96 | quote=True, 97 | ) 98 | os.remove("broadcast.txt") 99 | -------------------------------------------------------------------------------- /LuciferMoringstar_Robot/Broadcast/__init__.py: -------------------------------------------------------------------------------- 1 | from .Broadcast import broadcast 2 | -------------------------------------------------------------------------------- /LuciferMoringstar_Robot/Channel/Channel.py: -------------------------------------------------------------------------------- 1 | from pyrogram import Client, filters 2 | from LuciferMoringstar_Robot.Utils import save_file 3 | from Config 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 | -------------------------------------------------------------------------------- /LuciferMoringstar_Robot/Channel/Index.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import asyncio 3 | from pyrogram import Client, filters 4 | from pyrogram.errors import FloodWait 5 | from Config import ADMINS 6 | import os 7 | from LuciferMoringstar_Robot.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 | if last_msg.forward_from_chat.username: 24 | chat_id = last_msg.forward_from_chat.username 25 | else: 26 | chat_id=last_msg.forward_from_chat.id 27 | await bot.get_messages(chat_id, last_msg_id) 28 | break 29 | except Exception as e: 30 | 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}") 31 | continue 32 | 33 | msg = await message.reply('Processing...⏳') 34 | total_files = 0 35 | async with lock: 36 | try: 37 | total=last_msg_id + 1 38 | current=int(os.environ.get("SKIP", 2)) 39 | nyav=0 40 | while True: 41 | try: 42 | message = await bot.get_messages(chat_id=chat_id, message_ids=current, replies=0) 43 | except FloodWait as e: 44 | await asyncio.sleep(e.x) 45 | message = await bot.get_messages( 46 | chat_id, 47 | current, 48 | replies=0 49 | ) 50 | except Exception as e: 51 | print(e) 52 | pass 53 | try: 54 | for file_type in ("document", "video", "audio"): 55 | media = getattr(message, file_type, None) 56 | if media is not None: 57 | break 58 | else: 59 | continue 60 | media.file_type = file_type 61 | media.caption = message.caption 62 | await save_file(media) 63 | total_files += 1 64 | except Exception as e: 65 | print(e) 66 | pass 67 | current+=1 68 | nyav+=1 69 | if nyav == 20: 70 | await msg.edit(f"Total messages fetched: {current}\nTotal messages saved: {total_files}") 71 | nyav -= 20 72 | if current == total: 73 | break 74 | else: 75 | continue 76 | except Exception as e: 77 | logger.exception(e) 78 | await msg.edit(f'Error: {e}') 79 | else: 80 | await msg.edit(f'Total {total_files} Saved To DataBase!') 81 | 82 | RATING = ["5.1 | IMDB", "6.2 | IMDB", "7.3 | IMDB", "8.4 | IMDB", "9.5 | IMDB", ] 83 | GENRES = ["fun, fact", 84 | "Thriller, Comedy", 85 | "Drama, Comedy", 86 | "Family, Drama", 87 | "Action, Adventure", 88 | "Film Noir", 89 | "Documentary"] 90 | -------------------------------------------------------------------------------- /LuciferMoringstar_Robot/Channel/Log_Channel.py: -------------------------------------------------------------------------------- 1 | # (c) PR0FESS0R-99 2 | 3 | import datetime 4 | 5 | from Config import DB_URL, SESSION 6 | from Database import Database 7 | 8 | db = Database(DB_URL, SESSION) 9 | 10 | 11 | async def handle_user_status(bot, cmd): 12 | chat_id = cmd.from_user.id 13 | if not await db.is_user_exist(chat_id): 14 | data = await bot.get_me() 15 | BOT_USERNAME = data.username 16 | await db.add_user(chat_id) 17 | await bot.send_message( 18 | LOG_CHANNEL, 19 | f"#NEWUSER: \n\nNew User [{cmd.from_user.first_name}](tg://user?id={cmd.from_user.id}) started @{BOT_USERNAME} !!", 20 | ) 21 | 22 | ban_status = await db.get_ban_status(chat_id) 23 | if ban_status["is_banned"]: 24 | if ( 25 | datetime.date.today() - datetime.date.fromisoformat(ban_status["banned_on"]) 26 | ).days > ban_status["ban_duration"]: 27 | await db.remove_ban(chat_id) 28 | else: 29 | await cmd.reply_text("You are Banned to Use This Bot ", quote=True) 30 | return 31 | await cmd.continue_propagation() 32 | -------------------------------------------------------------------------------- /LuciferMoringstar_Robot/Channel/__init__.py: -------------------------------------------------------------------------------- 1 | from .Log_Channel import ( 2 | handle_user_status 3 | ) 4 | from .Index import ( 5 | RATING, 6 | GENRES 7 | ) 8 | -------------------------------------------------------------------------------- /LuciferMoringstar_Robot/Commands.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | from pyrogram import Client, filters 4 | from pyrogram import StopPropagation 5 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup 6 | from Config import START_MSG, CHANNELS, ADMINS, AUTH_CHANNEL, CUSTOM_FILE_CAPTION, TUTORIAL, BROADCAST_CHANNEL, DB_URL, SESSION, ADMIN_ID 7 | from LuciferMoringstar_Robot.Utils import Media, get_file_details 8 | from LuciferMoringstar_Robot.Broadcast import broadcast 9 | from LuciferMoringstar_Robot import ABOUT 10 | from LuciferMoringstar_Robot.Channel import handle_user_status 11 | from Database import Database 12 | from pyrogram.errors import UserNotParticipant 13 | logger = logging.getLogger(__name__) 14 | 15 | LOG_CHANNEL = BROADCAST_CHANNEL 16 | 17 | db = Database(DB_URL, SESSION) 18 | 19 | @Client.on_message(filters.command("start")) 20 | async def start(bot, message): 21 | chat_id = message.from_user.id 22 | if not await db.is_user_exist(chat_id): 23 | data = await bot.get_me() 24 | BOT_USERNAME = data.username 25 | await db.add_user(chat_id) 26 | await bot.send_message( 27 | LOG_CHANNEL, 28 | f"#NEWUSER: \n\nNew User [{message.from_user.first_name}](tg://user?id={message.from_user.id}) started @{BOT_USERNAME} !!", 29 | ) 30 | usr_cmdall1 = message.text 31 | if usr_cmdall1.startswith("/start pr0fess0r_99"): 32 | if AUTH_CHANNEL: 33 | invite_link = await bot.create_chat_invite_link(int(AUTH_CHANNEL)) 34 | try: 35 | user = await bot.get_chat_member(int(AUTH_CHANNEL), message.from_user.id) 36 | if user.status == "kicked": 37 | await bot.send_message( 38 | chat_id=message.from_user.id, 39 | text="Sorry Sir, You are Banned to use me.", 40 | parse_mode="markdown", 41 | disable_web_page_preview=True 42 | ) 43 | return 44 | except UserNotParticipant: 45 | ident, file_id = message.text.split("_-_-_-_") 46 | await bot.send_message( 47 | chat_id=message.from_user.id, 48 | text="**Please Join My Updates Channel to use this Bot!**", 49 | reply_markup=InlineKeyboardMarkup( 50 | [ 51 | [ 52 | InlineKeyboardButton("📢 Join Updates Channel 📢", url=invite_link.invite_link) 53 | ], 54 | [ 55 | InlineKeyboardButton("🔄 Try Again", callback_data=f"checksub#{file_id}") 56 | ] 57 | ] 58 | ), 59 | parse_mode="markdown" 60 | ) 61 | return 62 | except Exception: 63 | await bot.send_message( 64 | chat_id=message.from_user.id, 65 | text="Something went Wrong.", 66 | parse_mode="markdown", 67 | disable_web_page_preview=True 68 | ) 69 | return 70 | try: 71 | ident, file_id = message.text.split("_-_-_-_") 72 | filedetails = await get_file_details(file_id) 73 | for files in filedetails: 74 | title = files.file_name 75 | size=files.file_size 76 | f_caption=files.caption 77 | if CUSTOM_FILE_CAPTION: 78 | try: 79 | f_caption=CUSTOM_FILE_CAPTION.format(file_name=title, file_size=size, file_caption=f_caption) 80 | except Exception as e: 81 | print(e) 82 | f_caption=f_caption 83 | if f_caption is None: 84 | f_caption = f"{files.file_name}" 85 | buttons = [ 86 | [ 87 | InlineKeyboardButton('🎖 DEPLOY YOURS 🎖', url=f'{TUTORIAL}') 88 | ] 89 | ] 90 | await bot.send_cached_media( 91 | chat_id=message.from_user.id, 92 | file_id=file_id, 93 | caption=f_caption, 94 | reply_markup=InlineKeyboardMarkup(buttons) 95 | ) 96 | except Exception as err: 97 | await message.reply_text(f"Something went wrong!\n\n**Error:** `{err}`") 98 | elif len(message.command) > 1 and message.command[1] == 'subscribe': 99 | invite_link = await bot.create_chat_invite_link(int(AUTH_CHANNEL)) 100 | await bot.send_message( 101 | chat_id=message.from_user.id, 102 | text="**Please Join My Updates Channel to use this Bot!**", 103 | reply_markup=InlineKeyboardMarkup( 104 | [ 105 | [ 106 | InlineKeyboardButton("📢 Join Updates Channel 📢", url=invite_link.invite_link) 107 | ] 108 | ] 109 | ) 110 | ) 111 | else: 112 | await message.reply_text( 113 | START_MSG, 114 | parse_mode="Markdown", 115 | disable_web_page_preview=True, 116 | reply_markup=InlineKeyboardMarkup( 117 | [[ 118 | InlineKeyboardButton("Search Here", switch_inline_query_current_chat='') 119 | ],[ 120 | InlineKeyboardButton("Help", callback_data="help"), 121 | InlineKeyboardButton("About", callback_data="about") 122 | ]] 123 | ) 124 | ) 125 | StopPropagation 126 | 127 | @Client.on_message(filters.command('channel') & filters.user(ADMINS)) 128 | async def channel_info(bot, message): 129 | """Send basic information of channel""" 130 | if isinstance(CHANNELS, (int, str)): 131 | channels = [CHANNELS] 132 | elif isinstance(CHANNELS, list): 133 | channels = CHANNELS 134 | else: 135 | raise ValueError("Unexpected type of CHANNELS") 136 | 137 | text = '📑 **Indexed channels/groups**\n' 138 | for channel in channels: 139 | chat = await bot.get_chat(channel) 140 | if chat.username: 141 | text += '\n@' + chat.username 142 | else: 143 | text += '\n' + chat.title or chat.first_name 144 | 145 | text += f'\n\n**Total:** {len(CHANNELS)}' 146 | 147 | if len(text) < 4096: 148 | await message.reply(text) 149 | else: 150 | file = 'Indexed channels.txt' 151 | with open(file, 'w') as f: 152 | f.write(text) 153 | await message.reply_document(file) 154 | os.remove(file) 155 | 156 | 157 | @Client.on_message(filters.private & filters.command("broadcast")) 158 | async def broadcast_handler_open(_, m): 159 | if m.from_user.id not in ADMIN_ID: 160 | await m.delete() 161 | return 162 | if m.reply_to_message is None: 163 | await m.delete() 164 | else: 165 | await broadcast(m, db) 166 | 167 | 168 | @Client.on_message(filters.private & filters.command("stats")) 169 | async def sts(c, m): 170 | if m.from_user.id not in ADMIN_ID: 171 | await m.delete() 172 | return 173 | await m.reply_text( 174 | text=f"**Total Users in Database 📂:** `{await db.total_users_count()}`\n\n**Total Users with Notification Enabled 🔔 :** `{await db.total_notif_users_count()}`", 175 | parse_mode="Markdown", 176 | quote=True 177 | ) 178 | 179 | 180 | @Client.on_message(filters.private & filters.command("ban_user")) 181 | async def ban(c, m): 182 | if m.from_user.id not in ADMIN_ID: 183 | await m.delete() 184 | return 185 | if len(m.command) == 1: 186 | await m.reply_text( 187 | f"Use this command to ban 🛑 any user from the bot 🤖.\n\nUsage:\n\n`/ban_user user_id ban_duration ban_reason`\n\nEg: `/ban_user 1234567 28 You misused me.`\n This will ban user with id `1234567` for `28` days for the reason `You misused me`.", 188 | quote=True, 189 | ) 190 | return 191 | 192 | try: 193 | user_id = int(m.command[1]) 194 | ban_duration = int(m.command[2]) 195 | ban_reason = " ".join(m.command[3:]) 196 | ban_log_text = f"Banning user {user_id} for {ban_duration} days for the reason {ban_reason}." 197 | 198 | try: 199 | await c.send_message( 200 | user_id, 201 | f"You are Banned 🚫 to use this bot for **{ban_duration}** day(s) for the reason __{ban_reason}__ \n\n**Message from the admin 🤠**", 202 | ) 203 | ban_log_text += "\n\nUser notified successfully!" 204 | except BaseException: 205 | traceback.print_exc() 206 | ban_log_text += ( 207 | f"\n\n ⚠️ User notification failed! ⚠️ \n\n`{traceback.format_exc()}`" 208 | ) 209 | await db.ban_user(user_id, ban_duration, ban_reason) 210 | print(ban_log_text) 211 | await m.reply_text(ban_log_text, quote=True) 212 | except BaseException: 213 | traceback.print_exc() 214 | await m.reply_text( 215 | f"Error occoured ⚠️! Traceback given below\n\n`{traceback.format_exc()}`", 216 | quote=True 217 | ) 218 | 219 | 220 | @Client.on_message(filters.private & filters.command("unban_user")) 221 | async def unban(c, m): 222 | if m.from_user.id not in ADMIN_ID: 223 | await m.delete() 224 | return 225 | if len(m.command) == 1: 226 | await m.reply_text( 227 | f"Use this command to unban 😃 any user.\n\nUsage:\n\n`/unban_user user_id`\n\nEg: `/unban_user 1234567`\n This will unban user with id `1234567`.", 228 | quote=True, 229 | ) 230 | return 231 | 232 | try: 233 | user_id = int(m.command[1]) 234 | unban_log_text = f"Unbanning user 🤪 {user_id}" 235 | 236 | try: 237 | await c.send_message(user_id, f"Your ban was lifted!") 238 | unban_log_text += "\n\n✅ User notified successfully! ✅" 239 | except BaseException: 240 | traceback.print_exc() 241 | unban_log_text += ( 242 | f"\n\n⚠️ User notification failed! ⚠️\n\n`{traceback.format_exc()}`" 243 | ) 244 | await db.remove_ban(user_id) 245 | print(unban_log_text) 246 | await m.reply_text(unban_log_text, quote=True) 247 | except BaseException: 248 | traceback.print_exc() 249 | await m.reply_text( 250 | f"⚠️ Error occoured ⚠️! Traceback given below\n\n`{traceback.format_exc()}`", 251 | quote=True, 252 | ) 253 | 254 | 255 | @Client.on_message(filters.private & filters.command("banned_users")) 256 | async def _banned_usrs(c, m): 257 | if m.from_user.id not in ADMIN_ID: 258 | await m.delete() 259 | return 260 | all_banned_users = await db.get_all_banned_users() 261 | banned_usr_count = 0 262 | text = "" 263 | async for banned_user in all_banned_users: 264 | user_id = banned_user["id"] 265 | ban_duration = banned_user["ban_status"]["ban_duration"] 266 | banned_on = banned_user["ban_status"]["banned_on"] 267 | ban_reason = banned_user["ban_status"]["ban_reason"] 268 | banned_usr_count += 1 269 | text += f"> **User_id**: `{user_id}`, **Ban Duration**: `{ban_duration}`, **Banned on**: `{banned_on}`, **Reason**: `{ban_reason}`\n\n" 270 | reply_text = f"Total banned user(s) 🤭: `{banned_usr_count}`\n\n{text}" 271 | if len(reply_text) > 4096: 272 | with open("banned-users.txt", "w") as f: 273 | f.write(reply_text) 274 | await m.reply_document("banned-users.txt", True) 275 | os.remove("banned-users.txt") 276 | return 277 | await m.reply_text(reply_text, True) 278 | 279 | 280 | 281 | @Client.on_message(filters.command('total') & filters.user(ADMINS)) 282 | async def total(bot, message): 283 | """Show total files in database""" 284 | msg = await message.reply("Processing...⏳", quote=True) 285 | try: 286 | total = await Media.count_documents() 287 | await msg.edit(f'📁 Saved files: {total}') 288 | except Exception as e: 289 | logger.exception('Failed to check total files') 290 | await msg.edit(f'Error: {e}') 291 | 292 | 293 | @Client.on_message(filters.command('logger') & filters.user(ADMINS)) 294 | async def log_file(bot, message): 295 | """Send log file""" 296 | try: 297 | await message.reply_document('TelegramBot.log') 298 | except Exception as e: 299 | await message.reply(str(e)) 300 | 301 | 302 | @Client.on_message(filters.command('delete') & filters.user(ADMINS)) 303 | async def delete(bot, message): 304 | """Delete file from database""" 305 | reply = message.reply_to_message 306 | if reply and reply.media: 307 | msg = await message.reply("Processing...⏳", quote=True) 308 | else: 309 | await message.reply('Reply to file with /delete which you want to delete', quote=True) 310 | return 311 | 312 | for file_type in ("document", "video", "audio"): 313 | media = getattr(reply, file_type, None) 314 | if media is not None: 315 | break 316 | else: 317 | await msg.edit('This is not supported file format') 318 | return 319 | 320 | result = await Media.collection.delete_one({ 321 | 'file_name': media.file_name, 322 | 'file_size': media.file_size, 323 | 'mime_type': media.mime_type 324 | }) 325 | if result.deleted_count: 326 | await msg.edit('File is successfully deleted from database') 327 | else: 328 | await msg.edit('File not found in database') 329 | @Client.on_message(filters.command('about')) 330 | async def bot_info(bot, message): 331 | buttons = [ 332 | [ 333 | 334 | InlineKeyboardButton('Deploy Video', url=f'{TUTORIAL}') 335 | ] 336 | ] 337 | await message.reply(text=f"{ABOUT}", reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True) 338 | -------------------------------------------------------------------------------- /LuciferMoringstar_Robot/Filter/Inline.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from pyrogram import Client, emoji, filters 3 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, InlineQueryResultCachedDocument 4 | 5 | from LuciferMoringstar_Robot.Utils import get_search_results, is_subscribed 6 | from Config import CACHE_TIME, AUTH_USERS, AUTH_CHANNEL, CUSTOM_FILE_CAPTION, TUTORIAL 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 | InlineKeyboardButton('Deploy Video', url=f'{TUTORIAL}') 93 | ],[ 94 | InlineKeyboardButton('🔍 Search again 🔎', switch_inline_query_current_chat=query) 95 | ]] 96 | return InlineKeyboardMarkup(buttons) 97 | 98 | 99 | def get_size(size): 100 | """Get size in readable format""" 101 | 102 | units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"] 103 | size = float(size) 104 | i = 0 105 | while size >= 1024.0 and i < len(units): 106 | i += 1 107 | size /= 1024.0 108 | return "%.2f %s" % (size, units[i]) 109 | -------------------------------------------------------------------------------- /LuciferMoringstar_Robot/Filter/Main.py: -------------------------------------------------------------------------------- 1 | # (c) PR0FESS0R-99 2 | from Config import AUTH_CHANNEL, AUTH_USERS, CUSTOM_FILE_CAPTION, API_KEY, AUTH_GROUPS, TUTORIAL 3 | from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery 4 | from pyrogram import Client, filters 5 | import re 6 | from pyrogram.errors import UserNotParticipant 7 | from LuciferMoringstar_Robot import get_filter_results, get_file_details, is_subscribed, get_poster 8 | from LuciferMoringstar_Robot import RATING, GENRES, HELP, ABOUT 9 | import random 10 | BUTTONS = {} 11 | BOT = {} 12 | 13 | @Client.on_message(filters.text & filters.private & filters.incoming & filters.user(AUTH_USERS) if AUTH_USERS else filters.text & filters.private & filters.incoming) 14 | async def filter(client, message): 15 | if message.text.startswith("/"): 16 | return 17 | if AUTH_CHANNEL: 18 | invite_link = await client.create_chat_invite_link(int(AUTH_CHANNEL)) 19 | try: 20 | user = await client.get_chat_member(int(AUTH_CHANNEL), message.from_user.id) 21 | if user.status == "kicked": 22 | await client.send_message( 23 | chat_id=message.from_user.id, 24 | text="Sorry Sir, You are Banned to use me.", 25 | parse_mode="markdown", 26 | disable_web_page_preview=True 27 | ) 28 | return 29 | except UserNotParticipant: 30 | await client.send_message( 31 | chat_id=message.from_user.id, 32 | text="**Please Join My Updates Channel to use this Bot!**", 33 | reply_markup=InlineKeyboardMarkup( 34 | [ 35 | [ 36 | InlineKeyboardButton("📢 Join Updates Channel 📢", url=invite_link.invite_link) 37 | ] 38 | ] 39 | ), 40 | parse_mode="markdown" 41 | ) 42 | return 43 | except Exception: 44 | await client.send_message( 45 | chat_id=message.from_user.id, 46 | text="Something went Wrong.", 47 | parse_mode="markdown", 48 | disable_web_page_preview=True 49 | ) 50 | return 51 | if re.findall("((^\/|^,|^!|^\.|^[\U0001F600-\U000E007F]).*)", message.text): 52 | return 53 | if 2 < len(message.text) < 100: 54 | btn = [] 55 | search = message.text 56 | mo_tech_yt = f"**🗂️ Title:** {search}\n**⭐ Rating:** {random.choice(RATING)}\n**🎭 Genre:** {random.choice(GENRES)}\n**📤 Uploaded by {message.chat.title}**" 57 | files = await get_filter_results(query=search) 58 | if files: 59 | for file in files: 60 | file_id = file.file_id 61 | filename = f"[{get_size(file.file_size)}] {file.file_name}" 62 | btn.append( 63 | [InlineKeyboardButton(text=f"{filename}",callback_data=f"pr0fess0r_99#{file_id}")] 64 | ) 65 | else: 66 | await client.send_sticker(chat_id=message.from_user.id, sticker='CAADBQADMwIAAtbcmFelnLaGAZhgBwI') 67 | return 68 | 69 | if not btn: 70 | return 71 | 72 | if len(btn) > 10: 73 | btns = list(split_list(btn, 10)) 74 | keyword = f"{message.chat.id}-{message.message_id}" 75 | BUTTONS[keyword] = { 76 | "total" : len(btns), 77 | "buttons" : btns 78 | } 79 | else: 80 | buttons = btn 81 | buttons.append( 82 | [InlineKeyboardButton(text="📃 Pages 1/1",callback_data="pages")] 83 | ) 84 | poster=None 85 | if API_KEY: 86 | poster=await get_poster(search) 87 | if poster: 88 | await message.reply_photo(photo=poster, caption=mo_tech_yt, reply_markup=InlineKeyboardMarkup(buttons)) 89 | 90 | else: 91 | await message.reply_text(mo_tech_yt, reply_markup=InlineKeyboardMarkup(buttons)) 92 | return 93 | 94 | data = BUTTONS[keyword] 95 | buttons = data['buttons'][0].copy() 96 | 97 | buttons.append( 98 | [InlineKeyboardButton(text="NEXT ⏩",callback_data=f"next_0_{keyword}")] 99 | ) 100 | buttons.append( 101 | [InlineKeyboardButton(text=f"📃 Pages 1/{data['total']}",callback_data="pages")] 102 | ) 103 | poster=None 104 | if API_KEY: 105 | poster=await get_poster(search) 106 | if poster: 107 | await message.reply_photo(photo=poster, caption=mo_tech_yt, reply_markup=InlineKeyboardMarkup(buttons)) 108 | else: 109 | await message.reply_text(mo_tech_yt, reply_markup=InlineKeyboardMarkup(buttons)) 110 | 111 | @Client.on_message(filters.text & filters.group & filters.incoming & filters.chat(AUTH_GROUPS) if AUTH_GROUPS else filters.text & filters.group & filters.incoming) 112 | async def group(client, message): 113 | if re.findall("((^\/|^,|^!|^\.|^[\U0001F600-\U000E007F]).*)", message.text): 114 | return 115 | if 2 < len(message.text) < 50: 116 | btn = [] 117 | search = message.text 118 | mo_tech_yt = f"**🗂️ Title:** {search}\n**⭐ Rating:** {random.choice(RATING)}\n**🎭 Genre:** {random.choice(GENRES)}\n**📤 Uploaded by {message.chat.title}**" 119 | nyva=BOT.get("username") 120 | if not nyva: 121 | botusername=await client.get_me() 122 | nyva=botusername.username 123 | BOT["username"]=nyva 124 | files = await get_filter_results(query=search) 125 | if files: 126 | for file in files: 127 | file_id = file.file_id 128 | filename = f"[{get_size(file.file_size)}] {file.file_name}" 129 | btn.append( 130 | [InlineKeyboardButton(text=f"{filename}", url=f"https://telegram.dog/{nyva}?start=pr0fess0r_99_-_-_-_{file_id}")] 131 | ) 132 | else: 133 | return 134 | if not btn: 135 | return 136 | 137 | if len(btn) > 10: 138 | btns = list(split_list(btn, 10)) 139 | keyword = f"{message.chat.id}-{message.message_id}" 140 | BUTTONS[keyword] = { 141 | "total" : len(btns), 142 | "buttons" : btns 143 | } 144 | else: 145 | buttons = btn 146 | buttons.append( 147 | [InlineKeyboardButton(text="📃 Pages 1/1",callback_data="pages")] 148 | ) 149 | poster=None 150 | if API_KEY: 151 | poster=await get_poster(search) 152 | if poster: 153 | await message.reply_photo(photo=poster, caption=mo_tech_yt, reply_markup=InlineKeyboardMarkup(buttons)) 154 | else: 155 | await message.reply_text(mo_tech_yt, reply_markup=InlineKeyboardMarkup(buttons)) 156 | return 157 | 158 | data = BUTTONS[keyword] 159 | buttons = data['buttons'][0].copy() 160 | 161 | buttons.append( 162 | [InlineKeyboardButton(text="NEXT ⏩",callback_data=f"next_0_{keyword}")] 163 | ) 164 | buttons.append( 165 | [InlineKeyboardButton(text=f"📃 Pages 1/{data['total']}",callback_data="pages")] 166 | ) 167 | poster=None 168 | if API_KEY: 169 | poster=await get_poster(search) 170 | if poster: 171 | await message.reply_photo(photo=poster, caption=mo_tech_yt, reply_markup=InlineKeyboardMarkup(buttons)) 172 | else: 173 | await message.reply_text(mo_tech_yt, reply_markup=InlineKeyboardMarkup(buttons)) 174 | 175 | 176 | def get_size(size): 177 | """Get size in readable format""" 178 | 179 | units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"] 180 | size = float(size) 181 | i = 0 182 | while size >= 1024.0 and i < len(units): 183 | i += 1 184 | size /= 1024.0 185 | return "%.2f %s" % (size, units[i]) 186 | 187 | def split_list(l, n): 188 | for i in range(0, len(l), n): 189 | yield l[i:i + n] 190 | 191 | 192 | 193 | @Client.on_callback_query() 194 | async def cb_handler(client: Client, query: CallbackQuery): 195 | clicked = query.from_user.id 196 | try: 197 | typed = query.message.reply_to_message.from_user.id 198 | except: 199 | typed = query.from_user.id 200 | pass 201 | if (clicked == typed): 202 | 203 | if query.data.startswith("next"): 204 | ident, index, keyword = query.data.split("_") 205 | try: 206 | data = BUTTONS[keyword] 207 | except KeyError: 208 | await query.answer("You are using this for one of my old message, please send the request again.",show_alert=True) 209 | return 210 | 211 | if int(index) == int(data["total"]) - 2: 212 | buttons = data['buttons'][int(index)+1].copy() 213 | 214 | buttons.append( 215 | [InlineKeyboardButton("⏪ BACK", callback_data=f"back_{int(index)+1}_{keyword}")] 216 | ) 217 | buttons.append( 218 | [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data['total']}", callback_data="pages")] 219 | ) 220 | 221 | await query.edit_message_reply_markup( 222 | reply_markup=InlineKeyboardMarkup(buttons) 223 | ) 224 | return 225 | else: 226 | buttons = data['buttons'][int(index)+1].copy() 227 | 228 | buttons.append( 229 | [InlineKeyboardButton("⏪ BACK", callback_data=f"back_{int(index)+1}_{keyword}"),InlineKeyboardButton("NEXT ⏩", callback_data=f"next_{int(index)+1}_{keyword}")] 230 | ) 231 | buttons.append( 232 | [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data['total']}", callback_data="pages")] 233 | ) 234 | 235 | await query.edit_message_reply_markup( 236 | reply_markup=InlineKeyboardMarkup(buttons) 237 | ) 238 | return 239 | 240 | 241 | elif query.data.startswith("back"): 242 | ident, index, keyword = query.data.split("_") 243 | try: 244 | data = BUTTONS[keyword] 245 | except KeyError: 246 | await query.answer("You are using this for one of my old message, please send the request again.",show_alert=True) 247 | return 248 | 249 | if int(index) == 1: 250 | buttons = data['buttons'][int(index)-1].copy() 251 | 252 | buttons.append( 253 | [InlineKeyboardButton("NEXT ⏩", callback_data=f"next_{int(index)-1}_{keyword}")] 254 | ) 255 | buttons.append( 256 | [InlineKeyboardButton(f"📃 Pages {int(index)}/{data['total']}", callback_data="pages")] 257 | ) 258 | 259 | await query.edit_message_reply_markup( 260 | reply_markup=InlineKeyboardMarkup(buttons) 261 | ) 262 | return 263 | else: 264 | buttons = data['buttons'][int(index)-1].copy() 265 | 266 | buttons.append( 267 | [InlineKeyboardButton("⏪ BACK", callback_data=f"back_{int(index)-1}_{keyword}"),InlineKeyboardButton("NEXT ⏩", callback_data=f"next_{int(index)-1}_{keyword}")] 268 | ) 269 | buttons.append( 270 | [InlineKeyboardButton(f"📃 Pages {int(index)}/{data['total']}", callback_data="pages")] 271 | ) 272 | 273 | await query.edit_message_reply_markup( 274 | reply_markup=InlineKeyboardMarkup(buttons) 275 | ) 276 | return 277 | elif query.data == "help": 278 | buttons = [ 279 | [ 280 | InlineKeyboardButton('Making Video', url=f'{TUTORIAL}') 281 | ] 282 | ] 283 | await query.message.edit(text=f"{HELP}", reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True) 284 | 285 | elif query.data == "about": 286 | buttons = [ 287 | [ 288 | InlineKeyboardButton('Making Video', url=f'{TUTORIAL}') 289 | ] 290 | ] 291 | await query.message.edit(text=f"{ABOUT}", reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True) 292 | 293 | 294 | elif query.data.startswith("pr0fess0r_99"): 295 | ident, file_id = query.data.split("#") 296 | filedetails = await get_file_details(file_id) 297 | for files in filedetails: 298 | title = files.file_name 299 | size=files.file_size 300 | f_caption=files.caption 301 | if CUSTOM_FILE_CAPTION: 302 | try: 303 | f_caption=CUSTOM_FILE_CAPTION.format(file_name=title, file_size=size, file_caption=f_caption) 304 | except Exception as e: 305 | print(e) 306 | f_caption=f_caption 307 | if f_caption is None: 308 | f_caption = f"{files.file_name}" 309 | buttons = [ 310 | [ 311 | InlineKeyboardButton('🖥️ How To Own 🖥️', url=f'{TUTORIAL}') 312 | ] 313 | ] 314 | 315 | await query.answer() 316 | await client.send_cached_media( 317 | chat_id=query.from_user.id, 318 | file_id=file_id, 319 | caption=f_caption, 320 | reply_markup=InlineKeyboardMarkup(buttons) 321 | ) 322 | elif query.data.startswith("checksub"): 323 | if AUTH_CHANNEL and not await is_subscribed(client, query): 324 | await query.answer("I Like Your Smartness, But Don't Be Oversmart 😒",show_alert=True) 325 | return 326 | ident, file_id = query.data.split("#") 327 | filedetails = await get_file_details(file_id) 328 | for files in filedetails: 329 | title = files.file_name 330 | size=files.file_size 331 | f_caption=files.caption 332 | if CUSTOM_FILE_CAPTION: 333 | try: 334 | f_caption=CUSTOM_FILE_CAPTION.format(file_name=title, file_size=size, file_caption=f_caption) 335 | except Exception as e: 336 | print(e) 337 | f_caption=f_caption 338 | if f_caption is None: 339 | f_caption = f"{title}" 340 | buttons = [ 341 | [ 342 | InlineKeyboardButton('🖥️ How To Own 🖥️', url=f'{TUTORIAL}') 343 | ] 344 | ] 345 | 346 | await query.answer() 347 | await client.send_cached_media( 348 | chat_id=query.from_user.id, 349 | file_id=file_id, 350 | caption=f_caption, 351 | reply_markup=InlineKeyboardMarkup(buttons) 352 | ) 353 | 354 | 355 | elif query.data == "pages": 356 | await query.answer() 357 | else: 358 | await query.answer("കൌതുകും ലേശം കൂടുതൽ ആണല്ലേ👀",show_alert=True) 359 | -------------------------------------------------------------------------------- /LuciferMoringstar_Robot/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 Config 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 not 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 | pass 217 | return poster 218 | 219 | 220 | async def get_all(list): 221 | for y in list: 222 | v=y.get("Title").lower().strip() 223 | poster = y.get("Poster") 224 | year=y.get("Year")[:4] 225 | id=y.get("imdbID") 226 | await save_poster(id, v, year, poster) 227 | 228 | 229 | def encode_file_id(s: bytes) -> str: 230 | r = b"" 231 | n = 0 232 | 233 | for i in s + bytes([22]) + bytes([4]): 234 | if i == 0: 235 | n += 1 236 | else: 237 | if n: 238 | r += b"\x00" + bytes([n]) 239 | n = 0 240 | 241 | r += bytes([i]) 242 | 243 | return base64.urlsafe_b64encode(r).decode().rstrip("=") 244 | 245 | 246 | def encode_file_ref(file_ref: bytes) -> str: 247 | return base64.urlsafe_b64encode(file_ref).decode().rstrip("=") 248 | 249 | 250 | def unpack_new_file_id(new_file_id): 251 | """Return file_id, file_ref""" 252 | decoded = FileId.decode(new_file_id) 253 | file_id = encode_file_id( 254 | pack( 255 | " 5 | ## How To Deploy Video 6 | 7 | ## Subscribe YouTube Channel 8 | 9 | 10 | #### Added Features 11 | * Imdb posters for autofilter. 12 | * Imdb rating for autofilter. 13 | * Custom captions for your files. 14 | * Index command to index all the files in a given channel (No USER_SESSION Required). 15 | * Ability to Index Public Channels without being admin. 16 | * Support Auto-Filter (Both in PM and in Groups) 17 | * Once files saved in Database , exists until you manually deletes. (No Worry if post gets deleted from source channel.) 18 | * Added Force subscribe (Only channel subscribes can use the bot) 19 | * Ability to restrict groups(AUTH_GROUPS) 20 | 21 | #### Deploy To Heroku 22 | 23 | [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/DalinMathew/AutoFilterBotV3) 24 | 25 | #### Hard Way 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 [`Config.py`](Config.py) file 41 | 42 | ### Variables 43 | 44 | #### Required Variables 45 | * `BOT_TOKEN`: Create a bot using [@BotFather](https://telegram.dog/BotFather), and get the Telegram API token. 46 | * `API_ID`: Get this value from [telegram.org](https://my.telegram.org/apps) 47 | * `API_HASH`: Get this value from [telegram.org](https://my.telegram.org/apps) 48 | * `CHANNELS`: Username or ID of channel or group. Separate multiple IDs by space 49 | * `ADMINS`: Username or ID of Admin. Separate multiple Admins by space 50 | * `DATABASE_URI`: [mongoDB](https://www.mongodb.com) URI. Get this value from [mongoDB](https://www.mongodb.com) 51 | * `DATABASE_NAME`: Name of the database in [mongoDB](https://www.mongodb.com) 52 | 53 | #### Optional Variables 54 | * `OMDB_API_KEY`: OMBD_API_KEY to generate imdb poster for filter results.Get it from [omdbapi.com](http://www.omdbapi.com/apikey.aspx) 55 | * `CUSTOM_FILE_CAPTION` : A custom caption for your files. You can format it with file_name, file_size, file_caption.(supports html formating) 56 | Example: `Join [MT Bots](https://t.me/MalRok) for Best Channels\n\n{file_name}\nSize{file_size}\n{file_caption}.` 57 | * `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. 58 | * `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 59 | * `CACHE_TIME`: The maximum amount of time in seconds that the result of the inline query may be cached on the server 60 | * `USE_CAPTION_FILTER`: Whether bot should use captions to improve search results. (True/False) 61 | * `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. 62 | * `AUTH_CHANNEL`: ID of channel. Without subscribing this channel users cannot use bot. 63 | * `START_MSG`: Welcome message for start command. 64 | 65 | ##### Note 66 | * Currently [API used](http://www.omdbapi.com) here is allowing 1000 requests per day. [You may not get posters if its crossed]. 67 | Once a poster is fetched from OMDB , poster is saved to DB to reduce duplicate requests. 68 | 69 | ## Tips 70 | * You can use `|` to separate query and file type while searching for specific type of file. For example: `Avengers | video` 71 | * 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. 72 | 73 | ## Thanks to 74 | * [Pyrogram](https://github.com/pyrogram/pyrogram) 75 | * [Original Repo](https://github.com/Mahesh0253/Media-Search-bot) 76 | * [subinps](https://github.com/subinps/Media-Search-bot) 77 | * [Editing Muhammed Rk](https://github.com/PR0FESS0R-99/LuciferMoringstar_Robot) 78 | * [Mo Tech YT](https://t.me/Mo_Tech_Group) 79 | * [Lucifer Morningstar](@Lucifer_Devil_AD) 80 | 81 | ## License 82 | Code released under [The GNU General Public License](LICENSE). 83 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Auto Filter Bot V3", 3 | "description": "A greater auto filter bot with features like IMDb support,inline mode,broadcast feature etc..", 4 | "logo":"https://telegra.ph/file/ad9cb7fc42ec0e5e6d006.jpg", 5 | "keywords": [ 6 | "telegram", 7 | "auto-filter", 8 | "filter", 9 | "best", 10 | "indian", 11 | "pyrogram", 12 | "media", 13 | "search", 14 | "channel", 15 | "index", 16 | "inline" 17 | ], 18 | "website": "https://github.com/DalinMathew/AutoFilterBotV3", 19 | "repository": "https://github.com/DalinMathew/AutoFilterBotV3", 20 | "env": { 21 | "BOT_TOKEN": { 22 | "description": "Your bot token.", 23 | "value": "" 24 | }, 25 | "API_ID": { 26 | "description": "Get this value from https://my.telegram.org", 27 | "value": "" 28 | }, 29 | "API_HASH": { 30 | "description": "Get this value from https://my.telegram.org", 31 | "value": "" 32 | }, 33 | "CHANNELS": { 34 | "description": "Username or ID of channel or group. Separate multiple IDs by space.", 35 | "value": "" 36 | }, 37 | "ADMINS": { 38 | "description": "Username or ID of Admin. Separate multiple Admins by space.", 39 | "value": "" 40 | }, 41 | "AUTH_USERS": { 42 | "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.", 43 | "value": "", 44 | "required": false 45 | }, 46 | "FORCES_SUB": { 47 | "description": "ID of channel.Make sure bot is admin in this channel. Without subscribing this channel users cannot use bot.", 48 | "value": "", 49 | "required": false 50 | }, 51 | "START_MSG": { 52 | "description": "Welcome message for start command", 53 | "value": "**Hi, I'm Auto Filter Bot With Greater Abilities**", 54 | "required": false 55 | }, 56 | "USE_CAPTION_FILTER": { 57 | "description": "Whether bot should use captions to improve search results. (True False)", 58 | "value": "False", 59 | "required": false 60 | }, 61 | "OMDB_API_KEY": { 62 | "description": "Your OMBD API KEY, Fill if you want to generate a imdb poster of movie in autofilter.", 63 | "value": "", 64 | "required": false 65 | }, 66 | "CUSTOM_FILE_CAPTION": { 67 | "description": "A custom file caption for your files. formatable with , file_name, file_caption, file_size, Read Readme.md for better understanding.", 68 | "value": "", 69 | "required": false 70 | }, 71 | "AUTH_GROUPS": { 72 | "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.", 73 | "value": "", 74 | "required": false 75 | }, 76 | "DATABASE_2": { 77 | "description": "mongoDB URI. Get this value from https://www.mongodb.com ", 78 | "value": "" 79 | }, 80 | "BOT_NAME": { 81 | "description": "Name of the database in mongoDB ", 82 | "value": "LuciferMoringstar_Robot" 83 | }, 84 | "COLLECTION_NAME": { 85 | "description": "Name of the collections. Defaults to Telegram_files. If you are using the same database, then use different collection name for each bot", 86 | "value": "Telegram_files", 87 | "required": false 88 | }, 89 | "CACHE_TIME": { 90 | "description": "The maximum amount of time in seconds that the result of the inline query may be cached on the server", 91 | "value": "300", 92 | "required": false 93 | }, 94 | "BROADCAST": { 95 | "description": "Value should be True or False. Broadcast with Forward Tag or as Copy.(Without Forward Tag)", 96 | "value": "True", 97 | "required": false 98 | }, 99 | "DATABASE_1": { 100 | "description": "Broadcast Group Database", 101 | "value": "", 102 | "required": true 103 | }, 104 | "ADMIN_ID": { 105 | "description": "Control BroadCast", 106 | "value": "", 107 | "required": true 108 | }, 109 | "BROADCAST_CHANNEL": { 110 | "description": "ID of a Channel (user Notification)", 111 | "value": "", 112 | "required": true 113 | } 114 | }, 115 | "addons": [], 116 | "buildpacks": [ 117 | { 118 | "url": "heroku/python" 119 | } 120 | ], 121 | "formation": { 122 | "worker": { 123 | "quantity": 1, 124 | "size": "free" 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /mt_botz.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 LuciferMoringstar_Robot import Media 11 | from Config 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": "LuciferMoringstar_Robot"}, 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 | -------------------------------------------------------------------------------- /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 | aiofiles 11 | dnspython 12 | -------------------------------------------------------------------------------- /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.8.7 2 | -------------------------------------------------------------------------------- /sample_info.py: -------------------------------------------------------------------------------- 1 | # Bot information 2 | SESSION = 'LuciferMoringstar_Robot' 3 | USER_SESSION = 'User_Bot' 4 | API_ID = 12345 5 | API_HASH = '0123456789abcdef0123456789abcdef' 6 | BOT_TOKEN = '123456:LuciferMoringstar_Robot-zyx57W2v1u123ew11' 7 | USERBOT_STRING_SESSION = 'LuciferMoringstar_Robot' 8 | 9 | # Bot settings 10 | CACHE_TIME = 300 11 | USE_CAPTION_FILTER = False 12 | 13 | # Admins, Channels & Users 14 | ADMINS = [12345789, 'admin123', 987654321] 15 | CHANNELS = [-10012345678, -100987654321, 'Mo_Tech_YT'] 16 | AUTH_USERS = [] 17 | AUTH_CHANNEL = None 18 | 19 | # MongoDB information 20 | DATABASE_URI = "mongodb://[LuciferMoringstar_Robot:LuciferMoringstar_Robot@]host1[:port1][,...hostN[:portN]][/[defaultauthdb]?retryWrites=true&w=majority" 21 | DATABASE_NAME = 'LuciferMoringstar_Robot' 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' 33 | --------------------------------------------------------------------------------