├── .dockerignore ├── .gitignore ├── Dockerfile ├── LICENSE ├── Procfile ├── README.md ├── app.json ├── bot.py ├── generate_session_string.py ├── info.py ├── logging.conf ├── one_time_indexer.py ├── plugins ├── channel.py ├── commands.py ├── inline.py └── userbot.py ├── requirements.txt ├── runtime.txt ├── sample_info.py └── utils ├── __init__.py ├── database.py └── helpers.py /.dockerignore: -------------------------------------------------------------------------------- 1 | .github 2 | .gitignore 3 | Procfile 4 | app.json 5 | Dockerfile 6 | runtime.txt 7 | README.md 8 | LICENSE 9 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3-slim-buster 2 | 3 | RUN pip install --upgrade pip 4 | 5 | ENV USER botx 6 | ENV HOME /home/$USER 7 | ENV BOT $HOME/media-search-bot 8 | 9 | RUN useradd -m $USER 10 | RUN mkdir -p $BOT 11 | RUN chown $USER:$USER $BOT 12 | USER $USER 13 | WORKDIR $BOT 14 | 15 | 16 | COPY requirements.txt requirements.txt 17 | RUN pip install --user --no-cache-dir -r requirements.txt 18 | 19 | COPY . . 20 | 21 | CMD python3 bot.py 22 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | worker: python3 bot.py -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [Media Search bot](https://github.com/Mahesh0253/Media-Search-bot) 2 | 3 | * Index channel or group files for inline search. 4 | * When you post file on telegram channel or group this bot will save that file in database, so you can search easily in inline mode. 5 | * Supports document, video and audio file formats with caption support. 6 | 7 | ## Installation 8 | 9 | ### Watch this video to create bot - https://youtu.be/dsuTn4qV2GA 10 | ### Easy Way 11 | [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy) 12 | 13 | 14 | ### Hard Way 15 | ```bash 16 | # Create virtual environment 17 | python3 -m venv env 18 | 19 | # Activate virtual environment 20 | env\Scripts\activate.bat # For Windows 21 | source env/bin/activate # For Linux or MacOS 22 | 23 | # Install Packages 24 | pip3 install -r requirements.txt 25 | 26 | # Edit info.py with variables as given below then run bot 27 | python3 bot.py 28 | ``` 29 | Check [`sample_info.py`](sample_info.py) before editing [`info.py`](info.py) file 30 | 31 | ### Docker 32 | ``` 33 | docker run -d \ 34 | -e BOT_TOKEN="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11" \ 35 | -e API_ID='12345' \ 36 | -e API_HASH='0123456789abcdef0123456789abcdef' \ 37 | -e CHANNELS='-10012345678' \ 38 | -e ADMINS='123456789' \ 39 | -e DATABASE_URI="mongodb+srv://...mongodb.net/Database?retryWrites=true&w=majority" \ 40 | -e DATABASE_NAME=databasename \ 41 | --restart on-failure \ 42 | --name mediasearchbot botxtg/media-search-bot 43 | ``` 44 | You can also run with `env` file like below, 45 | ``` 46 | docker run -d \ 47 | --env-file .env \ 48 | --restart on-failure \ 49 | --name mediasearchbot botxtg/media-search-bot 50 | ``` 51 | 52 | ## Variables 53 | ### Required Variables 54 | * `BOT_TOKEN`: Create a bot using [@BotFather](https://telegram.dog/BotFather), and get the Telegram API token. 55 | * `API_ID`: Get this value from [telegram.org](https://my.telegram.org/apps) 56 | * `API_HASH`: Get this value from [telegram.org](https://my.telegram.org/apps) 57 | * `CHANNELS`: Username or ID of channel or group. Separate multiple IDs by space 58 | * `ADMINS`: Username or ID of Admin. Separate multiple Admins by space 59 | * `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) 60 | * `DATABASE_NAME`: Name of the database in [mongoDB](https://www.mongodb.com). For more help watch this [video](https://youtu.be/dsuTn4qV2GA) 61 | 62 | ### Optional Variables 63 | * `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 64 | * `CACHE_TIME`: The maximum amount of time in seconds that the result of the inline query may be cached on the server 65 | * `USE_CAPTION_FILTER`: Whether bot should use captions to improve search results. (True/False) 66 | * `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. 67 | * `AUTH_CHANNEL`: Username or ID of channel. Without subscribing this channel users cannot use bot. 68 | * `START_MSG`: Welcome message for start command. 69 | * `INVITE_MSG`: Auth channel invitation message. 70 | * `USERBOT_STRING_SESSION`: User bot string session. 71 | ## Admin commands 72 | ``` 73 | channel - Get basic infomation about channels 74 | total - Show total of saved files 75 | delete - Delete file from database 76 | index - Index all files from channel or group 77 | logger - Get log file 78 | ``` 79 | 80 | ## Tips 81 | * Use `index` command or run [one_time_indexer.py](one_time_indexer.py) file to save old files in the database that are not indexed yet. 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 | ## Contributions 86 | Contributions are welcome. 87 | 88 | ## Thanks to [Pyrogram](https://github.com/pyrogram/pyrogram) 89 | 90 | ## Support 91 | [Update Channel](https://t.me/botxupdates) and [Support Group](https://t.me/botxsupport) 92 | 93 | ## License 94 | Code released under [The GNU General Public License](LICENSE). 95 | 96 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Media Search bot", 3 | "description": "When you going to send file on telegram channel/group this bot will save that in database, So you can search that easily in inline mode", 4 | "keywords": [ 5 | "telegram", 6 | "best", 7 | "indian", 8 | "pyrogram", 9 | "media", 10 | "search", 11 | "channel", 12 | "index", 13 | "inline" 14 | ], 15 | "website": "https://github.com/Mahesh0253/Media-Search-bot", 16 | "repository": "https://github.com/Mahesh0253/Media-Search-bot", 17 | "env": { 18 | "BOT_TOKEN": { 19 | "description": "Your bot token.", 20 | "value": "" 21 | }, 22 | "USERBOT_STRING_SESSION": { 23 | "description": "User bot string session.", 24 | "value": "", 25 | "required": false 26 | }, 27 | "API_ID": { 28 | "description": "Get this value from https://my.telegram.org", 29 | "value": "" 30 | }, 31 | "API_HASH": { 32 | "description": "Get this value from https://my.telegram.org", 33 | "value": "" 34 | }, 35 | "CHANNELS": { 36 | "description": "Username or ID of channel or group. Separate multiple IDs by space.", 37 | "value": "" 38 | }, 39 | "ADMINS": { 40 | "description": "Username or ID of Admin. Separate multiple Admins by space.", 41 | "value": "" 42 | }, 43 | "AUTH_USERS": { 44 | "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.", 45 | "value": "", 46 | "required": false 47 | }, 48 | "AUTH_CHANNEL": { 49 | "description": "Username or ID of channel. Without subscribing this channel users cannot use bot.", 50 | "value": "", 51 | "required": false 52 | }, 53 | "START_MSG": { 54 | "description": "Welcome message for start command", 55 | "value": "**Hi, I'm Media Search bot**\n\nHere you can search files in inline mode. Just press following buttons and start searching.", 56 | "required": false 57 | }, 58 | "INVITE_MSG": { 59 | "description": "Auth channel invitation message", 60 | "value": "Please join @.... to use this bot", 61 | "required": false 62 | }, 63 | "USE_CAPTION_FILTER": { 64 | "description": "Whether bot should use captions to improve search results. (True False)", 65 | "value": "False", 66 | "required": false 67 | }, 68 | "DATABASE_URI": { 69 | "description": "mongoDB URI. Get this value from https://www.mongodb.com. For more help watch this video - https://youtu.be/dsuTn4qV2GA", 70 | "value": "" 71 | }, 72 | "DATABASE_NAME": { 73 | "description": "Name of the database in mongoDB. For more help watch this video - https://youtu.be/dsuTn4qV2GA", 74 | "value": "" 75 | }, 76 | "COLLECTION_NAME": { 77 | "description": "Name of the collections. Defaults to Telegram_files. If you are using the same database, then use different collection name for each bot", 78 | "value": "Telegram_files", 79 | "required": false 80 | }, 81 | "CACHE_TIME": { 82 | "description": "The maximum amount of time in seconds that the result of the inline query may be cached on the server", 83 | "value": "300", 84 | "required": false 85 | } 86 | }, 87 | "addons": [], 88 | "buildpacks": [ 89 | { 90 | "url": "heroku/python" 91 | } 92 | ], 93 | "formation": { 94 | "worker": { 95 | "quantity": 1, 96 | "size": "free" 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /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.WARNING) 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 | 13 | 14 | class Bot(Client): 15 | 16 | def __init__(self): 17 | super().__init__( 18 | 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 | -------------------------------------------------------------------------------- /generate_session_string.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import logging.config 3 | 4 | # Get logging configurations 5 | logging.config.fileConfig('logging.conf') 6 | logging.getLogger().setLevel(logging.WARNING) 7 | 8 | import asyncio 9 | from pyrogram import Client 10 | from info import API_ID, API_HASH 11 | 12 | 13 | async def main(): 14 | """Generate session string for user bot""" 15 | 16 | phone_number = input('Enter phone number with country code prefix: ') 17 | 18 | user_bot = Client( 19 | name='User-bot', 20 | api_id=API_ID, 21 | api_hash=API_HASH, 22 | phone_number=phone_number, 23 | in_memory=True 24 | ) 25 | 26 | async with user_bot: 27 | session_string = await user_bot.export_session_string() 28 | print(f"Following is your session string -\n\n{session_string}") 29 | 30 | 31 | loop = asyncio.get_event_loop() 32 | loop.run_until_complete(main()) 33 | -------------------------------------------------------------------------------- /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 | USER_SESSION = environ.get('USER_SESSION', 'User_Bot') 9 | API_ID = int(environ['API_ID']) 10 | API_HASH = environ['API_HASH'] 11 | BOT_TOKEN = environ['BOT_TOKEN'] 12 | USERBOT_STRING_SESSION = environ.get('USERBOT_STRING_SESSION') 13 | 14 | # Bot settings 15 | CACHE_TIME = int(environ.get('CACHE_TIME', 300)) 16 | USE_CAPTION_FILTER = bool(environ.get('USE_CAPTION_FILTER', False)) 17 | 18 | # Admins, Channels & Users 19 | ADMINS = [int(admin) if id_pattern.search(admin) else admin for admin in environ['ADMINS'].split()] 20 | CHANNELS = [int(ch) if id_pattern.search(ch) else ch for ch in environ['CHANNELS'].split()] 21 | auth_users = [int(user) if id_pattern.search(user) else user for user in environ.get('AUTH_USERS', '').split()] 22 | AUTH_USERS = (auth_users + ADMINS) if auth_users else [] 23 | auth_channel = environ.get('AUTH_CHANNEL') 24 | AUTH_CHANNEL = int(auth_channel) if auth_channel and id_pattern.search(auth_channel) else auth_channel 25 | 26 | # MongoDB information 27 | DATABASE_URI = environ['DATABASE_URI'] 28 | DATABASE_NAME = environ['DATABASE_NAME'] 29 | COLLECTION_NAME = environ.get('COLLECTION_NAME', 'Telegram_files') 30 | 31 | # Messages 32 | default_start_msg = """ 33 | **Hi, I'm Media Search bot** 34 | 35 | Here you can search files in inline mode. Just press following buttons and start searching. 36 | """ 37 | 38 | START_MSG = environ.get('START_MSG', default_start_msg) 39 | SHARE_BUTTON_TEXT = 'Checkout {username} for searching files' 40 | INVITE_MSG = environ.get('INVITE_MSG', 'Please join @.... to use this bot') -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /one_time_indexer.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import logging.config 3 | 4 | # Get logging configurations 5 | logging.config.fileConfig('logging.conf') 6 | logging.getLogger().setLevel(logging.WARNING) 7 | 8 | import asyncio 9 | from pyrogram import Client 10 | from info import SESSION, USERBOT_STRING_SESSION, API_ID, API_HASH, BOT_TOKEN, CHANNELS 11 | from utils import save_file 12 | 13 | 14 | async def main(): 15 | """Save old files in database with the help of user bot""" 16 | 17 | user_bot = Client('User-bot', API_ID, API_HASH, session_string=USERBOT_STRING_SESSION, in_memory=True) 18 | bot = Client(SESSION, API_ID, API_HASH, bot_token=BOT_TOKEN) 19 | 20 | await user_bot.start() 21 | await bot.start() 22 | 23 | try: 24 | for channel in CHANNELS: 25 | async for user_message in user_bot.get_chat_history(channel): 26 | message = await bot.get_messages(channel, user_message.id, replies=0) 27 | for file_type in ("document", "video", "audio"): 28 | media = getattr(message, file_type, None) 29 | if media is not None: 30 | break 31 | else: 32 | continue 33 | media.file_type = file_type 34 | media.caption = message.caption 35 | await save_file(media) 36 | finally: 37 | await user_bot.stop() 38 | await bot.stop() 39 | 40 | 41 | loop = asyncio.get_event_loop() 42 | loop.run_until_complete(main()) 43 | -------------------------------------------------------------------------------- /plugins/channel.py: -------------------------------------------------------------------------------- 1 | from pyrogram import Client, filters 2 | 3 | from info import CHANNELS 4 | from utils import save_file 5 | 6 | media_filter = filters.document | filters.video | filters.audio 7 | 8 | 9 | @Client.on_message(filters.chat(CHANNELS) & media_filter) 10 | async def media(bot, message): 11 | """Media Handler""" 12 | for file_type in ("document", "video", "audio"): 13 | media = getattr(message, file_type, None) 14 | if media is not None: 15 | break 16 | else: 17 | return 18 | 19 | media.file_type = file_type 20 | media.caption = message.caption 21 | await save_file(media) -------------------------------------------------------------------------------- /plugins/commands.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | 4 | from pyrogram import Client, filters 5 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup 6 | 7 | from info import START_MSG, CHANNELS, ADMINS, INVITE_MSG 8 | from utils import Media 9 | 10 | logger = logging.getLogger(__name__) 11 | 12 | 13 | @Client.on_message(filters.command('start')) 14 | async def start(bot, message): 15 | """Start command handler""" 16 | if len(message.command) > 1 and message.command[1] == 'subscribe': 17 | await message.reply(INVITE_MSG) 18 | else: 19 | buttons = [[ 20 | InlineKeyboardButton('Search Here', switch_inline_query_current_chat=''), 21 | InlineKeyboardButton('Go Inline', switch_inline_query=''), 22 | ]] 23 | reply_markup = InlineKeyboardMarkup(buttons) 24 | await message.reply(START_MSG, reply_markup=reply_markup) 25 | 26 | 27 | @Client.on_message(filters.command('channel') & filters.user(ADMINS)) 28 | async def channel_info(bot, message): 29 | """Send basic information of channel""" 30 | if isinstance(CHANNELS, (int, str)): 31 | channels = [CHANNELS] 32 | elif isinstance(CHANNELS, list): 33 | channels = CHANNELS 34 | else: 35 | raise ValueError("Unexpected type of CHANNELS") 36 | 37 | text = '📑 **Indexed channels/groups**\n' 38 | for channel in channels: 39 | chat = await bot.get_chat(channel) 40 | if chat.username: 41 | text += '\n@' + chat.username 42 | else: 43 | text += '\n' + chat.title or chat.first_name 44 | 45 | text += f'\n\n**Total:** {len(CHANNELS)}' 46 | 47 | if len(text) < 4096: 48 | await message.reply(text) 49 | else: 50 | file = 'Indexed channels.txt' 51 | with open(file, 'w') as f: 52 | f.write(text) 53 | await message.reply_document(file) 54 | os.remove(file) 55 | 56 | 57 | @Client.on_message(filters.command('total') & filters.user(ADMINS)) 58 | async def total(bot, message): 59 | """Show total files in database""" 60 | msg = await message.reply("Processing...⏳", quote=True) 61 | try: 62 | total = await Media.count_documents() 63 | await msg.edit(f'📁 Saved files: {total}') 64 | except Exception as e: 65 | logger.exception('Failed to check total files') 66 | await msg.edit(f'Error: {e}') 67 | 68 | 69 | @Client.on_message(filters.command('logger') & filters.user(ADMINS)) 70 | async def log_file(bot, message): 71 | """Send log file""" 72 | try: 73 | await message.reply_document('TelegramBot.log') 74 | except Exception as e: 75 | await message.reply(str(e)) 76 | 77 | 78 | @Client.on_message(filters.command('delete') & filters.user(ADMINS)) 79 | async def delete(bot, message): 80 | """Delete file from database""" 81 | reply = message.reply_to_message 82 | if not (reply and reply.media): 83 | await message.reply('Reply to file with /delete which you want to delete', quote=True) 84 | return 85 | 86 | msg = await message.reply("Processing...⏳", quote=True) 87 | 88 | for file_type in ("document", "video", "audio"): 89 | media = getattr(reply, file_type, None) 90 | if media is not None: 91 | break 92 | else: 93 | await msg.edit('This is not supported file format') 94 | return 95 | 96 | result = await Media.collection.delete_one({ 97 | 'file_name': media.file_name, 98 | 'file_size': media.file_size, 99 | 'file_type': media.file_type, 100 | 'mime_type': media.mime_type 101 | }) 102 | 103 | if result.deleted_count: 104 | await msg.edit('File is successfully deleted from database') 105 | else: 106 | await msg.edit('File not found in database') 107 | -------------------------------------------------------------------------------- /plugins/inline.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from urllib.parse import quote 3 | 4 | from pyrogram import Client, emoji, filters 5 | from pyrogram.errors import UserNotParticipant 6 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, InlineQueryResultCachedDocument 7 | 8 | from utils import get_search_results 9 | from info import CACHE_TIME, SHARE_BUTTON_TEXT, AUTH_USERS, AUTH_CHANNEL 10 | 11 | logger = logging.getLogger(__name__) 12 | cache_time = 0 if AUTH_USERS or AUTH_CHANNEL else CACHE_TIME 13 | 14 | 15 | @Client.on_inline_query(filters.user(AUTH_USERS) if AUTH_USERS else None) 16 | async def answer(bot, query): 17 | """Show search results for given inline query""" 18 | 19 | if AUTH_CHANNEL and not await is_subscribed(bot, query): 20 | await query.answer( 21 | results=[], 22 | cache_time=0, 23 | switch_pm_text='You have to subscribe channel', 24 | switch_pm_parameter="subscribe", 25 | ) 26 | return 27 | 28 | results = [] 29 | if '|' in query.query: 30 | text, file_type = query.query.split('|', maxsplit=1) 31 | text = text.strip() 32 | file_type = file_type.strip().lower() 33 | else: 34 | text = query.query.strip() 35 | file_type = None 36 | 37 | offset = int(query.offset or 0) 38 | reply_markup = get_reply_markup(bot.username, query=text) 39 | files, next_offset = await get_search_results(text, file_type=file_type, max_results=10, offset=offset) 40 | 41 | for file in files: 42 | results.append( 43 | InlineQueryResultCachedDocument( 44 | title=file.file_name, 45 | document_file_id=file.file_id, 46 | caption=file.caption or "", 47 | description=f'Size: {size_formatter(file.file_size)}\nType: {file.file_type}', 48 | reply_markup=reply_markup 49 | ) 50 | ) 51 | 52 | if results: 53 | switch_pm_text = f"{emoji.FILE_FOLDER} Results" 54 | if text: 55 | switch_pm_text += f" for {text}" 56 | 57 | await query.answer( 58 | results=results, 59 | cache_time=cache_time, 60 | switch_pm_text=switch_pm_text, 61 | switch_pm_parameter="start", 62 | next_offset=str(next_offset) 63 | ) 64 | else: 65 | 66 | switch_pm_text = f'{emoji.CROSS_MARK} No results' 67 | if text: 68 | switch_pm_text += f' for "{text}"' 69 | 70 | await query.answer( 71 | results=[], 72 | cache_time=cache_time, 73 | switch_pm_text=switch_pm_text, 74 | switch_pm_parameter="okay", 75 | ) 76 | 77 | 78 | def get_reply_markup(username, query): 79 | url = 't.me/share/url?url=' + quote(SHARE_BUTTON_TEXT.format(username=username)) 80 | buttons = [ 81 | [ 82 | InlineKeyboardButton('Search again', switch_inline_query_current_chat=query), 83 | InlineKeyboardButton('Share bot', url=url), 84 | ] 85 | ] 86 | return InlineKeyboardMarkup(buttons) 87 | 88 | 89 | def size_formatter(size): 90 | """Get size in readable format""" 91 | 92 | units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"] 93 | size = float(size) 94 | i = 0 95 | while size >= 1024.0 and i < len(units): 96 | i += 1 97 | size /= 1024.0 98 | return "%.2f %s" % (size, units[i]) 99 | 100 | 101 | async def is_subscribed(bot, query): 102 | try: 103 | user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id) 104 | except UserNotParticipant: 105 | pass 106 | except Exception as e: 107 | logger.exception(e) 108 | else: 109 | if not user.status == 'kicked': 110 | return True 111 | 112 | return False 113 | -------------------------------------------------------------------------------- /plugins/userbot.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import asyncio 3 | 4 | from pyrogram import Client, filters 5 | from pyrogram.errors import FloodWait 6 | 7 | from info import USERBOT_STRING_SESSION, API_ID, API_HASH, ADMINS, id_pattern 8 | from utils import save_file 9 | 10 | logger = logging.getLogger(__name__) 11 | lock = asyncio.Lock() 12 | 13 | 14 | @Client.on_message(filters.command(['index', 'indexfiles']) & filters.user(ADMINS)) 15 | async def index_files(bot, message): 16 | """Save channel or group files with the help of user bot""" 17 | 18 | if not USERBOT_STRING_SESSION: 19 | await message.reply('Set `USERBOT_STRING_SESSION` in info.py file or in environment variables.') 20 | elif len(message.command) == 1: 21 | await message.reply('Please specify channel username or id in command.\n\nExample: `/index -10012345678`') 22 | elif lock.locked(): 23 | await message.reply('Wait until previous process complete.') 24 | else: 25 | msg = await message.reply('Processing...⏳') 26 | raw_data = message.command[1:] 27 | user_bot = Client('User-bot', API_ID, API_HASH, session_string=USERBOT_STRING_SESSION) 28 | chats = [int(chat) if id_pattern.search(chat) else chat for chat in raw_data] 29 | total_files = 0 30 | 31 | async with lock: 32 | try: 33 | async with user_bot: 34 | for chat in chats: 35 | 36 | async for user_message in user_bot.get_chat_history(chat): 37 | try: 38 | message = await bot.get_messages(chat, user_message.id, replies=0) 39 | except FloodWait as e: 40 | await asyncio.sleep(e.value) 41 | message = await bot.get_messages(chat, user_message.id, replies=0) 42 | 43 | for file_type in ("document", "video", "audio"): 44 | media = getattr(message, file_type, None) 45 | if media is not None: 46 | break 47 | else: 48 | continue 49 | media.file_type = file_type 50 | media.caption = message.caption 51 | await save_file(media) 52 | total_files += 1 53 | except Exception as e: 54 | logger.exception(e) 55 | await msg.edit(f'Error: {e}') 56 | else: 57 | await msg.edit(f'Total {total_files} checked!') 58 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pyrogram~=2.0.35 2 | tgcrypto==1.2.3 3 | pymongo[srv]==3.12.3 4 | motor==2.5.1 5 | marshmallow==3.14.1 6 | umongo==3.0.1 7 | -------------------------------------------------------------------------------- /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.8.12 2 | -------------------------------------------------------------------------------- /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' -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .helpers import unpack_new_file_id 2 | from .database import Media, save_file, get_search_results -------------------------------------------------------------------------------- /utils/database.py: -------------------------------------------------------------------------------- 1 | import re 2 | import logging 3 | 4 | from pymongo.errors import DuplicateKeyError 5 | from umongo import Instance, Document, fields 6 | from motor.motor_asyncio import AsyncIOMotorClient 7 | from marshmallow.exceptions import ValidationError 8 | 9 | from info import DATABASE_URI, DATABASE_NAME, COLLECTION_NAME, USE_CAPTION_FILTER 10 | from .helpers import unpack_new_file_id 11 | 12 | logger = logging.getLogger(__name__) 13 | logger.setLevel(logging.INFO) 14 | 15 | client = AsyncIOMotorClient(DATABASE_URI) 16 | database = client[DATABASE_NAME] 17 | instance = Instance.from_db(database) 18 | 19 | 20 | @instance.register 21 | class Media(Document): 22 | file_id = fields.StrField(attribute='_id') 23 | file_ref = fields.StrField(allow_none=True) 24 | file_name = fields.StrField(required=True) 25 | file_size = fields.IntField(required=True) 26 | file_type = fields.StrField(allow_none=True) 27 | mime_type = fields.StrField(allow_none=True) 28 | caption = fields.StrField(allow_none=True) 29 | 30 | class Meta: 31 | indexes = ('$file_name', ) 32 | collection_name = COLLECTION_NAME 33 | 34 | 35 | async def save_file(media): 36 | """Save file in database""" 37 | 38 | file_id, file_ref = unpack_new_file_id(media.file_id) 39 | 40 | try: 41 | file = Media( 42 | file_id=file_id, 43 | file_ref=file_ref, 44 | file_name=media.file_name, 45 | file_size=media.file_size, 46 | file_type=media.file_type, 47 | mime_type=media.mime_type, 48 | caption=media.caption.html if media.caption else None, 49 | ) 50 | except ValidationError: 51 | logger.exception('Error occurred while saving file in database') 52 | else: 53 | try: 54 | await file.commit() 55 | except DuplicateKeyError: 56 | logger.warning(media.file_name + " is already saved in database") 57 | else: 58 | logger.info(media.file_name + " is saved in database") 59 | 60 | 61 | async def get_search_results(query, file_type=None, max_results=10, offset=0): 62 | """For given query return (results, next_offset)""" 63 | 64 | query = query.strip() 65 | if not query: 66 | raw_pattern = '.' 67 | elif ' ' not in query: 68 | raw_pattern = r'(\b|[\.\+\-_])' + query + r'(\b|[\.\+\-_])' 69 | else: 70 | raw_pattern = query.replace(' ', r'.*[\s\.\+\-_\(\)\[\]]') 71 | 72 | try: 73 | regex = re.compile(raw_pattern, flags=re.IGNORECASE) 74 | except: 75 | return [], '' 76 | 77 | if USE_CAPTION_FILTER: 78 | filter = {'$or': [{'file_name': regex}, {'caption': regex}]} 79 | else: 80 | filter = {'file_name': regex} 81 | 82 | if file_type: 83 | filter['file_type'] = file_type 84 | 85 | total_results = await Media.count_documents(filter) 86 | next_offset = offset + max_results 87 | 88 | if next_offset > total_results: 89 | next_offset = '' 90 | 91 | cursor = Media.find(filter) 92 | 93 | # Sort by recent 94 | cursor.sort('$natural', -1) 95 | 96 | # Slice files according to offset and max results 97 | cursor.skip(offset).limit(max_results) 98 | 99 | # Get list of files 100 | files = await cursor.to_list(length=max_results) 101 | 102 | return files, next_offset 103 | -------------------------------------------------------------------------------- /utils/helpers.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | 3 | import base64 4 | from struct import pack 5 | 6 | from pyrogram import raw 7 | from pyrogram.file_id import FileId, FileType, PHOTO_TYPES, DOCUMENT_TYPES 8 | 9 | 10 | def get_input_file_from_file_id( 11 | file_id: str, 12 | expected_file_type: FileType = None, 13 | ) -> Union["raw.types.InputPhoto", "raw.types.InputDocument"]: 14 | try: 15 | decoded = FileId.decode(file_id) 16 | except Exception: 17 | raise ValueError( 18 | f'Failed to decode "{file_id}". The value does not represent an existing local file, ' 19 | f'HTTP URL, or valid file id.' 20 | ) 21 | 22 | file_type = decoded.file_type 23 | 24 | if expected_file_type is not None and file_type != expected_file_type: 25 | raise ValueError(f'Expected: "{expected_file_type}", got "{file_type}" file_id instead') 26 | 27 | if file_type in (FileType.THUMBNAIL, FileType.CHAT_PHOTO): 28 | raise ValueError(f"This file_id can only be used for download: {file_id}") 29 | 30 | if file_type in PHOTO_TYPES: 31 | return raw.types.InputPhoto( 32 | id=decoded.media_id, 33 | access_hash=decoded.access_hash, 34 | file_reference=decoded.file_reference, 35 | ) 36 | 37 | if file_type in DOCUMENT_TYPES: 38 | return raw.types.InputDocument( 39 | id=decoded.media_id, 40 | access_hash=decoded.access_hash, 41 | file_reference=decoded.file_reference, 42 | ) 43 | 44 | raise ValueError(f"Unknown file id: {file_id}") 45 | 46 | 47 | def encode_file_id(s: bytes) -> str: 48 | r = b"" 49 | n = 0 50 | 51 | for i in s + bytes([22]) + bytes([4]): 52 | if i == 0: 53 | n += 1 54 | else: 55 | if n: 56 | r += b"\x00" + bytes([n]) 57 | n = 0 58 | 59 | r += bytes([i]) 60 | 61 | return base64.urlsafe_b64encode(r).decode().rstrip("=") 62 | 63 | 64 | def encode_file_ref(file_ref: bytes) -> str: 65 | return base64.urlsafe_b64encode(file_ref).decode().rstrip("=") 66 | 67 | 68 | def unpack_new_file_id(new_file_id): 69 | """Return file_id, file_ref""" 70 | decoded = FileId.decode(new_file_id) 71 | file_id = encode_file_id( 72 | pack( 73 | "