├── .gitignore ├── Dockerfile ├── LICENSE ├── Procfile ├── README.md ├── Script.py ├── app.json ├── bot.py ├── database ├── connections_mdb.py ├── filters_mdb.py ├── gfilters_mdb.py ├── ia_filterdb.py └── users_chats_db.py ├── docker-compose.yml ├── heroku.yml ├── info.py ├── logging.conf ├── plugins ├── __init__.py ├── banned.py ├── broadcast.py ├── channel.py ├── commands.py ├── connection.py ├── files_delete.py ├── filters.py ├── genlink.py ├── gfilters.py ├── index.py ├── inline.py ├── misc.py ├── p_ttishow.py ├── pm_filter.py └── route.py ├── requirements.txt ├── runtime.txt ├── sample_info.py ├── start.sh └── utils.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 | .goutputstream-VAFWB1 148 | result.json 149 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.8-slim-buster 2 | 3 | RUN apt update && apt upgrade -y 4 | RUN apt install git -y 5 | COPY requirements.txt /requirements.txt 6 | 7 | RUN cd / 8 | RUN pip3 install -U pip && pip3 install -U -r requirements.txt 9 | RUN mkdir /Advance-Auto-Filter 10 | WORKDIR /Advance-Auto-Filter 11 | COPY start.sh /start.sh 12 | CMD ["/bin/bash", "/start.sh"] 13 | -------------------------------------------------------------------------------- /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 | web: python3 bot.py 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Advance Auto Filter 3 | 4 |

5 | VJ Bots 6 |

7 | 8 | ## • What's New ? 9 | 10 | - ⟴ Self Delete Added (Auto delete) 11 | - ⟴ Filter On Off Option Added 12 | - ⟴ Custom Welcome Message 13 | - ⟴ Custom Download Name And URL 14 | - ⟴ Custom Texts (About, Help, Stats,More..) 15 | - ⟴ Custom URL Buttons (Updates channel, Add To Group, Force Sub, More...) 16 | 17 | 18 | ## Features 19 | 20 | - [x] 2GB+ Files Now Support 21 | - [x] Multiple URL Shortener Added 22 | - [x] Custom Buttons 23 | - [x] Auto Filter 24 | - [x] Manual Filter 25 | - [x] IMDB 26 | - [x] Admin Commands 27 | - [x] Broadcast 28 | - [x] Index 29 | - [x] IMDB search 30 | - [x] Inline Search 31 | - [x] Random pics 32 | - [x] ids and User info 33 | - [x] Stats, Users, Chats, Ban, Unban, Leave, Disable, Channel 34 | - [x] Spelling Check Feature 35 | - [x] File Store 36 | ## Variables 37 | 38 | Read [this](https://telegram.dog/VJ_Bots) before you start messing up with your edits. 39 | 40 | ### Required Variables 41 | * `BOT_TOKEN`: Create a bot using [@BotFather](https://telegram.dog/BotFather), and get the Telegram API token. 42 | * `API_ID`: Get this value from [telegram.org](https://my.telegram.org/apps) 43 | * `API_HASH`: Get this value from [telegram.org](https://my.telegram.org/apps) 44 | * `CHANNELS`: Username or ID of channel or group. Separate multiple IDs by space 45 | * `ADMINS`: Username or ID of Admin. Separate multiple Admins by space 46 | * `DATABASE_URI`: [mongoDB](https://www.mongodb.com) URI. Get this value from [mongoDB](https://www.mongodb.com). 47 | * `DATABASE_NAME`: Name of the database in [mongoDB](https://www.mongodb.com). 48 | * `LOG_CHANNEL` : A channel to log the activities of bot. Make sure bot is an admin in the channel. 49 | ### Optional Variables 50 | * `PICS`: Telegraph links of images to show in start message.( Multiple images can be used separated by space ) 51 | * `FILE_STORE_CHANNEL`: Channel from were file store links of posts should be made.Separate multiple IDs by space 52 | * Check [info.py](https://github.com/VJBots/Advance-Auto-Filter/blob/main/info.py) for more 53 | ## EXTRA FEATURES 54 | * `URL_SHORTENR_WEBSITE`: URL Shortener Website Link ( Without https://) 55 | * `URL_SHORTNER_WEBSITE_API`: URL Shortener Website API key 56 | * `SELF_DELETE`: True if SELF_DELETE is On, False if Off 57 | * `SELF_DELETE_SECONDS`: Enter Seconds to be SELF_DELETE 58 | * `START_TXT`: Enter Your Start Message 59 | * `ABOUT_TXT`: Enter Your About Message 60 | 61 | 62 | ## Deploy 63 | You can deploy this bot anywhere. 64 | 65 | **[Watch Deploying Tutorial...](https://youtube.com/@Tech_VJ)** 66 | 67 |
Deploy To Heroku 68 |

69 |
70 | 71 | Deploy 72 | 73 |

74 |
75 | 76 | [![Deploy to Koyeb](https://www.koyeb.com/static/images/deploy/button.svg)](https://app.koyeb.com/deploy?type=git&repository=github.com/VJbots/Advance-Auto-Filter&branch=koyeb&name=Advanced-Autofilter) 77 | 78 |
Deploy To VPS 79 |

80 |

 81 | git clone https://github.com/VJBots/Advance-Auto-Filter
 82 | # Install Packages
 83 | pip3 install -U -r requirements.txt
 84 | Edit info.py with variables as given below then run bot
 85 | python3 bot.py
 86 | 
87 |

88 |
89 | 90 | 91 | ## Commands 92 | ``` 93 | shortlink - to add multiple shortners in group 94 | logs - to get the rescent errors 95 | stats - to get status of files in db. 96 | filter - add manual filters 97 | filters - view filters 98 | connect - connect to PM. 99 | disconnect - disconnect from PM 100 | del - delete a filter 101 | delall - delete all filters 102 | deleteall - delete all index(autofilter) 103 | delete - delete a specific file from index. 104 | info - get user info 105 | id - get tg ids. 106 | imdb - fetch info from imdb. 107 | users - to get list of my users and ids. 108 | chats - to get list of the my chats and ids 109 | index - to add files from a channel 110 | leave - to leave from a chat. 111 | disable - do disable a chat. 112 | enable - re-enable chat. 113 | ban - to ban a user. 114 | unban - to unban a user. 115 | channel - to get list of total connected channels 116 | broadcast - to broadcast a message to all Eva Maria users 117 | batch - to create link for multiple posts 118 | link - to create link for one post 119 | ``` 120 | ## Support 121 | [![telegram badge](https://img.shields.io/badge/Telegram-Group-30302f?style=flat&logo=telegram)](https://telegram.dog/vj_bot_disscussion) 122 | [![telegram badge](https://img.shields.io/badge/Telegram-Channel-30302f?style=flat&logo=telegram)](https://telegram.dog/vj_botz) 123 | 124 | ## Thanks to 125 | - Thanks To Dan For His Awesome [Library](https://github.com/pyrogram/pyrogram) 126 | - Thanks To [VJ](https://github.com/VJBotz) for Original EvaMaria. 127 | - Thanks To [VJ](https://github.com/VJBotz) for Search in PM feature. 128 | - Thanks To All Everyone In This Journey 129 | 130 | ### Note 131 | 132 | you a Developer. 133 | Fork the repo and edit as per your needs. 134 | 135 | ## Inspiration 136 | - [VJ](https://telegram.dog/VJ_Botz) 137 | -------------------------------------------------------------------------------- /Script.py: -------------------------------------------------------------------------------- 1 | class script(object): 2 | START_TXT = "🧤 Hello {}, I'm {} I Can Provide You Any Movies And Series 😇. \n⚡ You Can Also Use Your Shortner And Bot Will Provide Your Links In Your Group⚡" 3 | 4 | HELP_TXT = """Hᴇʏ {} 5 | If You Want To Create This Type Of Bot Contact Us 6 | 7 | 🔗 For More Information Contact @VJbots_bot 🔗""" 8 | 9 | ABOUT_TXT = """🤖 Mʏ Nᴀᴍᴇ : Movie Search Bot\n 10 | 👑 Oᴡɴᴇʀ : 🏆 Vijay 🏆\n 11 | 📢 ᴜᴘᴅᴀᴛᴇs ᴄʜᴀɴɴᴇʟ : ⚡ VJ Bots ⚡\n 12 | 📝 ʟᴀɴɢᴜᴀɢᴇ : ᴘʏʀᴏɢʀᴀᴍ\n 13 | 📚 ꜰʀᴀᴍᴇᴡᴏʀᴋ : ᴘʏᴛʜᴏɴ 3\n 14 | 📡 ʜᴏsᴛᴇᴅ ᴏɴ : ʜᴇʀᴏᴋᴜ\n 15 | 🌟 ᴠᴇʀsɪᴏɴ : ᴠ 4.0\n""" 16 | 17 | SOURCE_TXT = """ɴᴏᴛᴇ: 18 | ✅ - This Bot Is An Private Project 19 | ✅ - ꜱᴏᴜʀᴄᴇ - ⚡ ʜᴇʀᴇ ⚡ 20 | Dᴇᴠᴇʟᴏᴘᴇʀ:""" 21 | 22 | MANUELFILTER_TXT = """ʜᴇʟᴘ: ꜰɪʟᴛᴇʀꜱ 23 | - ꜰɪʟᴛᴇʀ ɪꜱ ᴀ ꜰᴇᴀᴛᴜʀᴇ ᴡᴇʀᴇ ᴜꜱᴇʀꜱ ᴄᴀɴ ꜱᴇᴛ ᴀᴜᴛᴏᴍᴀᴛᴇᴅ ʀᴇᴘʟɪᴇꜱ ꜰᴏʀ ᴀ ᴘᴀʀᴛɪᴄᴜʟᴀʀ ᴋᴇʏᴡᴏʀᴅ ᴀɴᴅ ɪ ᴡɪʟʟ ʀᴇꜱᴘᴏɴᴅ ᴡʜᴇɴᴇᴠᴇʀ ᴀ ᴋᴇʏᴡᴏʀᴅ ɪꜱ ꜰᴏᴜɴᴅ ɪɴ ᴛʜᴇ ᴍᴇꜱꜱᴀɢᴇ 24 | ɴᴏᴛᴇ: 25 | 1. ᴛʜɪꜱ ʙᴏᴛ ꜱʜᴏᴜʟᴅ ʜᴀᴠᴇ ᴀᴅᴍɪɴ ᴘʀɪᴠɪʟᴇɢᴇ. 26 | 2. ᴏɴʟʏ ᴀᴅᴍɪɴꜱ ᴄᴀɴ ᴀᴅᴅ ꜰɪʟᴛᴇʀꜱ ɪɴ ᴀ ᴄʜᴀᴛ. 27 | 3. ᴀʟᴇʀᴛ ʙᴜᴛᴛᴏɴꜱ ʜᴀᴠᴇ ᴀ ʟɪᴍɪᴛ ᴏꜰ 64 ᴄʜᴀʀᴀᴄᴛᴇʀꜱ. 28 | Cᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ: 29 | • /filter - ᴀᴅᴅ ᴀ ꜰɪʟᴛᴇʀ ɪɴ ᴀ ᴄʜᴀᴛ 30 | • /filters - ʟɪꜱᴛ ᴀʟʟ ᴛʜᴇ ꜰɪʟᴛᴇʀꜱ ᴏꜰ ᴀ ᴄʜᴀᴛ 31 | • /del - ᴅᴇʟᴇᴛᴇ ᴀ ꜱᴘᴇᴄɪꜰɪᴄ ꜰɪʟᴛᴇʀ ɪɴ ᴀ ᴄʜᴀᴛ 32 | • /delall - ᴅᴇʟᴇᴛᴇ ᴛʜᴇ ᴡʜᴏʟᴇ ꜰɪʟᴛᴇʀꜱ ɪɴ ᴀ ᴄʜᴀᴛ (ᴄʜᴀᴛ ᴏᴡɴᴇʀ ᴏɴʟʏ)""" 33 | 34 | BUTTON_TXT = """ʜᴇʟᴘ: ʙᴜᴛᴛᴏɴꜱ 35 | - ᴛʜɪꜱ ʙᴏᴛ ꜱᴜᴘᴘᴏʀᴛꜱ ʙᴏᴛʜ ᴜʀʟ ᴀɴᴅ ᴀʟᴇʀᴛ ɪɴʟɪɴᴇ ʙᴜᴛᴛᴏɴꜱ. 36 | ɴᴏᴛᴇ: 37 | 1. ᴛᴇʟᴇɢʀᴀᴍ ᴡɪʟʟ ɴᴏᴛ ᴀʟʟᴏᴡꜱ ʏᴏᴜ ᴛᴏ ꜱᴇɴᴅ ʙᴜᴛᴛᴏɴꜱ ᴡɪᴛʜᴏᴜᴛ ᴀɴʏ ᴄᴏɴᴛᴇɴᴛ, ꜱᴏ ᴄᴏɴᴛᴇɴᴛ ɪꜱ ᴍᴀɴᴅᴀᴛᴏʀʏ. 38 | 2. ᴛʜɪꜱ ʙᴏᴛ ꜱᴜᴘᴘᴏʀᴛꜱ ʙᴜᴛᴛᴏɴꜱ ᴡɪᴛʜ ᴀɴʏ ᴛᴇʟᴇɢʀᴀᴍ ᴍᴇᴅɪᴀ ᴛʏᴘᴇ. 39 | 3. ʙᴜᴛᴛᴏɴꜱ ꜱʜᴏᴜʟᴅ ʙᴇ ᴘʀᴏᴘᴇʀʟʏ ᴘᴀʀꜱᴇᴅ ᴀꜱ ᴍᴀʀᴋᴅᴏᴡɴ ꜰᴏʀᴍᴀᴛ 40 | ᴜʀʟ ʙᴜᴛᴛᴏɴꜱ: 41 | [Button Text](buttonurl:https://t.me/anjel_neha) 42 | ᴀʟᴇʀᴛ ʙᴜᴛᴛᴏɴꜱ: 43 | [Button Text](buttonalert:ᴛʜɪꜱ ɪꜱ ᴀɴ ᴀʟᴇʀᴛ ᴍᴇꜱꜱᴀɢᴇ)""" 44 | 45 | AUTOFILTER_TXT = """ʜᴇʟᴘ: ᴀᴜᴛᴏ ꜰɪʟᴛᴇʀ 46 | ɴᴏᴛᴇ: Fɪʟᴇ Iɴᴅᴇx 47 | 1. ᴍᴀᴋᴇ ᴍᴇ ᴛʜᴇ ᴀᴅᴍɪɴ ᴏꜰ ʏᴏᴜʀ ᴄʜᴀɴɴᴇʟ ɪꜰ ɪᴛ'ꜱ ᴘʀɪᴠᴀᴛᴇ. 48 | 2. ᴍᴀᴋᴇ ꜱᴜʀᴇ ᴛʜᴀᴛ ʏᴏᴜʀ ᴄʜᴀɴɴᴇʟ ᴅᴏᴇꜱ ɴᴏᴛ ᴄᴏɴᴛᴀɪɴꜱ ᴄᴀᴍʀɪᴘꜱ, ᴘᴏʀɴ ᴀɴᴅ ꜰᴀᴋᴇ ꜰɪʟᴇꜱ. 49 | 3. ꜰᴏʀᴡᴀʀᴅ ᴛʜᴇ ʟᴀꜱᴛ ᴍᴇꜱꜱᴀɢᴇ ᴛᴏ ᴍᴇ ᴡɪᴛʜ Qᴜᴏᴛᴇꜱ. ɪ'ʟʟ ᴀᴅᴅ ᴀʟʟ ᴛʜᴇ ꜰɪʟᴇꜱ ɪɴ ᴛʜᴀᴛ ᴄʜᴀɴɴᴇʟ ᴛᴏ ᴍʏ ᴅʙ. 50 | 51 | Nᴏᴛᴇ: AᴜᴛᴏFɪʟᴛᴇʀ 52 | 1. Aᴅᴅ ᴛʜᴇ ʙᴏᴛ ᴀs ᴀᴅᴍɪɴ ᴏɴ ʏᴏᴜʀ ɢʀᴏᴜᴘ. 53 | 2. Usᴇ /connect ᴀɴᴅ ᴄᴏɴɴᴇᴄᴛ ʏᴏᴜʀ ɢʀᴏᴜᴘ ᴛᴏ ᴛʜᴇ ʙᴏᴛ. 54 | 3. Usᴇ /settings ᴏɴ ʙᴏᴛ's PM ᴀɴᴅ ᴛᴜʀɴ ᴏɴ AᴜᴛᴏFɪʟᴛᴇʀ ᴏɴ ᴛʜᴇ sᴇᴛᴛɪɴɢs ᴍᴇɴᴜ.""" 55 | 56 | CONNECTION_TXT = """ʜᴇʟᴘ: ᴄᴏɴɴᴇᴄᴛɪᴏɴꜱ 57 | - ᴜꜱᴇᴅ ᴛᴏ ᴄᴏɴɴᴇᴄᴛ ʙᴏᴛ ᴛᴏ ᴘᴍ ꜰᴏʀ ᴍᴀɴᴀɢɪɴɢ ꜰɪʟᴛᴇʀꜱ 58 | - ɪᴛ ʜᴇʟᴘꜱ ᴛᴏ ᴀᴠᴏɪᴅ ꜱᴘᴀᴍᴍɪɴɢ ɪɴ ɢʀᴏᴜᴘꜱ. 59 | ɴᴏᴛᴇ: 60 | 1. ᴏɴʟʏ ᴀᴅᴍɪɴꜱ ᴄᴀɴ ᴀᴅᴅ ᴀ ᴄᴏɴɴᴇᴄᴛɪᴏɴ. 61 | 2. ꜱᴇɴᴅ /ᴄᴏɴɴᴇᴄᴛ ꜰᴏʀ ᴄᴏɴɴᴇᴄᴛɪɴɢ ᴍᴇ ᴛᴏ ʏᴏᴜʀ ᴘᴍ 62 | Cᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ: 63 | • /connect - ᴄᴏɴɴᴇᴄᴛ ᴀ ᴘᴀʀᴛɪᴄᴜʟᴀʀ ᴄʜᴀᴛ ᴛᴏ ʏᴏᴜʀ ᴘᴍ 64 | • /disconnect - ᴅɪꜱᴄᴏɴɴᴇᴄᴛ ꜰʀᴏᴍ ᴀ ᴄʜᴀᴛ 65 | • /connections - ʟɪꜱᴛ ᴀʟʟ ʏᴏᴜʀ ᴄᴏɴɴᴇᴄᴛɪᴏɴꜱ""" 66 | 67 | EXTRAMOD_TXT = """ʜᴇʟᴘ: Exᴛʀᴀ Mᴏᴅᴜʟᴇs 68 | ɴᴏᴛᴇ: 69 | ᴛʜᴇꜱᴇ ᴀʀᴇ ᴛʜᴇ ᴇxᴛʀᴀ ꜰᴇᴀᴛᴜʀᴇꜱ ᴏꜰ ᴛʜɪꜱ ʙᴏᴛ 70 | Cᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ: 71 | • /id - ɢᴇᴛ ɪᴅ ᴏꜰ ᴀ ꜱᴘᴇᴄɪꜰɪᴇᴅ ᴜꜱᴇʀ. 72 | • /info - ɢᴇᴛ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ᴀʙᴏᴜᴛ ᴀ ᴜꜱᴇʀ. 73 | • /imdb - ɢᴇᴛ ᴛʜᴇ ꜰɪʟᴍ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ꜰʀᴏᴍ ɪᴍᴅʙ ꜱᴏᴜʀᴄᴇ. 74 | • /search - ɢᴇᴛ ᴛʜᴇ ꜰɪʟᴍ ɪɴꜰᴏʀᴍᴀᴛɪᴏɴ ꜰʀᴏᴍ ᴠᴀʀɪᴏᴜꜱ ꜱᴏᴜʀᴄᴇꜱ.""" 75 | 76 | ADMIN_TXT = """ʜᴇʟᴘ: Aᴅᴍɪɴ Mᴏᴅs 77 | ɴᴏᴛᴇ: 78 | Tʜɪs Mᴏᴅᴜʟᴇ Oɴʟʏ Wᴏʀᴋs Fᴏʀ Mʏ Aᴅᴍɪɴs 79 | Cᴏᴍᴍᴀɴᴅs Aɴᴅ Usᴀɢᴇ: 80 | • /logs - ᴛᴏ ɢᴇᴛ ᴛʜᴇ ʀᴇᴄᴇɴᴛ ᴇʀʀᴏʀꜱ 81 | • /stats - ᴛᴏ ɢᴇᴛ ꜱᴛᴀᴛᴜꜱ ᴏꜰ ꜰɪʟᴇꜱ ɪɴ ᴅʙ. [Tʜɪs Cᴏᴍᴍᴀɴᴅ Cᴀɴ Bᴇ Usᴇᴅ Bʏ Aɴʏᴏɴᴇ] 82 | • /delete - ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴀ ꜱᴘᴇᴄɪꜰɪᴄ ꜰɪʟᴇ ꜰʀᴏᴍ ᴅʙ. 83 | • /users - ᴛᴏ ɢᴇᴛ ʟɪꜱᴛ ᴏꜰ ᴍʏ ᴜꜱᴇʀꜱ ᴀɴᴅ ɪᴅꜱ. 84 | • /chats - ᴛᴏ ɢᴇᴛ ʟɪꜱᴛ ᴏꜰ ᴍʏ ᴄʜᴀᴛꜱ ᴀɴᴅ ɪᴅꜱ 85 | • /leave - ᴛᴏ ʟᴇᴀᴠᴇ ꜰʀᴏᴍ ᴀ ᴄʜᴀᴛ. 86 | • /disable - ᴛᴏ ᴅɪꜱᴀʙʟᴇ ᴀ ᴄʜᴀᴛ. 87 | • /ban - ᴛᴏ ʙᴀɴ ᴀ ᴜꜱᴇʀ. 88 | • /unban - ᴛᴏ ᴜɴʙᴀɴ ᴀ ᴜꜱᴇʀ. 89 | • /channel - ᴛᴏ ɢᴇᴛ ʟɪꜱᴛ ᴏꜰ ᴛᴏᴛᴀʟ ᴄᴏɴɴᴇᴄᴛᴇᴅ ᴄʜᴀɴɴᴇʟꜱ 90 | • /broadcast - ᴛᴏ ʙʀᴏᴀᴅᴄᴀꜱᴛ ᴀ ᴍᴇꜱꜱᴀɢᴇ ᴛᴏ ᴀʟʟ ᴜꜱᴇʀꜱ 91 | • /grp_broadcast - Tᴏ ʙʀᴏᴀᴅᴄᴀsᴛ ᴀ ᴍᴇssᴀɢᴇ ᴛᴏ ᴀʟʟ ᴄᴏɴɴᴇᴄᴛᴇᴅ ɢʀᴏᴜᴘs. 92 | • /gfilter - ᴛᴏ ᴀᴅᴅ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀs 93 | • /gfilters - ᴛᴏ ᴠɪᴇᴡ ʟɪsᴛ ᴏғ ᴀʟʟ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀs 94 | • /delg - ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴀ sᴘᴇᴄɪғɪᴄ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀ 95 | • /request - Tᴏ sᴇɴᴅ ᴀ ʀᴇᴏ̨ᴜᴇsᴛ ᴛᴏ ʙᴏᴛ ᴀᴅᴍɪɴs. Oɴʟʏ ᴡᴏʀᴋs ᴏɴ sᴜᴘᴘᴏʀᴛ ɢʀᴏᴜᴘ.""" 96 | 97 | STATUS_TXT = """★ Tᴏᴛᴀʟ Fɪʟᴇs: {} 98 | ★ Tᴏᴛᴀʟ Usᴇʀs: {} 99 | ★ Tᴏᴛᴀʟ Cʜᴀᴛs: {} 100 | ★ Usᴇᴅ Sᴛᴏʀᴀɢᴇ: {} 101 | ★ Fʀᴇᴇ Sᴛᴏʀᴀɢᴇ: {}""" 102 | 103 | LOG_TEXT_G = """#NewGroup 104 | Gʀᴏᴜᴘ = {}({}) 105 | Tᴏᴛᴀʟ Mᴇᴍʙᴇʀs = {} 106 | Aᴅᴅᴇᴅ Bʏ - {}""" 107 | 108 | LOG_TEXT_P = """#NewUser 109 | ID - {} 110 | Nᴀᴍᴇ - {}""" 111 | 112 | ALRT_TXT = """🔆 Hey {}, Its Not For You❗""" 113 | 114 | OLD_ALRT_TXT = """🔆 Hey {}, ❗Link Expired, Please Request Again ♻""" 115 | 116 | CUDNT_FND = """⚠ No Results, Please Follow Request Tips! \n ♀ Request Tips › [Click Here](https://te.legra.ph/Neha-01-21-2)""" 117 | 118 | I_CUDNT = """⚠ No Results, Please Follow Request Tips ! \n ♀ Request Tips › [Click Here](https://te.legra.ph/Neha-01-21-2)""" 119 | 120 | I_CUD_NT = """⚠ No Results, Please Follow Request Tips!! \n ♀ Request Tips › [Click Here](https://te.legra.ph/Neha-01-21-2)""" 121 | 122 | MVE_NT_FND = """⚠ No Results, Please Follow Request Tips !! \n ♀ Request Tips › [Click Here](https://te.legra.ph/Neha-01-21-2)""" 123 | 124 | TOP_ALRT_MSG = """Cʜᴇᴄᴋɪɴɢ Fᴏʀ Mᴏᴠɪᴇ Iɴ 1 Million Dᴀᴛᴀʙᴀsᴇ...""" 125 | 126 | MELCOW_ENG = """Hᴇʟʟᴏ {} 😍, Aɴᴅ Wᴇʟᴄᴏᴍᴇ Tᴏ {} Gʀᴏᴜᴘ ❤️""" 127 | 128 | OWNER_INFO = """ 129 | ⍟───[ ᴏᴡɴᴇʀ ᴅᴇᴛᴀɪʟꜱ ]───⍟ 130 | 131 | • ꜰᴜʟʟ ɴᴀᴍᴇ : Anjel Neha 132 | • ᴘᴇʀᴍᴀɴᴇɴᴛ ᴅᴍ ʟɪɴᴋ : ᴄʟɪᴄᴋ ʜᴇʀᴇ""" 133 | 134 | REQINFO = """ 135 | Check Your Spelling, Release Date, If You Still Don't Get The Movie Then Type Like This... 136 | ⊱⋅ ──────────────────── ⋅⊰ 137 | #Request Avatar 2009 720p 138 | 139 | Owner Will Update The Movie Within 24Hour""" 140 | 141 | MINFO = """ 142 | ⚠ How To Request Movies ⁉️ » 143 | ⊱⋅ ─────────────── ⋅⊰ 144 | › Avatar ✅ 145 | › Avatar 2009 720p ✅ 146 | › Avatar 2009 720p Hindi ✅ 147 | 148 | › Don't Type Movie Nickname, Don't Use Other Fonts, No Emoji, No Symbols ❌ 149 | """ 150 | 151 | SINFO = """ 152 | ⚠ How To Request Series ⁉️ » 153 | ⊱⋅ ─────────────── ⋅⊰ 154 | › Flash S01 ✅ 155 | › Flash Hindi ✅ 156 | › Flash S01E02 Hindi ✅ 157 | 158 | › Don't Type Movie Nickname, Don't free Use Other Fonts, No Emoji, No Symbols ❌ 159 | """ 160 | 161 | NORSLTS = """ 162 | ★ #Auto_Request ★ 163 | 164 | 🔆 Request : 🎗️`{}`🎗️ 165 | ♦️ Requested By : {} 166 | ♦️ User ID : `{}` """ 167 | 168 | CAPTION = """ 169 | ɴᴀᴍᴇ: {file_name} \n\nJᴏɪɴ Nᴏᴡ: [⚡ VJ Bots⚡](https://t.me/VJ_Bots)""" 170 | 171 | IMDB_TEMPLATE_TXT = """📟 ᴛɪᴛᴛʟᴇ : {title} \n🌟 ʀᴀᴛɪɴɢ : {rating} \n🎭 ɢᴇɴʀᴇ : {genres} \n📆 ʀᴇʟᴇᴀsᴇ : {year} \n⏰ ᴅᴜʀᴀᴛɪᴏɴ : {runtime}\n\n🔖 𝓟𝓵𝓸𝓽 : `{plot}` \n\n⚡ ᴘᴏᴡᴇʀᴇᴅ ʙʏ ⚡ : {message.chat.title}""" 172 | 173 | ALL_FILTERS = """ 174 | Hᴇʏ {}, Tʜᴇsᴇ ᴀʀᴇ ᴍʏ ᴛʜʀᴇᴇ ᴛʏᴘᴇs ᴏғ ғɪʟᴛᴇʀs.""" 175 | 176 | GFILTER_TXT = """ 177 | Wᴇʟᴄᴏᴍᴇ ᴛᴏ Gʟᴏʙᴀʟ Fɪʟᴛᴇʀs. Gʟᴏʙᴀʟ Fɪʟᴛᴇʀs ᴀʀᴇ ᴛʜᴇ ғɪʟᴛᴇʀs sᴇᴛ ʙʏ ʙᴏᴛ ᴀᴅᴍɪɴs ᴡʜɪᴄʜ ᴡɪʟʟ ᴡᴏʀᴋ ᴏɴ ᴀʟʟ ɢʀᴏᴜᴘs. 178 | 179 | Aᴠᴀɪʟᴀʙʟᴇ ᴄᴏᴍᴍᴀɴᴅs: 180 | • /gfilter - Tᴏ ᴄʀᴇᴀᴛᴇ ᴀ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀ. 181 | • /gfilters - Tᴏ ᴠɪᴇᴡ ᴀʟʟ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀs. 182 | • /delg - Tᴏ ᴅᴇʟᴇᴛᴇ ᴀ ᴘᴀʀᴛɪᴄᴜʟᴀʀ ɢʟᴏʙᴀʟ ғɪʟᴛᴇʀ. 183 | • /delallg - ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴀʟʟ ɢʟᴏʙᴀʟ ꜰɪʟᴛᴇʀꜱ.""" 184 | 185 | FILE_STORE_TXT = """ 186 | Fɪʟᴇ sᴛᴏʀᴇ ɪs ᴛʜᴇ ғᴇᴀᴛᴜʀᴇ ᴡʜɪᴄʜ ᴡɪʟʟ ᴄʀᴇᴀᴛᴇ ᴀ sʜᴀʀᴇᴀʙʟᴇ ʟɪɴᴋ ᴏғ ᴀ sɪɴɢʟᴇ ᴏʀ ᴍᴜʟᴛɪᴘʟᴇ ғɪʟᴇs. 187 | 188 | Aᴠᴀɪʟᴀʙʟᴇ ᴄᴏᴍᴍᴀɴᴅs: 189 | • /batch - Tᴏ ᴄʀᴇᴀᴛᴇ ᴀ ʙᴀᴛᴄʜ ʟɪɴᴋ ᴏғ ᴍᴜʟᴛɪᴘʟᴇ ғɪʟᴇs. 190 | • /link - Tᴏ ᴄʀᴇᴀᴛᴇ ᴀ sɪɴɢʟᴇ ғɪʟᴇ sᴛᴏʀᴇ ʟɪɴᴋ. 191 | • /pbatch - Jᴜsᴛ ʟɪᴋᴇ /batch, ʙᴜᴛ ᴛʜᴇ ғɪʟᴇs ᴡɪʟʟ ʙᴇ sᴇɴᴅ ᴡɪᴛʜ ғᴏʀᴡᴀʀᴅ ʀᴇsᴛʀɪᴄᴛɪᴏɴs. 192 | • /plink - Jᴜsᴛ ʟɪᴋᴇ /link, ʙᴜᴛ ᴛʜᴇ ғɪʟᴇ ᴡɪʟʟ ʙᴇ sᴇɴᴅ ᴡɪᴛʜ ғᴏʀᴡᴀʀᴅ ʀᴇsᴛʀɪᴄᴛɪᴏɴ.""" 193 | 194 | RESTART_TXT = """ 195 | Bᴏᴛ Rᴇsᴛᴀʀᴛᴇᴅ ! 196 | 197 | 📅 Dᴀᴛᴇ : {} 198 | ⏰Tɪᴍᴇ : {} 199 | 🌐 Tɪᴍᴇᴢᴏɴᴇ : Asia/Delhi""" 200 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Nataliya", 3 | "description": "When you going to send file on telegram channel this bot will save that in database, So you can search that easily in inline mode", 4 | "stack": "container", 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://t.me/MrperfectOffcial_bot", 19 | "repository": "https://t.me/MrperfectOffcial_bot", 20 | "env": { 21 | "BOT_TOKEN": { 22 | "description": "Your bot token.", 23 | "required": true 24 | }, 25 | "API_ID": { 26 | "description": "Get this value from https://my.telegram.org", 27 | "required": true 28 | }, 29 | "API_HASH": { 30 | "description": "Get this value from https://my.telegram.org", 31 | "required": true 32 | }, 33 | "CHANNELS": { 34 | "description": "Username or ID of channel or group. Separate multiple IDs by space.", 35 | "required": false 36 | }, 37 | "ADMINS": { 38 | "description": "Username or ID of Admin. Separate multiple Admins by space.", 39 | "required": true 40 | }, 41 | "PICS": { 42 | "description": "Add some telegraph link of pictures .", 43 | "required": false 44 | }, 45 | "LOG_CHANNEL": { 46 | "description": "Bot Logs,Give a channel id with -100xxxxxxx", 47 | "required": true 48 | }, 49 | "AUTH_USERS": { 50 | "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.", 51 | "required": false 52 | }, 53 | "AUTH_CHANNEL": { 54 | "description": "ID of channel.Make sure bot is admin in this channel. Without subscribing this channel users cannot use bot.", 55 | "required": false 56 | }, 57 | "DATABASE_URI": { 58 | "description": "mongoDB URI. Get this value from https://www.mongodb.com. For more help watch this video - https://youtu.be/dsuTn4qV2GA", 59 | "required": true 60 | }, 61 | "DATABASE_NAME": { 62 | "description": "Name of the database in mongoDB. For more help watch this video - https://youtu.be/dsuTn4qV2GA", 63 | "required": false 64 | }, 65 | "COLLECTION_NAME": { 66 | "description": "Name of the collections. Defaults to Telegram_files. If you are using the same database, then use different collection name for each bot", 67 | "value": "Telegram_files", 68 | "required": false 69 | } 70 | }, 71 | "addons": [], 72 | "buildpacks": [{ 73 | "url": "heroku/python" 74 | }], 75 | "formation": { 76 | "worker": { 77 | "quantity": 1, 78 | "size": "free" 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /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.INFO) 7 | logging.getLogger("pyrogram").setLevel(logging.ERROR) 8 | logging.getLogger("imdbpy").setLevel(logging.ERROR) 9 | 10 | from pyrogram import Client, __version__ 11 | from pyrogram.raw.all import layer 12 | from database.ia_filterdb import Media 13 | from database.users_chats_db import db 14 | from info import SESSION, API_ID, API_HASH, BOT_TOKEN, LOG_STR, LOG_CHANNEL, PORT 15 | from utils import temp 16 | from typing import Union, Optional, AsyncGenerator 17 | from pyrogram import types 18 | from Script import script 19 | from datetime import date, datetime 20 | import pytz 21 | from aiohttp import web 22 | from plugins import web_server 23 | 24 | class Bot(Client): 25 | 26 | def __init__(self): 27 | super().__init__( 28 | name=SESSION, 29 | api_id=API_ID, 30 | api_hash=API_HASH, 31 | bot_token=BOT_TOKEN, 32 | workers=50, 33 | plugins={"root": "plugins"}, 34 | sleep_threshold=5, 35 | ) 36 | 37 | async def start(self): 38 | b_users, b_chats = await db.get_banned() 39 | temp.BANNED_USERS = b_users 40 | temp.BANNED_CHATS = b_chats 41 | await super().start() 42 | await Media.ensure_indexes() 43 | me = await self.get_me() 44 | temp.ME = me.id 45 | temp.U_NAME = me.username 46 | temp.B_NAME = me.first_name 47 | self.username = '@' + me.username 48 | logging.info(f"{me.first_name} with for Pyrogram v{__version__} (Layer {layer}) started on {me.username}.") 49 | logging.info(LOG_STR) 50 | tz = pytz.timezone('Asia/Kolkata') 51 | today = date.today() 52 | now = datetime.now(tz) 53 | time = now.strftime("%H:%M:%S %p") 54 | await self.send_message(chat_id=LOG_CHANNEL, text=script.RESTART_TXT.format(today, time)) 55 | app = web.AppRunner(await web_server()) 56 | await app.setup() 57 | bind_address = "0.0.0.0" 58 | await web.TCPSite(app, bind_address, PORT).start() 59 | 60 | async def stop(self, *args): 61 | await super().stop() 62 | logging.info("Bot stopped. Bye.") 63 | 64 | async def iter_messages( 65 | self, 66 | chat_id: Union[int, str], 67 | limit: int, 68 | offset: int = 0, 69 | ) -> Optional[AsyncGenerator["types.Message", None]]: 70 | """Iterate through a chat sequentially. 71 | This convenience method does the same as repeatedly calling :meth:`~pyrogram.Client.get_messages` in a loop, thus saving 72 | you from the hassle of setting up boilerplate code. It is useful for getting the whole chat messages with a 73 | single call. 74 | Parameters: 75 | chat_id (``int`` | ``str``): 76 | Unique identifier (int) or username (str) of the target chat. 77 | For your personal cloud (Saved Messages) you can simply use "me" or "self". 78 | For a contact that exists in your Telegram address book you can use his phone number (str). 79 | 80 | limit (``int``): 81 | Identifier of the last message to be returned. 82 | 83 | offset (``int``, *optional*): 84 | Identifier of the first message to be returned. 85 | Defaults to 0. 86 | Returns: 87 | ``Generator``: A generator yielding :obj:`~pyrogram.types.Message` objects. 88 | Example: 89 | .. code-block:: python 90 | for message in app.iter_messages("pyrogram", 1, 15000): 91 | print(message.text) 92 | """ 93 | current = offset 94 | while True: 95 | new_diff = min(200, limit - current) 96 | if new_diff <= 0: 97 | return 98 | messages = await self.get_messages(chat_id, list(range(current, current+new_diff+1))) 99 | for message in messages: 100 | yield message 101 | current += 1 102 | 103 | 104 | app = Bot() 105 | app.run() 106 | -------------------------------------------------------------------------------- /database/connections_mdb.py: -------------------------------------------------------------------------------- 1 | import pymongo 2 | 3 | from info import DATABASE_URI, DATABASE_NAME 4 | 5 | import logging 6 | logger = logging.getLogger(__name__) 7 | logger.setLevel(logging.ERROR) 8 | 9 | myclient = pymongo.MongoClient(DATABASE_URI) 10 | mydb = myclient[DATABASE_NAME] 11 | mycol = mydb['CONNECTION'] 12 | 13 | 14 | async def add_connection(group_id, user_id): 15 | query = mycol.find_one( 16 | { "_id": user_id }, 17 | { "_id": 0, "active_group": 0 } 18 | ) 19 | if query is not None: 20 | group_ids = [x["group_id"] for x in query["group_details"]] 21 | if group_id in group_ids: 22 | return False 23 | 24 | group_details = { 25 | "group_id" : group_id 26 | } 27 | 28 | data = { 29 | '_id': user_id, 30 | 'group_details' : [group_details], 31 | 'active_group' : group_id, 32 | } 33 | 34 | if mycol.count_documents( {"_id": user_id} ) == 0: 35 | try: 36 | mycol.insert_one(data) 37 | return True 38 | except: 39 | logger.exception('Some error occurred!', exc_info=True) 40 | 41 | else: 42 | try: 43 | mycol.update_one( 44 | {'_id': user_id}, 45 | { 46 | "$push": {"group_details": group_details}, 47 | "$set": {"active_group" : group_id} 48 | } 49 | ) 50 | return True 51 | except: 52 | logger.exception('Some error occurred!', exc_info=True) 53 | 54 | 55 | async def active_connection(user_id): 56 | 57 | query = mycol.find_one( 58 | { "_id": user_id }, 59 | { "_id": 0, "group_details": 0 } 60 | ) 61 | if not query: 62 | return None 63 | 64 | group_id = query['active_group'] 65 | return int(group_id) if group_id != None else None 66 | 67 | 68 | async def all_connections(user_id): 69 | query = mycol.find_one( 70 | { "_id": user_id }, 71 | { "_id": 0, "active_group": 0 } 72 | ) 73 | if query is not None: 74 | return [x["group_id"] for x in query["group_details"]] 75 | else: 76 | return None 77 | 78 | 79 | async def if_active(user_id, group_id): 80 | query = mycol.find_one( 81 | { "_id": user_id }, 82 | { "_id": 0, "group_details": 0 } 83 | ) 84 | return query is not None and query['active_group'] == group_id 85 | 86 | 87 | async def make_active(user_id, group_id): 88 | update = mycol.update_one( 89 | {'_id': user_id}, 90 | {"$set": {"active_group" : group_id}} 91 | ) 92 | return update.modified_count != 0 93 | 94 | 95 | async def make_inactive(user_id): 96 | update = mycol.update_one( 97 | {'_id': user_id}, 98 | {"$set": {"active_group" : None}} 99 | ) 100 | return update.modified_count != 0 101 | 102 | 103 | async def delete_connection(user_id, group_id): 104 | 105 | try: 106 | update = mycol.update_one( 107 | {"_id": user_id}, 108 | {"$pull" : { "group_details" : {"group_id":group_id} } } 109 | ) 110 | if update.modified_count == 0: 111 | return False 112 | query = mycol.find_one( 113 | { "_id": user_id }, 114 | { "_id": 0 } 115 | ) 116 | if len(query["group_details"]) >= 1: 117 | if query['active_group'] == group_id: 118 | prvs_group_id = query["group_details"][len(query["group_details"]) - 1]["group_id"] 119 | 120 | mycol.update_one( 121 | {'_id': user_id}, 122 | {"$set": {"active_group" : prvs_group_id}} 123 | ) 124 | else: 125 | mycol.update_one( 126 | {'_id': user_id}, 127 | {"$set": {"active_group" : None}} 128 | ) 129 | return True 130 | except Exception as e: 131 | logger.exception(f'Some error occurred! {e}', exc_info=True) 132 | return False 133 | 134 | -------------------------------------------------------------------------------- /database/filters_mdb.py: -------------------------------------------------------------------------------- 1 | import pymongo 2 | from info import DATABASE_URI, DATABASE_NAME 3 | from pyrogram import enums 4 | import logging 5 | logger = logging.getLogger(__name__) 6 | logger.setLevel(logging.ERROR) 7 | 8 | myclient = pymongo.MongoClient(DATABASE_URI) 9 | mydb = myclient[DATABASE_NAME] 10 | 11 | 12 | 13 | async def add_filter(grp_id, text, reply_text, btn, file, alert): 14 | mycol = mydb[str(grp_id)] 15 | # mycol.create_index([('text', 'text')]) 16 | 17 | data = { 18 | 'text':str(text), 19 | 'reply':str(reply_text), 20 | 'btn':str(btn), 21 | 'file':str(file), 22 | 'alert':str(alert) 23 | } 24 | 25 | try: 26 | mycol.update_one({'text': str(text)}, {"$set": data}, upsert=True) 27 | except: 28 | logger.exception('Some error occured!', exc_info=True) 29 | 30 | 31 | async def find_filter(group_id, name): 32 | mycol = mydb[str(group_id)] 33 | 34 | query = mycol.find( {"text":name}) 35 | # query = mycol.find( { "$text": {"$search": name}}) 36 | try: 37 | for file in query: 38 | reply_text = file['reply'] 39 | btn = file['btn'] 40 | fileid = file['file'] 41 | try: 42 | alert = file['alert'] 43 | except: 44 | alert = None 45 | return reply_text, btn, alert, fileid 46 | except: 47 | return None, None, None, None 48 | 49 | 50 | async def get_filters(group_id): 51 | mycol = mydb[str(group_id)] 52 | 53 | texts = [] 54 | query = mycol.find() 55 | try: 56 | for file in query: 57 | text = file['text'] 58 | texts.append(text) 59 | except: 60 | pass 61 | return texts 62 | 63 | 64 | async def delete_filter(message, text, group_id): 65 | mycol = mydb[str(group_id)] 66 | 67 | myquery = {'text':text } 68 | query = mycol.count_documents(myquery) 69 | if query == 1: 70 | mycol.delete_one(myquery) 71 | await message.reply_text( 72 | f"'`{text}`' deleted. I'll not respond to that filter anymore.", 73 | quote=True, 74 | parse_mode=enums.ParseMode.MARKDOWN 75 | ) 76 | else: 77 | await message.reply_text("Couldn't find that filter!", quote=True) 78 | 79 | 80 | async def del_all(message, group_id, title): 81 | if str(group_id) not in mydb.list_collection_names(): 82 | await message.edit_text(f"Nothing to remove in {title}!") 83 | return 84 | 85 | mycol = mydb[str(group_id)] 86 | try: 87 | mycol.drop() 88 | await message.edit_text(f"All filters from {title} has been removed") 89 | except: 90 | await message.edit_text("Couldn't remove all filters from group!") 91 | return 92 | 93 | 94 | async def count_filters(group_id): 95 | mycol = mydb[str(group_id)] 96 | 97 | count = mycol.count() 98 | return False if count == 0 else count 99 | 100 | 101 | async def filter_stats(): 102 | collections = mydb.list_collection_names() 103 | 104 | if "CONNECTION" in collections: 105 | collections.remove("CONNECTION") 106 | 107 | totalcount = 0 108 | for collection in collections: 109 | mycol = mydb[collection] 110 | count = mycol.count() 111 | totalcount += count 112 | 113 | totalcollections = len(collections) 114 | 115 | return totalcollections, totalcount 116 | -------------------------------------------------------------------------------- /database/gfilters_mdb.py: -------------------------------------------------------------------------------- 1 | import pymongo 2 | from info import DATABASE_URI, DATABASE_NAME 3 | from pyrogram import enums 4 | import logging 5 | logger = logging.getLogger(__name__) 6 | logger.setLevel(logging.ERROR) 7 | 8 | myclient = pymongo.MongoClient(DATABASE_URI) 9 | mydb = myclient[DATABASE_NAME] 10 | 11 | 12 | 13 | async def add_gfilter(gfilters, text, reply_text, btn, file, alert): 14 | mycol = mydb[str(gfilters)] 15 | # mycol.create_index([('text', 'text')]) 16 | 17 | data = { 18 | 'text':str(text), 19 | 'reply':str(reply_text), 20 | 'btn':str(btn), 21 | 'file':str(file), 22 | 'alert':str(alert) 23 | } 24 | 25 | try: 26 | mycol.update_one({'text': str(text)}, {"$set": data}, upsert=True) 27 | except: 28 | logger.exception('Some error occured!', exc_info=True) 29 | 30 | 31 | async def find_gfilter(gfilters, name): 32 | mycol = mydb[str(gfilters)] 33 | 34 | query = mycol.find( {"text":name}) 35 | # query = mycol.find( { "$text": {"$search": name}}) 36 | try: 37 | for file in query: 38 | reply_text = file['reply'] 39 | btn = file['btn'] 40 | fileid = file['file'] 41 | try: 42 | alert = file['alert'] 43 | except: 44 | alert = None 45 | return reply_text, btn, alert, fileid 46 | except: 47 | return None, None, None, None 48 | 49 | 50 | async def get_gfilters(gfilters): 51 | mycol = mydb[str(gfilters)] 52 | 53 | texts = [] 54 | query = mycol.find() 55 | try: 56 | for file in query: 57 | text = file['text'] 58 | texts.append(text) 59 | except: 60 | pass 61 | return texts 62 | 63 | 64 | async def delete_gfilter(message, text, gfilters): 65 | mycol = mydb[str(gfilters)] 66 | 67 | myquery = {'text':text } 68 | query = mycol.count_documents(myquery) 69 | if query == 1: 70 | mycol.delete_one(myquery) 71 | await message.reply_text( 72 | f"'`{text}`' deleted. I'll not respond to that gfilter anymore.", 73 | quote=True, 74 | parse_mode=enums.ParseMode.MARKDOWN 75 | ) 76 | else: 77 | await message.reply_text("Couldn't find that gfilter!", quote=True) 78 | 79 | async def del_allg(message, gfilters): 80 | if str(gfilters) not in mydb.list_collection_names(): 81 | await message.edit_text("Nothing to remove !") 82 | return 83 | 84 | mycol = mydb[str(gfilters)] 85 | try: 86 | mycol.drop() 87 | await message.edit_text(f"All gfilters has been removed !") 88 | except: 89 | await message.edit_text("Couldn't remove all gfilters !") 90 | return 91 | 92 | async def count_gfilters(gfilters): 93 | mycol = mydb[str(gfilters)] 94 | 95 | count = mycol.count() 96 | return False if count == 0 else count 97 | 98 | 99 | async def gfilter_stats(): 100 | collections = mydb.list_collection_names() 101 | 102 | if "CONNECTION" in collections: 103 | collections.remove("CONNECTION") 104 | 105 | totalcount = 0 106 | for collection in collections: 107 | mycol = mydb[collection] 108 | count = mycol.count() 109 | totalcount += count 110 | 111 | totalcollections = len(collections) 112 | 113 | return totalcollections, totalcount 114 | -------------------------------------------------------------------------------- /database/ia_filterdb.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from struct import pack 3 | import re 4 | import base64 5 | from pyrogram.file_id import FileId 6 | from pymongo.errors import DuplicateKeyError 7 | from umongo import Instance, Document, fields 8 | from motor.motor_asyncio import AsyncIOMotorClient 9 | from marshmallow.exceptions import ValidationError 10 | from info import DATABASE_URI, DATABASE_NAME, COLLECTION_NAME, USE_CAPTION_FILTER, MAX_B_TN 11 | from utils import get_settings, save_group_settings 12 | 13 | logger = logging.getLogger(__name__) 14 | logger.setLevel(logging.INFO) 15 | 16 | 17 | client = AsyncIOMotorClient(DATABASE_URI) 18 | db = client[DATABASE_NAME] 19 | instance = Instance.from_db(db) 20 | 21 | @instance.register 22 | class Media(Document): 23 | file_id = fields.StrField(attribute='_id') 24 | file_ref = fields.StrField(allow_none=True) 25 | file_name = fields.StrField(required=True) 26 | file_size = fields.IntField(required=True) 27 | file_type = fields.StrField(allow_none=True) 28 | mime_type = fields.StrField(allow_none=True) 29 | caption = fields.StrField(allow_none=True) 30 | 31 | class Meta: 32 | indexes = ('$file_name', ) 33 | collection_name = COLLECTION_NAME 34 | 35 | 36 | async def save_file(media): 37 | """Save file in database""" 38 | 39 | # TODO: Find better way to get same file_id for same media to avoid duplicates 40 | file_id, file_ref = unpack_new_file_id(media.file_id) 41 | file_name = re.sub(r"(_|\-|\.|\+)", " ", str(media.file_name)) 42 | try: 43 | file = Media( 44 | file_id=file_id, 45 | file_ref=file_ref, 46 | file_name=file_name, 47 | file_size=media.file_size, 48 | file_type=media.file_type, 49 | mime_type=media.mime_type, 50 | caption=media.caption.html if media.caption else None, 51 | ) 52 | except ValidationError: 53 | logger.exception('Error occurred while saving file in database') 54 | return False, 2 55 | else: 56 | try: 57 | await file.commit() 58 | except DuplicateKeyError: 59 | logger.warning( 60 | f'{getattr(media, "file_name", "NO_FILE")} is already saved in database' 61 | ) 62 | 63 | return False, 0 64 | else: 65 | logger.info(f'{getattr(media, "file_name", "NO_FILE")} is saved to database') 66 | return True, 1 67 | 68 | 69 | 70 | async def get_search_results(chat_id, query, file_type=None, max_results=10, offset=0, filter=False): 71 | """For given query return (results, next_offset)""" 72 | if chat_id is not None: 73 | settings = await get_settings(int(chat_id)) 74 | try: 75 | if settings['max_btn']: 76 | max_results = 10 77 | else: 78 | max_results = int(MAX_B_TN) 79 | except KeyError: 80 | await save_group_settings(int(chat_id), 'max_btn', False) 81 | settings = await get_settings(int(chat_id)) 82 | if settings['max_btn']: 83 | max_results = 10 84 | else: 85 | max_results = int(MAX_B_TN) 86 | query = query.strip() 87 | #if filter: 88 | #better ? 89 | #query = query.replace(' ', r'(\s|\.|\+|\-|_)') 90 | #raw_pattern = r'(\s|_|\-|\.|\+)' + query + r'(\s|_|\-|\.|\+)' 91 | if not query: 92 | raw_pattern = '.' 93 | elif ' ' not in query: 94 | raw_pattern = r'(\b|[\.\+\-_])' + query + r'(\b|[\.\+\-_])' 95 | else: 96 | raw_pattern = query.replace(' ', r'.*[\s\.\+\-_]') 97 | 98 | try: 99 | regex = re.compile(raw_pattern, flags=re.IGNORECASE) 100 | except: 101 | return [] 102 | 103 | if USE_CAPTION_FILTER: 104 | filter = {'$or': [{'file_name': regex}, {'caption': regex}]} 105 | else: 106 | filter = {'file_name': regex} 107 | 108 | if file_type: 109 | filter['file_type'] = file_type 110 | 111 | total_results = await Media.count_documents(filter) 112 | next_offset = offset + max_results 113 | 114 | if next_offset > total_results: 115 | next_offset = '' 116 | 117 | cursor = Media.find(filter) 118 | # Sort by recent 119 | cursor.sort('$natural', -1) 120 | # Slice files according to offset and max results 121 | cursor.skip(offset).limit(max_results) 122 | # Get list of files 123 | files = await cursor.to_list(length=max_results) 124 | 125 | return files, next_offset, total_results 126 | 127 | async def get_bad_files(query, file_type=None, max_results=100, offset=0, filter=False): 128 | """For given query return (results, next_offset)""" 129 | query = query.strip() 130 | #if filter: 131 | #better ? 132 | #query = query.replace(' ', r'(\s|\.|\+|\-|_)') 133 | #raw_pattern = r'(\s|_|\-|\.|\+)' + query + r'(\s|_|\-|\.|\+)' 134 | if not query: 135 | raw_pattern = '.' 136 | elif ' ' not in query: 137 | raw_pattern = r'(\b|[\.\+\-_])' + query + r'(\b|[\.\+\-_])' 138 | else: 139 | raw_pattern = query.replace(' ', r'.*[\s\.\+\-_]') 140 | 141 | try: 142 | regex = re.compile(raw_pattern, flags=re.IGNORECASE) 143 | except: 144 | return [] 145 | 146 | if USE_CAPTION_FILTER: 147 | filter = {'$or': [{'file_name': regex}, {'caption': regex}]} 148 | else: 149 | filter = {'file_name': regex} 150 | 151 | if file_type: 152 | filter['file_type'] = file_type 153 | 154 | total_results = await Media.count_documents(filter) 155 | next_offset = offset + max_results 156 | 157 | if next_offset > total_results: 158 | next_offset = '' 159 | 160 | cursor = Media.find(filter) 161 | # Sort by recent 162 | cursor.sort('$natural', -1) 163 | # Slice files according to offset and max results 164 | cursor.skip(offset).limit(max_results) 165 | # Get list of files 166 | files = await cursor.to_list(length=max_results) 167 | 168 | return files, next_offset, total_results 169 | 170 | async def get_file_details(query): 171 | filter = {'file_id': query} 172 | cursor = Media.find(filter) 173 | filedetails = await cursor.to_list(length=1) 174 | return filedetails 175 | 176 | 177 | def encode_file_id(s: bytes) -> str: 178 | r = b"" 179 | n = 0 180 | 181 | for i in s + bytes([22]) + bytes([4]): 182 | if i == 0: 183 | n += 1 184 | else: 185 | if n: 186 | r += b"\x00" + bytes([n]) 187 | n = 0 188 | 189 | r += bytes([i]) 190 | 191 | return base64.urlsafe_b64encode(r).decode().rstrip("=") 192 | 193 | 194 | def encode_file_ref(file_ref: bytes) -> str: 195 | return base64.urlsafe_b64encode(file_ref).decode().rstrip("=") 196 | 197 | 198 | def unpack_new_file_id(new_file_id): 199 | """Return file_id, file_ref""" 200 | decoded = FileId.decode(new_file_id) 201 | file_id = encode_file_id( 202 | pack( 203 | "{vazha['reason']}.", 35 | reply_markup=reply_markup) 36 | try: 37 | await k.pin() 38 | except: 39 | pass 40 | await bot.leave_chat(message.chat.id) 41 | -------------------------------------------------------------------------------- /plugins/broadcast.py: -------------------------------------------------------------------------------- 1 | 2 | from pyrogram import Client, filters 3 | import datetime 4 | import time 5 | from database.users_chats_db import db 6 | from info import ADMINS 7 | from utils import broadcast_messages 8 | import asyncio 9 | 10 | @Client.on_message(filters.command("broadcast") & filters.user(ADMINS) & filters.reply) 11 | # https://t.me/GetTGLink/4178 12 | async def verupikkals(bot, message): 13 | users = await db.get_all_users() 14 | b_msg = message.reply_to_message 15 | sts = await message.reply_text( 16 | text='Broadcasting your messages...' 17 | ) 18 | start_time = time.time() 19 | total_users = await db.total_users_count() 20 | done = 0 21 | blocked = 0 22 | deleted = 0 23 | failed =0 24 | 25 | success = 0 26 | async for user in users: 27 | pti, sh = await broadcast_messages(int(user['id']), b_msg) 28 | if pti: 29 | success += 1 30 | elif pti == False: 31 | if sh == "Blocked": 32 | blocked+=1 33 | elif sh == "Deleted": 34 | deleted += 1 35 | elif sh == "Error": 36 | failed += 1 37 | done += 1 38 | await asyncio.sleep(2) 39 | if not done % 20: 40 | await sts.edit(f"Broadcast in progress:\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}") 41 | time_taken = datetime.timedelta(seconds=int(time.time()-start_time)) 42 | await sts.edit(f"Broadcast Completed:\nCompleted in {time_taken} seconds.\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}") 43 | 44 | @Client.on_message(filters.command("grp_broadcast") & filters.user(ADMINS) & filters.reply) 45 | async def grp_brodcst(bot, message): 46 | chats = await db.get_all_chats() 47 | b_msg = message.reply_to_message 48 | sts = await message.reply_text( 49 | text='Broadcasting your messages...' 50 | ) 51 | start_time = time.time() 52 | total_chats = await db.total_chat_count() 53 | done = 0 54 | failed =0 55 | 56 | success = 0 57 | async for chat in chats: 58 | pti, sh = await broadcast_messages(int(chat['id']), b_msg) 59 | if pti: 60 | success += 1 61 | elif pti == False: 62 | if sh == "Blocked": 63 | blocked+=1 64 | elif sh == "Deleted": 65 | deleted += 1 66 | elif sh == "Error": 67 | failed += 1 68 | done += 1 69 | await asyncio.sleep(2) 70 | if not done % 20: 71 | await sts.edit(f"Broadcast in progress:\n\nTotal Chats {total_chats}\nCompleted: {done} / {total_chats}\nSuccess: {success}\nFailed: {failed}") 72 | time_taken = datetime.timedelta(seconds=int(time.time()-start_time)) 73 | await sts.edit(f"Broadcast Completed:\nCompleted in {time_taken} seconds.\n\nTotal Chats {total_chats}\nCompleted: {done} / {total_chats}\nSuccess: {success}\nFailed: {failed}") 74 | -------------------------------------------------------------------------------- /plugins/channel.py: -------------------------------------------------------------------------------- 1 | from pyrogram import Client, filters 2 | from info import CHANNELS 3 | from database.ia_filterdb import save_file 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) -------------------------------------------------------------------------------- /plugins/commands.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | import random 4 | import asyncio 5 | from Script import script 6 | from pyrogram import Client, filters, enums 7 | from pyrogram.errors import ChatAdminRequired, FloodWait 8 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup 9 | from database.ia_filterdb import Media, get_file_details, unpack_new_file_id, get_bad_files 10 | from database.users_chats_db import db 11 | from info import CHANNELS, ADMINS, AUTH_CHANNEL, LOG_CHANNEL, PICS, BATCH_FILE_CAPTION, CUSTOM_FILE_CAPTION, PROTECT_CONTENT, CHNL_LNK, GRP_LNK, REQST_CHANNEL, SUPPORT_CHAT_ID, MAX_B_TN 12 | from utils import get_settings, get_size, is_subscribed, save_group_settings, temp 13 | from database.connections_mdb import active_connection 14 | import re 15 | import json 16 | import base64 17 | logger = logging.getLogger(__name__) 18 | 19 | BATCH_FILES = {} 20 | 21 | @Client.on_message(filters.command("start") & filters.incoming) 22 | async def start(client, message): 23 | if message.chat.type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: 24 | buttons = [ 25 | [ 26 | InlineKeyboardButton('📣 Uᴘᴅᴀᴛᴇs 📣', url='https://t.me/VJ_Bots') 27 | ], 28 | [ 29 | InlineKeyboardButton('♠️ Subscribe ♠️', url='https://youtube.com/@Tech_VJ'), 30 | ], 31 | [ 32 | InlineKeyboardButton('🎗️ Owner 🎗️',url='https://t.me/vjbots_bot') 33 | ] 34 | ] 35 | reply_markup = InlineKeyboardMarkup(buttons) 36 | await message.reply(script.START_TXT.format(message.from_user.mention if message.from_user else message.chat.title, temp.U_NAME, temp.B_NAME), reply_markup=reply_markup) 37 | await asyncio.sleep(2) # 😢 https://github.com/EvamariaTG/EvaMaria/blob/master/plugins/p_ttishow.py#L17 😬 wait a bit, before checking. 38 | if not await db.get_chat(message.chat.id): 39 | total=await client.get_chat_members_count(message.chat.id) 40 | await client.send_message(LOG_CHANNEL, script.LOG_TEXT_G.format(message.chat.title, message.chat.id, total, "Unknown")) 41 | await db.add_chat(message.chat.id, message.chat.title) 42 | return 43 | if not await db.is_user_exist(message.from_user.id): 44 | await db.add_user(message.from_user.id, message.from_user.first_name) 45 | await client.send_message(LOG_CHANNEL, script.LOG_TEXT_P.format(message.from_user.id, message.from_user.mention)) 46 | if len(message.command) != 2: 47 | buttons = [[ 48 | InlineKeyboardButton('➕ Add Me To Your Groups ➕', 49 | url=f'http://t.me/{temp.U_NAME}?startgroup=true') 50 | ], [ 51 | InlineKeyboardButton( 52 | '🔍 Group 🔍', url='https://t.me/vJ_botz'), 53 | InlineKeyboardButton( 54 | '🤖 Updates', url='https://t.me/VJ_Bots') 55 | ], [ 56 | InlineKeyboardButton('📚 Hᴇʟᴘ', callback_data='help'), 57 | InlineKeyboardButton('Aʙᴏᴜᴛ 🌐', callback_data='about') 58 | ], [ 59 | InlineKeyboardButton('🔗 Subscribe YouTube Channel 🔗', 60 | url=f'https://youtube.com/@Tech_VJ') 61 | ]] 62 | reply_markup = InlineKeyboardMarkup(buttons) 63 | await message.reply_photo( 64 | photo=random.choice(PICS), 65 | caption=script.START_TXT.format(message.from_user.mention, temp.U_NAME, temp.B_NAME), 66 | reply_markup=reply_markup, 67 | parse_mode=enums.ParseMode.HTML 68 | ) 69 | return 70 | if AUTH_CHANNEL and not await is_subscribed(client, message): 71 | try: 72 | invite_link = await client.create_chat_invite_link(int(AUTH_CHANNEL)) 73 | except ChatAdminRequired: 74 | logger.error("Make sure Bot is admin in Forcesub channel") 75 | return 76 | btn = [ 77 | [ 78 | InlineKeyboardButton( 79 | "❆ Jᴏɪɴ Oᴜʀ Bᴀᴄᴋ-Uᴘ Cʜᴀɴɴᴇʟ ❆", url=invite_link.invite_link 80 | ) 81 | ] 82 | ] 83 | 84 | if message.command[1] != "subscribe": 85 | try: 86 | kk, file_id = message.command[1].split("_", 1) 87 | pre = 'checksubp' if kk == 'filep' else 'checksub' 88 | btn.append([InlineKeyboardButton("↻ Tʀʏ Aɢᴀɪɴ", callback_data=f"{pre}#{file_id}")]) 89 | except (IndexError, ValueError): 90 | btn.append([InlineKeyboardButton("↻ Tʀʏ Aɢᴀɪɴ", url=f"https://t.me/{temp.U_NAME}?start={message.command[1]}")]) 91 | await client.send_message( 92 | chat_id=message.from_user.id, 93 | text="**You are not in our Back-up channel given below so you don't get the movie file...\n\nIf you want the movie file, click on the '🍿ᴊᴏɪɴ ᴏᴜʀ ʙᴀᴄᴋ-ᴜᴘ ᴄʜᴀɴɴᴇʟ🍿' button below and join our back-up channel, then click on the '🔄 Try Again' button below...\n\nThen you will get the movie files...**", 94 | reply_markup=InlineKeyboardMarkup(btn), 95 | parse_mode=enums.ParseMode.MARKDOWN 96 | ) 97 | return 98 | if len(message.command) == 2 and message.command[1] in ["subscribe", "error", "okay", "help"]: 99 | buttons = [[ 100 | InlineKeyboardButton('➕ Add Me To Your Groups ➕', 101 | url=f'http://t.me/{temp.U_NAME}?startgroup=true') 102 | ], [ 103 | InlineKeyboardButton( 104 | '🏆 Group 🏆', url='https://t.me/neha_movie_request'), 105 | InlineKeyboardButton( 106 | '📣 Updates 📣', url='https://t.me/vj_bots') 107 | ], [ 108 | InlineKeyboardButton('📚 Hᴇʟᴘ', callback_data='help'), 109 | InlineKeyboardButton('Aʙᴏᴜᴛ 🌐', callback_data='about') 110 | ], [ 111 | InlineKeyboardButton('🔗 Subscribe YouTube Channel 🔗', 112 | url=f'https://youtube.com/@Tech_VJ') 113 | ]] 114 | reply_markup = InlineKeyboardMarkup(buttons) 115 | await message.reply_photo( 116 | photo=random.choice(PICS), 117 | caption=script.START_TXT.format(message.from_user.mention, temp.U_NAME, temp.B_NAME), 118 | reply_markup=reply_markup, 119 | parse_mode=enums.ParseMode.HTML 120 | ) 121 | return 122 | data = message.command[1] 123 | try: 124 | pre, file_id = data.split('_', 1) 125 | except: 126 | file_id = data 127 | pre = "" 128 | if data.split("-", 1)[0] == "BATCH": 129 | sts = await message.reply("Please wait...") 130 | file_id = data.split("-", 1)[1] 131 | msgs = BATCH_FILES.get(file_id) 132 | if not msgs: 133 | file = await client.download_media(file_id) 134 | try: 135 | with open(file) as file_data: 136 | msgs=json.loads(file_data.read()) 137 | except: 138 | await sts.edit("FAILED") 139 | return await client.send_message(LOG_CHANNEL, "UNABLE TO OPEN FILE.") 140 | os.remove(file) 141 | BATCH_FILES[file_id] = msgs 142 | for msg in msgs: 143 | title = msg.get("title") 144 | size=get_size(int(msg.get("size", 0))) 145 | f_caption=msg.get("caption", "") 146 | if BATCH_FILE_CAPTION: 147 | try: 148 | f_caption=BATCH_FILE_CAPTION.format(file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='' if f_caption is None else f_caption) 149 | except Exception as e: 150 | logger.exception(e) 151 | f_caption=f_caption 152 | if f_caption is None: 153 | f_caption = f"{title}" 154 | try: 155 | await client.send_cached_media( 156 | chat_id=message.from_user.id, 157 | file_id=msg.get("file_id"), 158 | caption=f_caption, 159 | protect_content=msg.get('protect', False), 160 | reply_markup=InlineKeyboardMarkup( 161 | [ 162 | [InlineKeyboardButton('⚡ Sᴜᴘᴘᴏʀᴛ Gʀᴏᴜᴘ ⚡', url='https://t.me/vj_bot_disscussion'), 163 | InlineKeyboardButton('🔗 Uᴘᴅᴀᴛᴇs Cʜᴀɴɴᴇʟ 🔗', url='https://t.me/vj_bots') 164 | ],[ 165 | InlineKeyboardButton("📣 Bᴏᴛ Oᴡɴᴇʀ 📣", url="t.me/VJBots_bot") 166 | ] 167 | ] 168 | ) 169 | ) 170 | except FloodWait as e: 171 | await asyncio.sleep(e.x) 172 | logger.warning(f"Floodwait of {e.x} sec.") 173 | await client.send_cached_media( 174 | chat_id=message.from_user.id, 175 | file_id=msg.get("file_id"), 176 | caption=f_caption, 177 | protect_content=msg.get('protect', False), 178 | reply_markup=InlineKeyboardMarkup( 179 | [ 180 | [InlineKeyboardButton('⚡ Sᴜᴘᴘᴏʀᴛ Gʀᴏᴜᴘ ⚡', url='https://t.me/vj_bot_disscussion'), 181 | InlineKeyboardButton('🔗 Uᴘᴅᴀᴛᴇs Cʜᴀɴɴᴇʟ 🔗', url='https://t.me/vj_bots') 182 | ],[ 183 | InlineKeyboardButton("📣 Bᴏᴛ Oᴡɴᴇʀ 📣", url="t.me/VJBots_bot") 184 | ] 185 | ] 186 | ) 187 | ) 188 | except Exception as e: 189 | logger.warning(e, exc_info=True) 190 | continue 191 | await asyncio.sleep(1) 192 | await sts.delete() 193 | return 194 | elif data.split("-", 1)[0] == "DSTORE": 195 | sts = await message.reply("Please wait...") 196 | b_string = data.split("-", 1)[1] 197 | decoded = (base64.urlsafe_b64decode(b_string + "=" * (-len(b_string) % 4))).decode("ascii") 198 | try: 199 | f_msg_id, l_msg_id, f_chat_id, protect = decoded.split("_", 3) 200 | except: 201 | f_msg_id, l_msg_id, f_chat_id = decoded.split("_", 2) 202 | protect = "/pbatch" if PROTECT_CONTENT else "batch" 203 | diff = int(l_msg_id) - int(f_msg_id) 204 | async for msg in client.iter_messages(int(f_chat_id), int(l_msg_id), int(f_msg_id)): 205 | if msg.media: 206 | media = getattr(msg, msg.media.value) 207 | if BATCH_FILE_CAPTION: 208 | try: 209 | f_caption=BATCH_FILE_CAPTION.format(file_name=getattr(media, 'file_name', ''), file_size=getattr(media, 'file_size', ''), file_caption=getattr(msg, 'caption', '')) 210 | except Exception as e: 211 | logger.exception(e) 212 | f_caption = getattr(msg, 'caption', '') 213 | else: 214 | media = getattr(msg, msg.media.value) 215 | file_name = getattr(media, 'file_name', '') 216 | f_caption = getattr(msg, 'caption', file_name) 217 | try: 218 | await msg.copy(message.chat.id, caption=f_caption, protect_content=True if protect == "/pbatch" else False) 219 | except FloodWait as e: 220 | await asyncio.sleep(e.x) 221 | await msg.copy(message.chat.id, caption=f_caption, protect_content=True if protect == "/pbatch" else False) 222 | except Exception as e: 223 | logger.exception(e) 224 | continue 225 | elif msg.empty: 226 | continue 227 | else: 228 | try: 229 | await msg.copy(message.chat.id, protect_content=True if protect == "/pbatch" else False) 230 | except FloodWait as e: 231 | await asyncio.sleep(e.x) 232 | await msg.copy(message.chat.id, protect_content=True if protect == "/pbatch" else False) 233 | except Exception as e: 234 | logger.exception(e) 235 | continue 236 | await asyncio.sleep(1) 237 | return await sts.delete() 238 | 239 | 240 | files_ = await get_file_details(file_id) 241 | if not files_: 242 | pre, file_id = ((base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))).decode("ascii")).split("_", 1) 243 | try: 244 | msg = await client.send_cached_media( 245 | chat_id=message.from_user.id, 246 | file_id=file_id, 247 | protect_content=True if pre == 'filep' else False, 248 | reply_markup=InlineKeyboardMarkup( 249 | [ 250 | [ 251 | InlineKeyboardButton('⚡ Sᴜᴘᴘᴏʀᴛ Gʀᴏᴜᴘ ⚡', url='https://t.me/vj_bot_disscussion'), 252 | InlineKeyboardButton('🔗 Uᴘᴅᴀᴛᴇs Cʜᴀɴɴᴇʟ 🔗', url='https://t.me/vj_bots') 253 | ],[ 254 | InlineKeyboardButton("📣 Bᴏᴛ Oᴡɴᴇʀ 📣", url="t.me/VJBots_bot") 255 | ] 256 | ] 257 | ) 258 | ) 259 | filetype = msg.media 260 | file = getattr(msg, filetype.value) 261 | title = file.file_name 262 | size=get_size(file.file_size) 263 | f_caption = f"{title}" 264 | if CUSTOM_FILE_CAPTION: 265 | try: 266 | f_caption=CUSTOM_FILE_CAPTION.format(file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='') 267 | except: 268 | return 269 | await msg.edit_caption(f_caption) 270 | return 271 | except: 272 | pass 273 | return await message.reply('No such file exist.') 274 | files = files_[0] 275 | title = files.file_name 276 | size=get_size(files.file_size) 277 | f_caption=files.caption 278 | if CUSTOM_FILE_CAPTION: 279 | try: 280 | f_caption=CUSTOM_FILE_CAPTION.format(file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='' if f_caption is None else f_caption) 281 | except Exception as e: 282 | logger.exception(e) 283 | f_caption=f_caption 284 | if f_caption is None: 285 | f_caption = f"{files.file_name}" 286 | await client.send_cached_media( 287 | chat_id=message.from_user.id, 288 | file_id=file_id, 289 | caption=f_caption, 290 | protect_content=True if pre == 'filep' else False, 291 | reply_markup=InlineKeyboardMarkup( 292 | [ 293 | [ 294 | InlineKeyboardButton('⚡ Sᴜᴘᴘᴏʀᴛ Gʀᴏᴜᴘ ⚡', url='https://t.me/vj_bot_disscussion'), 295 | InlineKeyboardButton('🔗 Uᴘᴅᴀᴛᴇs Cʜᴀɴɴᴇʟ 🔗', url='https://t.me/vj_bots') 296 | ],[ 297 | InlineKeyboardButton("📣 Bᴏᴛ Oᴡɴᴇʀ 📣", url="t.me/VJBots_bot") 298 | ] 299 | ] 300 | ) 301 | ) 302 | 303 | 304 | @Client.on_message(filters.command('channel') & filters.user(ADMINS)) 305 | async def channel_info(bot, message): 306 | 307 | """Send basic information of channel""" 308 | if isinstance(CHANNELS, (int, str)): 309 | channels = [CHANNELS] 310 | elif isinstance(CHANNELS, list): 311 | channels = CHANNELS 312 | else: 313 | raise ValueError("Unexpected type of CHANNELS") 314 | 315 | text = '📑 **Indexed channels/groups**\n' 316 | for channel in channels: 317 | chat = await bot.get_chat(channel) 318 | if chat.username: 319 | text += '\n@' + chat.username 320 | else: 321 | text += '\n' + chat.title or chat.first_name 322 | 323 | text += f'\n\n**Total:** {len(CHANNELS)}' 324 | 325 | if len(text) < 4096: 326 | await message.reply(text) 327 | else: 328 | file = 'Indexed channels.txt' 329 | with open(file, 'w') as f: 330 | f.write(text) 331 | await message.reply_document(file) 332 | os.remove(file) 333 | 334 | 335 | @Client.on_message(filters.command('logs') & filters.user(ADMINS)) 336 | async def log_file(bot, message): 337 | """Send log file""" 338 | try: 339 | await message.reply_document('TelegramBot.log') 340 | except Exception as e: 341 | await message.reply(str(e)) 342 | 343 | @Client.on_message(filters.command('delete') & filters.user(ADMINS)) 344 | async def delete(bot, message): 345 | """Delete file from database""" 346 | reply = message.reply_to_message 347 | if reply and reply.media: 348 | msg = await message.reply("Processing...⏳", quote=True) 349 | else: 350 | await message.reply('Reply to file with /delete which you want to delete', quote=True) 351 | return 352 | 353 | for file_type in ("document", "video", "audio"): 354 | media = getattr(reply, file_type, None) 355 | if media is not None: 356 | break 357 | else: 358 | await msg.edit('This is not supported file format') 359 | return 360 | 361 | file_id, file_ref = unpack_new_file_id(media.file_id) 362 | 363 | result = await Media.collection.delete_one({ 364 | '_id': file_id, 365 | }) 366 | if result.deleted_count: 367 | await msg.edit('File is successfully deleted from database') 368 | else: 369 | file_name = re.sub(r"(_|\-|\.|\+)", " ", str(media.file_name)) 370 | result = await Media.collection.delete_many({ 371 | 'file_name': file_name, 372 | 'file_size': media.file_size, 373 | 'mime_type': media.mime_type 374 | }) 375 | if result.deleted_count: 376 | await msg.edit('File is successfully deleted from database') 377 | else: 378 | # files indexed before https://github.com/EvamariaTG/EvaMaria/commit/f3d2a1bcb155faf44178e5d7a685a1b533e714bf#diff-86b613edf1748372103e94cacff3b578b36b698ef9c16817bb98fe9ef22fb669R39 379 | # have original file name. 380 | result = await Media.collection.delete_many({ 381 | 'file_name': media.file_name, 382 | 'file_size': media.file_size, 383 | 'mime_type': media.mime_type 384 | }) 385 | if result.deleted_count: 386 | await msg.edit('File is successfully deleted from database') 387 | else: 388 | await msg.edit('File not found in database') 389 | 390 | 391 | @Client.on_message(filters.command('deleteall') & filters.user(ADMINS)) 392 | async def delete_all_index(bot, message): 393 | await message.reply_text( 394 | 'This will delete all indexed files.\nDo you want to continue??', 395 | reply_markup=InlineKeyboardMarkup( 396 | [ 397 | [ 398 | InlineKeyboardButton( 399 | text="YES", callback_data="autofilter_delete" 400 | ) 401 | ], 402 | [ 403 | InlineKeyboardButton( 404 | text="CANCEL", callback_data="close_data" 405 | ) 406 | ], 407 | ] 408 | ), 409 | quote=True, 410 | ) 411 | 412 | 413 | @Client.on_callback_query(filters.regex(r'^autofilter_delete')) 414 | async def delete_all_index_confirm(bot, message): 415 | await Media.collection.drop() 416 | await message.answer('Piracy Is Crime') 417 | await message.message.edit('Succesfully Deleted All The Indexed Files.') 418 | 419 | 420 | @Client.on_message(filters.command('settings')) 421 | async def settings(client, message): 422 | userid = message.from_user.id if message.from_user else None 423 | if not userid: 424 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM") 425 | chat_type = message.chat.type 426 | 427 | if chat_type == enums.ChatType.PRIVATE: 428 | grpid = await active_connection(str(userid)) 429 | if grpid is not None: 430 | grp_id = grpid 431 | try: 432 | chat = await client.get_chat(grpid) 433 | title = chat.title 434 | except: 435 | await message.reply_text("Make sure I'm present in your group!!", quote=True) 436 | return 437 | else: 438 | await message.reply_text("I'm not connected to any groups!", quote=True) 439 | return 440 | 441 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: 442 | grp_id = message.chat.id 443 | title = message.chat.title 444 | 445 | else: 446 | return 447 | 448 | st = await client.get_chat_member(grp_id, userid) 449 | if ( 450 | st.status != enums.ChatMemberStatus.ADMINISTRATOR 451 | and st.status != enums.ChatMemberStatus.OWNER 452 | and str(userid) not in ADMINS 453 | ): 454 | return 455 | 456 | settings = await get_settings(grp_id) 457 | 458 | try: 459 | if settings['max_btn']: 460 | settings = await get_settings(grp_id) 461 | except KeyError: 462 | await save_group_settings(grp_id, 'max_btn', False) 463 | settings = await get_settings(grp_id) 464 | if 'is_shortlink' not in settings.keys(): 465 | await save_group_settings(grp_id, 'is_shortlink', False) 466 | else: 467 | pass 468 | 469 | if settings is not None: 470 | buttons = [ 471 | [ 472 | InlineKeyboardButton( 473 | 'Fɪʟᴛᴇʀ Bᴜᴛᴛᴏɴ', 474 | callback_data=f'setgs#button#{settings["button"]}#{grp_id}', 475 | ), 476 | InlineKeyboardButton( 477 | 'Sɪɴɢʟᴇ' if settings["button"] else 'Dᴏᴜʙʟᴇ', 478 | callback_data=f'setgs#button#{settings["button"]}#{grp_id}', 479 | ), 480 | ], 481 | [ 482 | InlineKeyboardButton( 483 | 'Fɪʟᴇ Sᴇɴᴅ Mᴏᴅᴇ', 484 | callback_data=f'setgs#botpm#{settings["botpm"]}#{grp_id}', 485 | ), 486 | InlineKeyboardButton( 487 | 'Mᴀɴᴜᴀʟ Sᴛᴀʀᴛ' if settings["botpm"] else 'Aᴜᴛᴏ Sᴇɴᴅ', 488 | callback_data=f'setgs#botpm#{settings["botpm"]}#{grp_id}', 489 | ), 490 | ], 491 | [ 492 | InlineKeyboardButton( 493 | 'Pʀᴏᴛᴇᴄᴛ Cᴏɴᴛᴇɴᴛ', 494 | callback_data=f'setgs#file_secure#{settings["file_secure"]}#{grp_id}', 495 | ), 496 | InlineKeyboardButton( 497 | '✔ Oɴ' if settings["file_secure"] else '✘ Oғғ', 498 | callback_data=f'setgs#file_secure#{settings["file_secure"]}#{grp_id}', 499 | ), 500 | ], 501 | [ 502 | InlineKeyboardButton( 503 | 'Iᴍᴅʙ', 504 | callback_data=f'setgs#imdb#{settings["imdb"]}#{grp_id}', 505 | ), 506 | InlineKeyboardButton( 507 | '✔ Oɴ' if settings["imdb"] else '✘ Oғғ', 508 | callback_data=f'setgs#imdb#{settings["imdb"]}#{grp_id}', 509 | ), 510 | ], 511 | [ 512 | InlineKeyboardButton( 513 | 'Sᴘᴇʟʟ Cʜᴇᴄᴋ', 514 | callback_data=f'setgs#spell_check#{settings["spell_check"]}#{grp_id}', 515 | ), 516 | InlineKeyboardButton( 517 | '✔ Oɴ' if settings["spell_check"] else '✘ Oғғ', 518 | callback_data=f'setgs#spell_check#{settings["spell_check"]}#{grp_id}', 519 | ), 520 | ], 521 | [ 522 | InlineKeyboardButton( 523 | 'Wᴇʟᴄᴏᴍᴇ Msɢ', 524 | callback_data=f'setgs#welcome#{settings["welcome"]}#{grp_id}', 525 | ), 526 | InlineKeyboardButton( 527 | '✔ Oɴ' if settings["welcome"] else '✘ Oғғ', 528 | callback_data=f'setgs#welcome#{settings["welcome"]}#{grp_id}', 529 | ), 530 | ], 531 | [ 532 | InlineKeyboardButton( 533 | 'Aᴜᴛᴏ-Dᴇʟᴇᴛᴇ', 534 | callback_data=f'setgs#auto_delete#{settings["auto_delete"]}#{grp_id}', 535 | ), 536 | InlineKeyboardButton( 537 | '10 Mɪɴs' if settings["auto_delete"] else '✘ Oғғ', 538 | callback_data=f'setgs#auto_delete#{settings["auto_delete"]}#{grp_id}', 539 | ), 540 | ], 541 | [ 542 | InlineKeyboardButton( 543 | 'Aᴜᴛᴏ-Fɪʟᴛᴇʀ', 544 | callback_data=f'setgs#auto_ffilter#{settings["auto_ffilter"]}#{grp_id}', 545 | ), 546 | InlineKeyboardButton( 547 | '✔ Oɴ' if settings["auto_ffilter"] else '✘ Oғғ', 548 | callback_data=f'setgs#auto_ffilter#{settings["auto_ffilter"]}#{grp_id}', 549 | ), 550 | ], 551 | [ 552 | InlineKeyboardButton( 553 | 'Mᴀx Bᴜᴛᴛᴏɴs', 554 | callback_data=f'setgs#max_btn#{settings["max_btn"]}#{grp_id}', 555 | ), 556 | InlineKeyboardButton( 557 | '10' if settings["max_btn"] else f'{MAX_B_TN}', 558 | callback_data=f'setgs#max_btn#{settings["max_btn"]}#{grp_id}', 559 | ), 560 | ], 561 | [ 562 | InlineKeyboardButton( 563 | 'ShortLink', 564 | callback_data=f'setgs#is_shortlink#{settings["is_shortlink"]}#{grp_id}', 565 | ), 566 | InlineKeyboardButton( 567 | '✔ Oɴ' if settings["is_shortlink"] else '✘ Oғғ', 568 | callback_data=f'setgs#is_shortlink#{settings["is_shortlink"]}#{grp_id}', 569 | ), 570 | ], 571 | ] 572 | 573 | btn = [[ 574 | InlineKeyboardButton("Oᴘᴇɴ Hᴇʀᴇ ↓", callback_data=f"opnsetgrp#{grp_id}"), 575 | InlineKeyboardButton("Oᴘᴇɴ Iɴ PM ⇲", callback_data=f"opnsetpm#{grp_id}") 576 | ]] 577 | 578 | reply_markup = InlineKeyboardMarkup(buttons) 579 | if chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: 580 | await message.reply_text( 581 | text="Dᴏ ʏᴏᴜ ᴡᴀɴᴛ ᴛᴏ ᴏᴘᴇɴ sᴇᴛᴛɪɴɢs ʜᴇʀᴇ ?", 582 | reply_markup=InlineKeyboardMarkup(btn), 583 | disable_web_page_preview=True, 584 | parse_mode=enums.ParseMode.HTML, 585 | reply_to_message_id=message.id 586 | ) 587 | else: 588 | await message.reply_text( 589 | text=f"Cʜᴀɴɢᴇ Yᴏᴜʀ Sᴇᴛᴛɪɴɢs Fᴏʀ {title} As Yᴏᴜʀ Wɪsʜ ⚙", 590 | reply_markup=reply_markup, 591 | disable_web_page_preview=True, 592 | parse_mode=enums.ParseMode.HTML, 593 | reply_to_message_id=message.id 594 | ) 595 | 596 | 597 | 598 | @Client.on_message(filters.command('set_template')) 599 | async def save_template(client, message): 600 | sts = await message.reply("Checking template") 601 | userid = message.from_user.id if message.from_user else None 602 | if not userid: 603 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM") 604 | chat_type = message.chat.type 605 | 606 | if chat_type == enums.ChatType.PRIVATE: 607 | grpid = await active_connection(str(userid)) 608 | if grpid is not None: 609 | grp_id = grpid 610 | try: 611 | chat = await client.get_chat(grpid) 612 | title = chat.title 613 | except: 614 | await message.reply_text("Make sure I'm present in your group!!", quote=True) 615 | return 616 | else: 617 | await message.reply_text("I'm not connected to any groups!", quote=True) 618 | return 619 | 620 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: 621 | grp_id = message.chat.id 622 | title = message.chat.title 623 | 624 | else: 625 | return 626 | 627 | st = await client.get_chat_member(grp_id, userid) 628 | if ( 629 | st.status != enums.ChatMemberStatus.ADMINISTRATOR 630 | and st.status != enums.ChatMemberStatus.OWNER 631 | and str(userid) not in ADMINS 632 | ): 633 | return 634 | 635 | if len(message.command) < 2: 636 | return await sts.edit("No Input!!") 637 | template = message.text.split(" ", 1)[1] 638 | await save_group_settings(grp_id, 'template', template) 639 | await sts.edit(f"Successfully changed template for {title} to\n\n{template}") 640 | 641 | 642 | @Client.on_message((filters.command(["request", "Request"]) | filters.regex("#request") | filters.regex("#Request")) & filters.group) 643 | async def requests(bot, message): 644 | if REQST_CHANNEL is None or SUPPORT_CHAT_ID is None: return # Must add REQST_CHANNEL and SUPPORT_CHAT_ID to use this feature 645 | if message.reply_to_message and SUPPORT_CHAT_ID == message.chat.id: 646 | chat_id = message.chat.id 647 | reporter = str(message.from_user.id) 648 | mention = message.from_user.mention 649 | success = True 650 | content = message.reply_to_message.text 651 | try: 652 | if REQST_CHANNEL is not None: 653 | btn = [[ 654 | InlineKeyboardButton('View Request', url=f"{message.reply_to_message.link}"), 655 | InlineKeyboardButton('Show Options', callback_data=f'show_option#{reporter}') 656 | ]] 657 | reported_post = await bot.send_message(chat_id=REQST_CHANNEL, text=f"𝖱𝖾𝗉𝗈𝗋𝗍𝖾𝗋 : {mention} ({reporter})\n\n𝖬𝖾𝗌𝗌𝖺𝗀𝖾 : {content}", reply_markup=InlineKeyboardMarkup(btn)) 658 | success = True 659 | elif len(content) >= 3: 660 | for admin in ADMINS: 661 | btn = [[ 662 | InlineKeyboardButton('View Request', url=f"{message.reply_to_message.link}"), 663 | InlineKeyboardButton('Show Options', callback_data=f'show_option#{reporter}') 664 | ]] 665 | reported_post = await bot.send_message(chat_id=admin, text=f"𝖱𝖾𝗉𝗈𝗋𝗍𝖾𝗋 : {mention} ({reporter})\n\n𝖬𝖾𝗌𝗌𝖺𝗀𝖾 : {content}", reply_markup=InlineKeyboardMarkup(btn)) 666 | success = True 667 | else: 668 | if len(content) < 3: 669 | await message.reply_text("You must type about your request [Minimum 3 Characters]. Requests can't be empty.") 670 | if len(content) < 3: 671 | success = False 672 | except Exception as e: 673 | await message.reply_text(f"Error: {e}") 674 | pass 675 | 676 | elif SUPPORT_CHAT_ID == message.chat.id: 677 | chat_id = message.chat.id 678 | reporter = str(message.from_user.id) 679 | mention = message.from_user.mention 680 | success = True 681 | content = message.text 682 | keywords = ["#request", "/request", "#Request", "/Request"] 683 | for keyword in keywords: 684 | if keyword in content: 685 | content = content.replace(keyword, "") 686 | try: 687 | if REQST_CHANNEL is not None and len(content) >= 3: 688 | btn = [[ 689 | InlineKeyboardButton('View Request', url=f"{message.link}"), 690 | InlineKeyboardButton('Show Options', callback_data=f'show_option#{reporter}') 691 | ]] 692 | reported_post = await bot.send_message(chat_id=REQST_CHANNEL, text=f"𝖱𝖾𝗉𝗈𝗋𝗍𝖾𝗋 : {mention} ({reporter})\n\n𝖬𝖾𝗌𝗌𝖺𝗀𝖾 : {content}", reply_markup=InlineKeyboardMarkup(btn)) 693 | success = True 694 | elif len(content) >= 3: 695 | for admin in ADMINS: 696 | btn = [[ 697 | InlineKeyboardButton('View Request', url=f"{message.link}"), 698 | InlineKeyboardButton('Show Options', callback_data=f'show_option#{reporter}') 699 | ]] 700 | reported_post = await bot.send_message(chat_id=admin, text=f"𝖱𝖾𝗉𝗈𝗋𝗍𝖾𝗋 : {mention} ({reporter})\n\n𝖬𝖾𝗌𝗌𝖺𝗀𝖾 : {content}", reply_markup=InlineKeyboardMarkup(btn)) 701 | success = True 702 | else: 703 | if len(content) < 3: 704 | await message.reply_text("You must type about your request [Minimum 3 Characters]. Requests can't be empty.") 705 | if len(content) < 3: 706 | success = False 707 | except Exception as e: 708 | await message.reply_text(f"Error: {e}") 709 | pass 710 | 711 | else: 712 | success = False 713 | 714 | if success: 715 | btn = [[ 716 | InlineKeyboardButton('View Request', url=f"{reported_post.link}") 717 | ]] 718 | await message.reply_text("Your request has been added! Please wait for some time.", reply_markup=InlineKeyboardMarkup(btn)) 719 | 720 | 721 | @Client.on_message(filters.command("send") & filters.user(ADMINS)) 722 | async def send_msg(bot, message): 723 | if message.reply_to_message: 724 | target_id = message.text.split(" ", 1)[1] 725 | out = "Users Saved In DB Are:\n\n" 726 | success = False 727 | try: 728 | user = await bot.get_users(target_id) 729 | users = await db.get_all_users() 730 | async for usr in users: 731 | out += f"{usr['id']}" 732 | out += '\n' 733 | if str(user.id) in str(out): 734 | await message.reply_to_message.copy(int(user.id)) 735 | success = True 736 | else: 737 | success = False 738 | if success: 739 | await message.reply_text(f"Your message has been successfully send to {user.mention}.") 740 | else: 741 | await message.reply_text("This user didn't started this bot yet !") 742 | except Exception as e: 743 | await message.reply_text(f"Error: {e}") 744 | else: 745 | await message.reply_text("Use this command as a reply to any message using the target chat id. For eg: /send userid") 746 | 747 | @Client.on_message(filters.command("deletefiles") & filters.user(ADMINS)) 748 | async def deletemultiplefiles(bot, message): 749 | chat_type = message.chat.type 750 | if chat_type != enums.ChatType.PRIVATE: 751 | return await message.reply_text(f"Hey {message.from_user.mention}, This command won't work in groups. It only works on my PM !") 752 | else: 753 | pass 754 | try: 755 | keyword = message.text.split(" ", 1)[1] 756 | except: 757 | return await message.reply_text(f"Hey {message.from_user.mention}, Give me a keyword along with the command to delete files.") 758 | k = await bot.send_message(chat_id=message.chat.id, text=f"Fetching Files for your query {keyword} on DB... Please wait...") 759 | files, next_offset, total = await get_bad_files(keyword) 760 | await k.edit_text(f"Found {total} files for your query {keyword} !") 761 | deleted = 0 762 | for file in files: 763 | file_ids = file.file_id 764 | file_name = file.file_name 765 | result = await Media.collection.delete_one({ 766 | '_id': file_ids, 767 | }) 768 | if result.deleted_count: 769 | logger.info(f'File Found for your query {keyword}! Successfully deleted {file_name} from database.') 770 | deleted += 1 771 | deleted = str(deleted) 772 | await k.edit_text(text=f"Successfully deleted {deleted} files from database for your query {keyword}.") 773 | 774 | @Client.on_message(filters.command("shortlink")) 775 | async def shortlink(bot, message): 776 | chat_type = message.chat.type 777 | if chat_type == enums.ChatType.PRIVATE: 778 | return await message.reply_text(f"Hey {message.from_user.mention}, This command only works on groups !") 779 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: 780 | grpid = message.chat.id 781 | title = message.chat.title 782 | else: 783 | return 784 | data = message.text 785 | userid = message.from_user.id 786 | user = await bot.get_chat_member(grpid, userid) 787 | if user.status != enums.ChatMemberStatus.ADMINISTRATOR and user.status != enums.ChatMemberStatus.OWNER and str(userid) not in ADMINS: 788 | return await message.reply_text("You don't have access to use this command !") 789 | else: 790 | pass 791 | try: 792 | command, shortlink_url, api = data.split(" ") 793 | except: 794 | return await message.reply_text("Command Incomplete :(\n\nGive me a shortlink and api along with the command !\n\nFormat: /shortlink omegalinks.in 9c53d31922826c891f8d5d730ef5c495c2bcf36e") 795 | reply = await message.reply_text("Please Wait...") 796 | await save_group_settings(grpid, 'shortlink', shortlink_url) 797 | await save_group_settings(grpid, 'shortlink_api', api) 798 | await save_group_settings(grpid, 'is_shortlink', True) 799 | await reply.edit_text(f"⚡ Successfully Added Shortlink API For {title}.\n\n🔗 Current Shortlink Website: {shortlink_url}\n📣 Current API: {api}") 800 | -------------------------------------------------------------------------------- /plugins/connection.py: -------------------------------------------------------------------------------- 1 | from pyrogram import filters, Client, enums 2 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup 3 | from database.connections_mdb import add_connection, all_connections, if_active, delete_connection 4 | from info import ADMINS 5 | import logging 6 | 7 | logger = logging.getLogger(__name__) 8 | logger.setLevel(logging.ERROR) 9 | 10 | 11 | @Client.on_message((filters.private | filters.group) & filters.command('connect')) 12 | async def addconnection(client, message): 13 | userid = message.from_user.id if message.from_user else None 14 | if not userid: 15 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM") 16 | chat_type = message.chat.type 17 | 18 | if chat_type == enums.ChatType.PRIVATE: 19 | try: 20 | cmd, group_id = message.text.split(" ", 1) 21 | except: 22 | await message.reply_text( 23 | "Enter in correct format!\n\n" 24 | "/connect groupid\n\n" 25 | "Get your Group id by adding this bot to your group and use /id", 26 | quote=True 27 | ) 28 | return 29 | 30 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: 31 | group_id = message.chat.id 32 | 33 | try: 34 | st = await client.get_chat_member(group_id, userid) 35 | if ( 36 | st.status != enums.ChatMemberStatus.ADMINISTRATOR 37 | and st.status != enums.ChatMemberStatus.OWNER 38 | and userid not in ADMINS 39 | ): 40 | await message.reply_text("You should be an admin in Given group!", quote=True) 41 | return 42 | except Exception as e: 43 | logger.exception(e) 44 | await message.reply_text( 45 | "Invalid Group ID!\n\nIf correct, Make sure I'm present in your group!!", 46 | quote=True, 47 | ) 48 | 49 | return 50 | try: 51 | st = await client.get_chat_member(group_id, "me") 52 | if st.status == enums.ChatMemberStatus.ADMINISTRATOR: 53 | ttl = await client.get_chat(group_id) 54 | title = ttl.title 55 | 56 | addcon = await add_connection(str(group_id), str(userid)) 57 | if addcon: 58 | await message.reply_text( 59 | f"Successfully connected to **{title}**\nNow manage your group from my pm !", 60 | quote=True, 61 | parse_mode=enums.ParseMode.MARKDOWN 62 | ) 63 | if chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: 64 | await client.send_message( 65 | userid, 66 | f"Connected to **{title}** !", 67 | parse_mode=enums.ParseMode.MARKDOWN 68 | ) 69 | else: 70 | await message.reply_text( 71 | "You're already connected to this chat!", 72 | quote=True 73 | ) 74 | else: 75 | await message.reply_text("Add me as an admin in group", quote=True) 76 | except Exception as e: 77 | logger.exception(e) 78 | await message.reply_text('Some error occurred! Try again later.', quote=True) 79 | return 80 | 81 | 82 | @Client.on_message((filters.private | filters.group) & filters.command('disconnect')) 83 | async def deleteconnection(client, message): 84 | userid = message.from_user.id if message.from_user else None 85 | if not userid: 86 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM") 87 | chat_type = message.chat.type 88 | 89 | if chat_type == enums.ChatType.PRIVATE: 90 | await message.reply_text("Run /connections to view or disconnect from groups!", quote=True) 91 | 92 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: 93 | group_id = message.chat.id 94 | 95 | st = await client.get_chat_member(group_id, userid) 96 | if ( 97 | st.status != enums.ChatMemberStatus.ADMINISTRATOR 98 | and st.status != enums.ChatMemberStatus.OWNER 99 | and str(userid) not in ADMINS 100 | ): 101 | return 102 | 103 | delcon = await delete_connection(str(userid), str(group_id)) 104 | if delcon: 105 | await message.reply_text("Successfully disconnected from this chat", quote=True) 106 | else: 107 | await message.reply_text("This chat isn't connected to me!\nDo /connect to connect.", quote=True) 108 | 109 | 110 | @Client.on_message(filters.private & filters.command(["connections"])) 111 | async def connections(client, message): 112 | userid = message.from_user.id 113 | 114 | groupids = await all_connections(str(userid)) 115 | if groupids is None: 116 | await message.reply_text( 117 | "There are no active connections!! Connect to some groups first.", 118 | quote=True 119 | ) 120 | return 121 | buttons = [] 122 | for groupid in groupids: 123 | try: 124 | ttl = await client.get_chat(int(groupid)) 125 | title = ttl.title 126 | active = await if_active(str(userid), str(groupid)) 127 | act = " - ACTIVE" if active else "" 128 | buttons.append( 129 | [ 130 | InlineKeyboardButton( 131 | text=f"{title}{act}", callback_data=f"groupcb:{groupid}:{act}" 132 | ) 133 | ] 134 | ) 135 | except: 136 | pass 137 | if buttons: 138 | await message.reply_text( 139 | "Your connected group details ;\n\n", 140 | reply_markup=InlineKeyboardMarkup(buttons), 141 | quote=True 142 | ) 143 | else: 144 | await message.reply_text( 145 | "There are no active connections!! Connect to some groups first.", 146 | quote=True 147 | ) 148 | -------------------------------------------------------------------------------- /plugins/files_delete.py: -------------------------------------------------------------------------------- 1 | import re 2 | import logging 3 | from pyrogram import Client, filters 4 | from info import DELETE_CHANNELS 5 | from database.ia_filterdb import Media, unpack_new_file_id 6 | 7 | logger = logging.getLogger(__name__) 8 | 9 | media_filter = filters.document | filters.video | filters.audio 10 | 11 | 12 | @Client.on_message(filters.chat(DELETE_CHANNELS) & media_filter) 13 | async def deletemultiplemedia(bot, message): 14 | """Delete Multiple files from database""" 15 | 16 | for file_type in ("document", "video", "audio"): 17 | media = getattr(message, file_type, None) 18 | if media is not None: 19 | break 20 | else: 21 | return 22 | 23 | file_id, file_ref = unpack_new_file_id(media.file_id) 24 | 25 | result = await Media.collection.delete_one({ 26 | '_id': file_id, 27 | }) 28 | if result.deleted_count: 29 | logger.info('File is successfully deleted from database.') 30 | else: 31 | file_name = re.sub(r"(_|\-|\.|\+)", " ", str(media.file_name)) 32 | result = await Media.collection.delete_many({ 33 | 'file_name': file_name, 34 | 'file_size': media.file_size, 35 | 'mime_type': media.mime_type 36 | }) 37 | if result.deleted_count: 38 | logger.info('File is successfully deleted from database.') 39 | else: 40 | result = await Media.collection.delete_many({ 41 | 'file_name': media.file_name, 42 | 'file_size': media.file_size, 43 | 'mime_type': media.mime_type 44 | }) 45 | if result.deleted_count: 46 | logger.info('File is successfully deleted from database.') 47 | else: 48 | logger.info('File not found in database.') 49 | -------------------------------------------------------------------------------- /plugins/filters.py: -------------------------------------------------------------------------------- 1 | import io 2 | from pyrogram import filters, Client, enums 3 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup 4 | from database.filters_mdb import( 5 | add_filter, 6 | get_filters, 7 | delete_filter, 8 | count_filters 9 | ) 10 | 11 | from database.connections_mdb import active_connection 12 | from utils import get_file_id, parser, split_quotes 13 | from info import ADMINS 14 | 15 | 16 | @Client.on_message(filters.command(['filter', 'add']) & filters.incoming) 17 | async def addfilter(client, message): 18 | userid = message.from_user.id if message.from_user else None 19 | if not userid: 20 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM") 21 | chat_type = message.chat.type 22 | args = message.text.html.split(None, 1) 23 | 24 | if chat_type == enums.ChatType.PRIVATE: 25 | grpid = await active_connection(str(userid)) 26 | if grpid is not None: 27 | grp_id = grpid 28 | try: 29 | chat = await client.get_chat(grpid) 30 | title = chat.title 31 | except: 32 | await message.reply_text("Make sure I'm present in your group!!", quote=True) 33 | return 34 | else: 35 | await message.reply_text("I'm not connected to any groups!", quote=True) 36 | return 37 | 38 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: 39 | grp_id = message.chat.id 40 | title = message.chat.title 41 | 42 | else: 43 | return 44 | 45 | st = await client.get_chat_member(grp_id, userid) 46 | if ( 47 | st.status != enums.ChatMemberStatus.ADMINISTRATOR 48 | and st.status != enums.ChatMemberStatus.OWNER 49 | and str(userid) not in ADMINS 50 | ): 51 | return 52 | 53 | 54 | if len(args) < 2: 55 | await message.reply_text("Command Incomplete :(", quote=True) 56 | return 57 | 58 | extracted = split_quotes(args[1]) 59 | text = extracted[0].lower() 60 | 61 | if not message.reply_to_message and len(extracted) < 2: 62 | await message.reply_text("Add some content to save your filter!", quote=True) 63 | return 64 | 65 | if (len(extracted) >= 2) and not message.reply_to_message: 66 | reply_text, btn, alert = parser(extracted[1], text) 67 | fileid = None 68 | if not reply_text: 69 | await message.reply_text("You cannot have buttons alone, give some text to go with it!", quote=True) 70 | return 71 | 72 | elif message.reply_to_message and message.reply_to_message.reply_markup: 73 | try: 74 | rm = message.reply_to_message.reply_markup 75 | btn = rm.inline_keyboard 76 | msg = get_file_id(message.reply_to_message) 77 | if msg: 78 | fileid = msg.file_id 79 | reply_text = message.reply_to_message.caption.html 80 | else: 81 | reply_text = message.reply_to_message.text.html 82 | fileid = None 83 | alert = None 84 | except: 85 | reply_text = "" 86 | btn = "[]" 87 | fileid = None 88 | alert = None 89 | 90 | elif message.reply_to_message and message.reply_to_message.media: 91 | try: 92 | msg = get_file_id(message.reply_to_message) 93 | fileid = msg.file_id if msg else None 94 | reply_text, btn, alert = parser(extracted[1], text) if message.reply_to_message.sticker else parser(message.reply_to_message.caption.html, text) 95 | except: 96 | reply_text = "" 97 | btn = "[]" 98 | alert = None 99 | elif message.reply_to_message and message.reply_to_message.text: 100 | try: 101 | fileid = None 102 | reply_text, btn, alert = parser(message.reply_to_message.text.html, text) 103 | except: 104 | reply_text = "" 105 | btn = "[]" 106 | alert = None 107 | else: 108 | return 109 | 110 | await add_filter(grp_id, text, reply_text, btn, fileid, alert) 111 | 112 | await message.reply_text( 113 | f"Filter for `{text}` added in **{title}**", 114 | quote=True, 115 | parse_mode=enums.ParseMode.MARKDOWN 116 | ) 117 | 118 | 119 | @Client.on_message(filters.command(['viewfilters', 'filters']) & filters.incoming) 120 | async def get_all(client, message): 121 | 122 | chat_type = message.chat.type 123 | userid = message.from_user.id if message.from_user else None 124 | if not userid: 125 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM") 126 | if chat_type == enums.ChatType.PRIVATE: 127 | userid = message.from_user.id 128 | grpid = await active_connection(str(userid)) 129 | if grpid is not None: 130 | grp_id = grpid 131 | try: 132 | chat = await client.get_chat(grpid) 133 | title = chat.title 134 | except: 135 | await message.reply_text("Make sure I'm present in your group!!", quote=True) 136 | return 137 | else: 138 | await message.reply_text("I'm not connected to any groups!", quote=True) 139 | return 140 | 141 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: 142 | grp_id = message.chat.id 143 | title = message.chat.title 144 | 145 | else: 146 | return 147 | 148 | st = await client.get_chat_member(grp_id, userid) 149 | if ( 150 | st.status != enums.ChatMemberStatus.ADMINISTRATOR 151 | and st.status != enums.ChatMemberStatus.OWNER 152 | and str(userid) not in ADMINS 153 | ): 154 | return 155 | 156 | texts = await get_filters(grp_id) 157 | count = await count_filters(grp_id) 158 | if count: 159 | filterlist = f"Total number of filters in **{title}** : {count}\n\n" 160 | 161 | for text in texts: 162 | keywords = " × `{}`\n".format(text) 163 | 164 | filterlist += keywords 165 | 166 | if len(filterlist) > 4096: 167 | with io.BytesIO(str.encode(filterlist.replace("`", ""))) as keyword_file: 168 | keyword_file.name = "keywords.txt" 169 | await message.reply_document( 170 | document=keyword_file, 171 | quote=True 172 | ) 173 | return 174 | else: 175 | filterlist = f"There are no active filters in **{title}**" 176 | 177 | await message.reply_text( 178 | text=filterlist, 179 | quote=True, 180 | parse_mode=enums.ParseMode.MARKDOWN 181 | ) 182 | 183 | @Client.on_message(filters.command('del') & filters.incoming) 184 | async def deletefilter(client, message): 185 | userid = message.from_user.id if message.from_user else None 186 | if not userid: 187 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM") 188 | chat_type = message.chat.type 189 | 190 | if chat_type == enums.ChatType.PRIVATE: 191 | grpid = await active_connection(str(userid)) 192 | if grpid is not None: 193 | grp_id = grpid 194 | try: 195 | chat = await client.get_chat(grpid) 196 | title = chat.title 197 | except: 198 | await message.reply_text("Make sure I'm present in your group!!", quote=True) 199 | return 200 | else: 201 | await message.reply_text("I'm not connected to any groups!", quote=True) 202 | 203 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: 204 | grp_id = message.chat.id 205 | title = message.chat.title 206 | 207 | else: 208 | return 209 | 210 | st = await client.get_chat_member(grp_id, userid) 211 | if ( 212 | st.status != enums.ChatMemberStatus.ADMINISTRATOR 213 | and st.status != enums.ChatMemberStatus.OWNER 214 | and str(userid) not in ADMINS 215 | ): 216 | return 217 | 218 | try: 219 | cmd, text = message.text.split(" ", 1) 220 | except: 221 | await message.reply_text( 222 | "Mention the filtername which you wanna delete!\n\n" 223 | "/del filtername\n\n" 224 | "Use /viewfilters to view all available filters", 225 | quote=True 226 | ) 227 | return 228 | 229 | query = text.lower() 230 | 231 | await delete_filter(message, query, grp_id) 232 | 233 | 234 | @Client.on_message(filters.command('delall') & filters.incoming) 235 | async def delallconfirm(client, message): 236 | userid = message.from_user.id if message.from_user else None 237 | if not userid: 238 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM") 239 | chat_type = message.chat.type 240 | 241 | if chat_type == enums.ChatType.PRIVATE: 242 | grpid = await active_connection(str(userid)) 243 | if grpid is not None: 244 | grp_id = grpid 245 | try: 246 | chat = await client.get_chat(grpid) 247 | title = chat.title 248 | except: 249 | await message.reply_text("Make sure I'm present in your group!!", quote=True) 250 | return 251 | else: 252 | await message.reply_text("I'm not connected to any groups!", quote=True) 253 | return 254 | 255 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: 256 | grp_id = message.chat.id 257 | title = message.chat.title 258 | 259 | else: 260 | return 261 | 262 | st = await client.get_chat_member(grp_id, userid) 263 | if (st.status == enums.ChatMemberStatus.OWNER) or (str(userid) in ADMINS): 264 | await message.reply_text( 265 | f"This will delete all filters from '{title}'.\nDo you want to continue??", 266 | reply_markup=InlineKeyboardMarkup([ 267 | [InlineKeyboardButton(text="YES",callback_data="delallconfirm")], 268 | [InlineKeyboardButton(text="CANCEL",callback_data="delallcancel")] 269 | ]), 270 | quote=True 271 | ) 272 | 273 | -------------------------------------------------------------------------------- /plugins/genlink.py: -------------------------------------------------------------------------------- 1 | import re 2 | from pyrogram import filters, Client, enums 3 | from pyrogram.errors.exceptions.bad_request_400 import ChannelInvalid, UsernameInvalid, UsernameNotModified 4 | from info import ADMINS, LOG_CHANNEL, FILE_STORE_CHANNEL, PUBLIC_FILE_STORE 5 | from database.ia_filterdb import unpack_new_file_id 6 | from utils import temp 7 | import re 8 | import os 9 | import json 10 | import base64 11 | import logging 12 | 13 | logger = logging.getLogger(__name__) 14 | logger.setLevel(logging.INFO) 15 | 16 | async def allowed(_, __, message): 17 | if PUBLIC_FILE_STORE: 18 | return True 19 | if message.from_user and message.from_user.id in ADMINS: 20 | return True 21 | return False 22 | 23 | @Client.on_message(filters.command(['link', 'plink']) & filters.create(allowed)) 24 | async def gen_link_s(bot, message): 25 | replied = message.reply_to_message 26 | if not replied: 27 | return await message.reply('Reply to a message to get a shareable link.') 28 | file_type = replied.media 29 | if file_type not in [enums.MessageMediaType.VIDEO, enums.MessageMediaType.AUDIO, enums.MessageMediaType.DOCUMENT]: 30 | return await message.reply("Reply to a supported media") 31 | if message.has_protected_content and message.chat.id not in ADMINS: 32 | return await message.reply("okDa") 33 | file_id, ref = unpack_new_file_id((getattr(replied, file_type.value)).file_id) 34 | string = 'filep_' if message.text.lower().strip() == "/plink" else 'file_' 35 | string += file_id 36 | outstr = base64.urlsafe_b64encode(string.encode("ascii")).decode().strip("=") 37 | await message.reply(f"Here is your Link:\nhttps://telegram.me/{temp.U_NAME}?start={outstr}") 38 | 39 | 40 | @Client.on_message(filters.command(['batch', 'pbatch']) & filters.create(allowed)) 41 | async def gen_link_batch(bot, message): 42 | if " " not in message.text: 43 | return await message.reply("Use correct format.\nExample /batch https://telegram.me/TeamEvamaria/10 https://telegram.me/TeamEvamaria/20.") 44 | links = message.text.strip().split(" ") 45 | if len(links) != 3: 46 | return await message.reply("Use correct format.\nExample /batch https://telegram.me/TeamEvamaria/10 https://telegram.me/TeamEvamaria/20.") 47 | cmd, first, last = links 48 | regex = re.compile("(https://)?(t\.me/|telegram\.me/|telegram\.dog/)(c/)?(\d+|[a-zA-Z_0-9]+)/(\d+)$") 49 | match = regex.match(first) 50 | if not match: 51 | return await message.reply('Invalid link') 52 | f_chat_id = match.group(4) 53 | f_msg_id = int(match.group(5)) 54 | if f_chat_id.isnumeric(): 55 | f_chat_id = int(("-100" + f_chat_id)) 56 | 57 | match = regex.match(last) 58 | if not match: 59 | return await message.reply('Invalid link') 60 | l_chat_id = match.group(4) 61 | l_msg_id = int(match.group(5)) 62 | if l_chat_id.isnumeric(): 63 | l_chat_id = int(("-100" + l_chat_id)) 64 | 65 | if f_chat_id != l_chat_id: 66 | return await message.reply("Chat ids not matched.") 67 | try: 68 | chat_id = (await bot.get_chat(f_chat_id)).id 69 | except ChannelInvalid: 70 | return await message.reply('This may be a private channel / group. Make me an admin over there to index the files.') 71 | except (UsernameInvalid, UsernameNotModified): 72 | return await message.reply('Invalid Link specified.') 73 | except Exception as e: 74 | return await message.reply(f'Errors - {e}') 75 | 76 | sts = await message.reply("Generating link for your message.\nThis may take time depending upon number of messages") 77 | if chat_id in FILE_STORE_CHANNEL: 78 | string = f"{f_msg_id}_{l_msg_id}_{chat_id}_{cmd.lower().strip()}" 79 | b_64 = base64.urlsafe_b64encode(string.encode("ascii")).decode().strip("=") 80 | return await sts.edit(f"Here is your link https://telegram.me/{temp.U_NAME}?start=DSTORE-{b_64}") 81 | 82 | FRMT = "Generating Link...\nTotal Messages: `{total}`\nDone: `{current}`\nRemaining: `{rem}`\nStatus: `{sts}`" 83 | 84 | outlist = [] 85 | 86 | # file store without db channel 87 | og_msg = 0 88 | tot = 0 89 | async for msg in bot.iter_messages(f_chat_id, l_msg_id, f_msg_id): 90 | tot += 1 91 | if msg.empty or msg.service: 92 | continue 93 | if not msg.media: 94 | # only media messages supported. 95 | continue 96 | try: 97 | file_type = msg.media 98 | file = getattr(msg, file_type.value) 99 | caption = getattr(msg, 'caption', '') 100 | if caption: 101 | caption = caption.html 102 | if file: 103 | file = { 104 | "file_id": file.file_id, 105 | "caption": caption, 106 | "title": getattr(file, "file_name", ""), 107 | "size": file.file_size, 108 | "protect": cmd.lower().strip() == "/pbatch", 109 | } 110 | 111 | og_msg +=1 112 | outlist.append(file) 113 | except: 114 | pass 115 | if not og_msg % 20: 116 | try: 117 | await sts.edit(FRMT.format(total=l_msg_id-f_msg_id, current=tot, rem=((l_msg_id-f_msg_id) - tot), sts="Saving Messages")) 118 | except: 119 | pass 120 | with open(f"batchmode_{message.from_user.id}.json", "w+") as out: 121 | json.dump(outlist, out) 122 | post = await bot.send_document(LOG_CHANNEL, f"batchmode_{message.from_user.id}.json", file_name="Batch.json", caption="⚠️Generated for filestore.") 123 | os.remove(f"batchmode_{message.from_user.id}.json") 124 | file_id, ref = unpack_new_file_id(post.document.file_id) 125 | await sts.edit(f"Here is your link\nContains `{og_msg}` files.\n https://telegram.me/{temp.U_NAME}?start=BATCH-{file_id}") 126 | -------------------------------------------------------------------------------- /plugins/gfilters.py: -------------------------------------------------------------------------------- 1 | import io 2 | from pyrogram import filters, Client, enums 3 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup 4 | from database.gfilters_mdb import( 5 | add_gfilter, 6 | get_gfilters, 7 | delete_gfilter, 8 | count_gfilters 9 | ) 10 | 11 | from database.connections_mdb import active_connection 12 | from utils import get_file_id, gfilterparser, split_quotes 13 | from info import ADMINS 14 | 15 | 16 | @Client.on_message(filters.command(['gfilter', 'addg']) & filters.incoming & filters.user(ADMINS)) 17 | async def addgfilter(client, message): 18 | args = message.text.html.split(None, 1) 19 | 20 | if len(args) < 2: 21 | await message.reply_text("Command Incomplete :(", quote=True) 22 | return 23 | 24 | extracted = split_quotes(args[1]) 25 | text = extracted[0].lower() 26 | 27 | if not message.reply_to_message and len(extracted) < 2: 28 | await message.reply_text("Add some content to save your filter!", quote=True) 29 | return 30 | 31 | if (len(extracted) >= 2) and not message.reply_to_message: 32 | reply_text, btn, alert = gfilterparser(extracted[1], text) 33 | fileid = None 34 | if not reply_text: 35 | await message.reply_text("You cannot have buttons alone, give some text to go with it!", quote=True) 36 | return 37 | 38 | elif message.reply_to_message and message.reply_to_message.reply_markup: 39 | try: 40 | rm = message.reply_to_message.reply_markup 41 | btn = rm.inline_keyboard 42 | msg = get_file_id(message.reply_to_message) 43 | if msg: 44 | fileid = msg.file_id 45 | reply_text = message.reply_to_message.caption.html 46 | else: 47 | reply_text = message.reply_to_message.text.html 48 | fileid = None 49 | alert = None 50 | except: 51 | reply_text = "" 52 | btn = "[]" 53 | fileid = None 54 | alert = None 55 | 56 | elif message.reply_to_message and message.reply_to_message.media: 57 | try: 58 | msg = get_file_id(message.reply_to_message) 59 | fileid = msg.file_id if msg else None 60 | reply_text, btn, alert = gfilterparser(extracted[1], text) if message.reply_to_message.sticker else gfilterparser(message.reply_to_message.caption.html, text) 61 | except: 62 | reply_text = "" 63 | btn = "[]" 64 | alert = None 65 | elif message.reply_to_message and message.reply_to_message.text: 66 | try: 67 | fileid = None 68 | reply_text, btn, alert = gfilterparser(message.reply_to_message.text.html, text) 69 | except: 70 | reply_text = "" 71 | btn = "[]" 72 | alert = None 73 | else: 74 | return 75 | 76 | await add_gfilter('gfilters', text, reply_text, btn, fileid, alert) 77 | 78 | await message.reply_text( 79 | f"GFilter for `{text}` added", 80 | quote=True, 81 | parse_mode=enums.ParseMode.MARKDOWN 82 | ) 83 | 84 | 85 | @Client.on_message(filters.command(['viewgfilters', 'gfilters']) & filters.incoming & filters.user(ADMINS)) 86 | async def get_all_gfilters(client, message): 87 | texts = await get_gfilters('gfilters') 88 | count = await count_gfilters('gfilters') 89 | if count: 90 | gfilterlist = f"Total number of gfilters : {count}\n\n" 91 | 92 | for text in texts: 93 | keywords = " × `{}`\n".format(text) 94 | 95 | gfilterlist += keywords 96 | 97 | if len(gfilterlist) > 4096: 98 | with io.BytesIO(str.encode(gfilterlist.replace("`", ""))) as keyword_file: 99 | keyword_file.name = "keywords.txt" 100 | await message.reply_document( 101 | document=keyword_file, 102 | quote=True 103 | ) 104 | return 105 | else: 106 | gfilterlist = f"There are no active gfilters." 107 | 108 | await message.reply_text( 109 | text=gfilterlist, 110 | quote=True, 111 | parse_mode=enums.ParseMode.MARKDOWN 112 | ) 113 | 114 | @Client.on_message(filters.command('delg') & filters.incoming & filters.user(ADMINS)) 115 | async def deletegfilter(client, message): 116 | try: 117 | cmd, text = message.text.split(" ", 1) 118 | except: 119 | await message.reply_text( 120 | "Mention the gfiltername which you wanna delete!\n\n" 121 | "/delg gfiltername\n\n" 122 | "Use /viewgfilters to view all available gfilters", 123 | quote=True 124 | ) 125 | return 126 | 127 | query = text.lower() 128 | 129 | await delete_gfilter(message, query, 'gfilters') 130 | 131 | @Client.on_message(filters.command('delallg') & filters.user(ADMINS)) 132 | async def delallgfilters(client, message): 133 | await message.reply_text( 134 | f"Do you want to continue??", 135 | reply_markup=InlineKeyboardMarkup([ 136 | [InlineKeyboardButton(text="YES",callback_data="gfiltersdeleteallconfirm")], 137 | [InlineKeyboardButton(text="CANCEL",callback_data="gfiltersdeleteallcancel")] 138 | ]), 139 | quote=True 140 | ) 141 | -------------------------------------------------------------------------------- /plugins/index.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import asyncio 3 | from pyrogram import Client, filters, enums 4 | from pyrogram.errors import FloodWait 5 | from pyrogram.errors.exceptions.bad_request_400 import ChannelInvalid, ChatAdminRequired, UsernameInvalid, UsernameNotModified 6 | from info import ADMINS 7 | from info import INDEX_REQ_CHANNEL as LOG_CHANNEL 8 | from database.ia_filterdb import save_file 9 | from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton 10 | from utils import temp 11 | import re 12 | logger = logging.getLogger(__name__) 13 | logger.setLevel(logging.INFO) 14 | lock = asyncio.Lock() 15 | 16 | 17 | @Client.on_callback_query(filters.regex(r'^index')) 18 | async def index_files(bot, query): 19 | if query.data.startswith('index_cancel'): 20 | temp.CANCEL = True 21 | return await query.answer("Cancelling Indexing") 22 | _, raju, chat, lst_msg_id, from_user = query.data.split("#") 23 | if raju == 'reject': 24 | await query.message.delete() 25 | await bot.send_message(int(from_user), 26 | f'Your Submission for indexing {chat} has been decliened by our moderators.', 27 | reply_to_message_id=int(lst_msg_id)) 28 | return 29 | 30 | if lock.locked(): 31 | return await query.answer('Wait until previous process complete.', show_alert=True) 32 | msg = query.message 33 | 34 | await query.answer('Processing...⏳', show_alert=True) 35 | if int(from_user) not in ADMINS: 36 | await bot.send_message(int(from_user), 37 | f'Your Submission for indexing {chat} has been accepted by our moderators and will be added soon.', 38 | reply_to_message_id=int(lst_msg_id)) 39 | await msg.edit( 40 | "Starting Indexing", 41 | reply_markup=InlineKeyboardMarkup( 42 | [[InlineKeyboardButton('Cancel', callback_data='index_cancel')]] 43 | ) 44 | ) 45 | try: 46 | chat = int(chat) 47 | except: 48 | chat = chat 49 | await index_files_to_db(int(lst_msg_id), chat, msg, bot) 50 | 51 | 52 | @Client.on_message((filters.forwarded | (filters.regex("(https://)?(t\.me/|telegram\.me/|telegram\.dog/)(c/)?(\d+|[a-zA-Z_0-9]+)/(\d+)$")) & filters.text ) & filters.private & filters.incoming) 53 | async def send_for_index(bot, message): 54 | if message.text: 55 | regex = re.compile("(https://)?(t\.me/|telegram\.me/|telegram\.dog/)(c/)?(\d+|[a-zA-Z_0-9]+)/(\d+)$") 56 | match = regex.match(message.text) 57 | if not match: 58 | return await message.reply('Invalid link') 59 | chat_id = match.group(4) 60 | last_msg_id = int(match.group(5)) 61 | if chat_id.isnumeric(): 62 | chat_id = int(("-100" + chat_id)) 63 | elif message.forward_from_chat.type == enums.ChatType.CHANNEL: 64 | last_msg_id = message.forward_from_message_id 65 | chat_id = message.forward_from_chat.username or message.forward_from_chat.id 66 | else: 67 | return 68 | try: 69 | await bot.get_chat(chat_id) 70 | except ChannelInvalid: 71 | return await message.reply('This may be a private channel / group. Make me an admin over there to index the files.') 72 | except (UsernameInvalid, UsernameNotModified): 73 | return await message.reply('Invalid Link specified.') 74 | except Exception as e: 75 | logger.exception(e) 76 | return await message.reply(f'Errors - {e}') 77 | try: 78 | k = await bot.get_messages(chat_id, last_msg_id) 79 | except: 80 | return await message.reply('Make Sure That Iam An Admin In The Channel, if channel is private') 81 | if k.empty: 82 | return await message.reply('This may be group and iam not a admin of the group.') 83 | 84 | if message.from_user.id in ADMINS: 85 | buttons = [ 86 | [ 87 | InlineKeyboardButton('Yes', 88 | callback_data=f'index#accept#{chat_id}#{last_msg_id}#{message.from_user.id}') 89 | ], 90 | [ 91 | InlineKeyboardButton('close', callback_data='close_data'), 92 | ] 93 | ] 94 | reply_markup = InlineKeyboardMarkup(buttons) 95 | return await message.reply( 96 | f'Do you Want To Index This Channel/ Group ?\n\nChat ID/ Username: {chat_id}\nLast Message ID: {last_msg_id}', 97 | reply_markup=reply_markup) 98 | 99 | if type(chat_id) is int: 100 | try: 101 | link = (await bot.create_chat_invite_link(chat_id)).invite_link 102 | except ChatAdminRequired: 103 | return await message.reply('Make sure iam an admin in the chat and have permission to invite users.') 104 | else: 105 | link = f"@{message.forward_from_chat.username}" 106 | buttons = [ 107 | [ 108 | InlineKeyboardButton('Accept Index', 109 | callback_data=f'index#accept#{chat_id}#{last_msg_id}#{message.from_user.id}') 110 | ], 111 | [ 112 | InlineKeyboardButton('Reject Index', 113 | callback_data=f'index#reject#{chat_id}#{message.id}#{message.from_user.id}'), 114 | ] 115 | ] 116 | reply_markup = InlineKeyboardMarkup(buttons) 117 | await bot.send_message(LOG_CHANNEL, 118 | f'#IndexRequest\n\nBy : {message.from_user.mention} ({message.from_user.id})\nChat ID/ Username - {chat_id}\nLast Message ID - {last_msg_id}\nInviteLink - {link}', 119 | reply_markup=reply_markup) 120 | await message.reply('ThankYou For the Contribution, Wait For My Moderators to verify the files.') 121 | 122 | 123 | @Client.on_message(filters.command('setskip') & filters.user(ADMINS)) 124 | async def set_skip_number(bot, message): 125 | if ' ' in message.text: 126 | _, skip = message.text.split(" ") 127 | try: 128 | skip = int(skip) 129 | except: 130 | return await message.reply("Skip number should be an integer.") 131 | await message.reply(f"Successfully set SKIP number as {skip}") 132 | temp.CURRENT = int(skip) 133 | else: 134 | await message.reply("Give me a skip number") 135 | 136 | 137 | async def index_files_to_db(lst_msg_id, chat, msg, bot): 138 | total_files = 0 139 | duplicate = 0 140 | errors = 0 141 | deleted = 0 142 | no_media = 0 143 | unsupported = 0 144 | async with lock: 145 | try: 146 | current = temp.CURRENT 147 | temp.CANCEL = False 148 | async for message in bot.iter_messages(chat, lst_msg_id, temp.CURRENT): 149 | if temp.CANCEL: 150 | await msg.edit(f"Successfully Cancelled!!\n\nSaved {total_files} files to dataBase!\nDuplicate Files Skipped: {duplicate}\nDeleted Messages Skipped: {deleted}\nNon-Media messages skipped: {no_media + unsupported}(Unsupported Media - `{unsupported}` )\nErrors Occurred: {errors}") 151 | break 152 | current += 1 153 | if current % 20 == 0: 154 | can = [[InlineKeyboardButton('Cancel', callback_data='index_cancel')]] 155 | reply = InlineKeyboardMarkup(can) 156 | await msg.edit_text( 157 | text=f"Total messages fetched: {current}\nTotal messages saved: {total_files}\nDuplicate Files Skipped: {duplicate}\nDeleted Messages Skipped: {deleted}\nNon-Media messages skipped: {no_media + unsupported}(Unsupported Media - `{unsupported}` )\nErrors Occurred: {errors}", 158 | reply_markup=reply) 159 | if message.empty: 160 | deleted += 1 161 | continue 162 | elif not message.media: 163 | no_media += 1 164 | continue 165 | elif message.media not in [enums.MessageMediaType.VIDEO, enums.MessageMediaType.AUDIO, enums.MessageMediaType.DOCUMENT]: 166 | unsupported += 1 167 | continue 168 | media = getattr(message, message.media.value, None) 169 | if not media: 170 | unsupported += 1 171 | continue 172 | media.file_type = message.media.value 173 | media.caption = message.caption 174 | aynav, vnay = await save_file(media) 175 | if aynav: 176 | total_files += 1 177 | elif vnay == 0: 178 | duplicate += 1 179 | elif vnay == 2: 180 | errors += 1 181 | except Exception as e: 182 | logger.exception(e) 183 | await msg.edit(f'Error: {e}') 184 | else: 185 | await msg.edit(f'Succesfully saved {total_files} to dataBase!\nDuplicate Files Skipped: {duplicate}\nDeleted Messages Skipped: {deleted}\nNon-Media messages skipped: {no_media + unsupported}(Unsupported Media - `{unsupported}` )\nErrors Occurred: {errors}') 186 | -------------------------------------------------------------------------------- /plugins/inline.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from pyrogram import Client, emoji, filters 3 | from pyrogram.errors.exceptions.bad_request_400 import QueryIdInvalid 4 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, InlineQueryResultCachedDocument, InlineQuery 5 | from database.ia_filterdb import get_search_results 6 | from utils import is_subscribed, get_size, temp 7 | from info import CACHE_TIME, AUTH_USERS, AUTH_CHANNEL, CUSTOM_FILE_CAPTION 8 | from database.connections_mdb import active_connection 9 | 10 | logger = logging.getLogger(__name__) 11 | cache_time = 0 if AUTH_USERS or AUTH_CHANNEL else CACHE_TIME 12 | 13 | async def inline_users(query: InlineQuery): 14 | if AUTH_USERS: 15 | if query.from_user and query.from_user.id in AUTH_USERS: 16 | return True 17 | else: 18 | return False 19 | if query.from_user and query.from_user.id not in temp.BANNED_USERS: 20 | return True 21 | return False 22 | 23 | @Client.on_inline_query() 24 | async def answer(bot, query): 25 | """Show search results for given inline query""" 26 | chat_id = await active_connection(str(query.from_user.id)) 27 | 28 | if not await inline_users(query): 29 | await query.answer(results=[], 30 | cache_time=0, 31 | switch_pm_text='You are Not A VIP Member', 32 | switch_pm_parameter="hehe") 33 | return 34 | 35 | if AUTH_CHANNEL and not await is_subscribed(bot, query): 36 | await query.answer(results=[], 37 | cache_time=0, 38 | switch_pm_text='You have to subscribe my channel to use the bot', 39 | switch_pm_parameter="subscribe") 40 | return 41 | 42 | results = [] 43 | if '|' in query.query: 44 | string, file_type = query.query.split('|', maxsplit=1) 45 | string = string.strip() 46 | file_type = file_type.strip().lower() 47 | else: 48 | string = query.query.strip() 49 | file_type = None 50 | 51 | offset = int(query.offset or 0) 52 | reply_markup = get_reply_markup(query=string) 53 | files, next_offset, total = await get_search_results( 54 | chat_id, 55 | string, 56 | file_type=file_type, 57 | max_results=10, 58 | offset=offset) 59 | 60 | for file in files: 61 | title=file.file_name 62 | size=get_size(file.file_size) 63 | f_caption=file.caption 64 | if CUSTOM_FILE_CAPTION: 65 | try: 66 | f_caption=CUSTOM_FILE_CAPTION.format(file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='' if f_caption is None else f_caption) 67 | except Exception as e: 68 | logger.exception(e) 69 | f_caption=f_caption 70 | if f_caption is None: 71 | f_caption = f"{file.file_name}" 72 | results.append( 73 | InlineQueryResultCachedDocument( 74 | title=file.file_name, 75 | document_file_id=file.file_id, 76 | caption=f_caption, 77 | description=f'Size: {get_size(file.file_size)}\nType: {file.file_type}', 78 | reply_markup=reply_markup)) 79 | 80 | if results: 81 | switch_pm_text = f"{emoji.FILE_FOLDER} Results - {total}" 82 | if string: 83 | switch_pm_text += f" for {string}" 84 | try: 85 | await query.answer(results=results, 86 | is_personal = True, 87 | cache_time=cache_time, 88 | switch_pm_text=switch_pm_text, 89 | switch_pm_parameter="start", 90 | next_offset=str(next_offset)) 91 | except QueryIdInvalid: 92 | pass 93 | except Exception as e: 94 | logging.exception(str(e)) 95 | else: 96 | switch_pm_text = f'{emoji.CROSS_MARK} No results' 97 | if string: 98 | switch_pm_text += f' for "{string}"' 99 | 100 | await query.answer(results=[], 101 | is_personal = True, 102 | cache_time=cache_time, 103 | switch_pm_text=switch_pm_text, 104 | switch_pm_parameter="okay") 105 | 106 | 107 | def get_reply_markup(query): 108 | buttons = [ 109 | [ 110 | InlineKeyboardButton('Search again', switch_inline_query_current_chat=query) 111 | ] 112 | ] 113 | return InlineKeyboardMarkup(buttons) 114 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /plugins/misc.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pyrogram import Client, filters, enums 3 | from pyrogram.errors.exceptions.bad_request_400 import UserNotParticipant, MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty 4 | from info import IMDB_TEMPLATE 5 | from utils import extract_user, get_file_id, get_poster, last_online 6 | import time 7 | from datetime import datetime 8 | from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery 9 | import logging 10 | logger = logging.getLogger(__name__) 11 | logger.setLevel(logging.ERROR) 12 | 13 | @Client.on_message(filters.command('id')) 14 | async def showid(client, message): 15 | chat_type = message.chat.type 16 | if chat_type == enums.ChatType.PRIVATE: 17 | user_id = message.chat.id 18 | first = message.from_user.first_name 19 | last = message.from_user.last_name or "" 20 | username = message.from_user.username 21 | dc_id = message.from_user.dc_id or "" 22 | await message.reply_text( 23 | f"➲ First Name: {first}\n➲ Last Name: {last}\n➲ Username: {username}\n➲ Telegram ID: {user_id}\n➲ Data Centre: {dc_id}", 24 | quote=True 25 | ) 26 | 27 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: 28 | _id = "" 29 | _id += ( 30 | "➲ Chat ID: " 31 | f"{message.chat.id}\n" 32 | ) 33 | if message.reply_to_message: 34 | _id += ( 35 | "➲ User ID: " 36 | f"{message.from_user.id if message.from_user else 'Anonymous'}\n" 37 | "➲ Replied User ID: " 38 | f"{message.reply_to_message.from_user.id if message.reply_to_message.from_user else 'Anonymous'}\n" 39 | ) 40 | file_info = get_file_id(message.reply_to_message) 41 | else: 42 | _id += ( 43 | "➲ User ID: " 44 | f"{message.from_user.id if message.from_user else 'Anonymous'}\n" 45 | ) 46 | file_info = get_file_id(message) 47 | if file_info: 48 | _id += ( 49 | f"{file_info.message_type}: " 50 | f"{file_info.file_id}\n" 51 | ) 52 | await message.reply_text( 53 | _id, 54 | quote=True 55 | ) 56 | 57 | @Client.on_message(filters.command(["info"])) 58 | async def who_is(client, message): 59 | # https://github.com/SpEcHiDe/PyroGramBot/blob/master/pyrobot/plugins/admemes/whois.py#L19 60 | status_message = await message.reply_text( 61 | "`Fetching user info...`" 62 | ) 63 | await status_message.edit( 64 | "`Processing user info...`" 65 | ) 66 | from_user = None 67 | from_user_id, _ = extract_user(message) 68 | try: 69 | from_user = await client.get_users(from_user_id) 70 | except Exception as error: 71 | await status_message.edit(str(error)) 72 | return 73 | if from_user is None: 74 | return await status_message.edit("no valid user_id / message specified") 75 | message_out_str = "" 76 | message_out_str += f"➲First Name: {from_user.first_name}\n" 77 | last_name = from_user.last_name or "None" 78 | message_out_str += f"➲Last Name: {last_name}\n" 79 | message_out_str += f"➲Telegram ID: {from_user.id}\n" 80 | username = from_user.username or "None" 81 | dc_id = from_user.dc_id or "[User Doesn't Have A Valid DP]" 82 | message_out_str += f"➲Data Centre: {dc_id}\n" 83 | message_out_str += f"➲User Name: @{username}\n" 84 | message_out_str += f"➲User 𝖫𝗂𝗇𝗄: Click Here\n" 85 | if message.chat.type in ((enums.ChatType.SUPERGROUP, enums.ChatType.CHANNEL)): 86 | try: 87 | chat_member_p = await message.chat.get_member(from_user.id) 88 | joined_date = ( 89 | chat_member_p.joined_date or datetime.now() 90 | ).strftime("%Y.%m.%d %H:%M:%S") 91 | message_out_str += ( 92 | "➲Joined this Chat on: " 93 | f"{joined_date}" 94 | "\n" 95 | ) 96 | except UserNotParticipant: 97 | pass 98 | chat_photo = from_user.photo 99 | if chat_photo: 100 | local_user_photo = await client.download_media( 101 | message=chat_photo.big_file_id 102 | ) 103 | buttons = [[ 104 | InlineKeyboardButton('🔐 Close', callback_data='close_data') 105 | ]] 106 | reply_markup = InlineKeyboardMarkup(buttons) 107 | await message.reply_photo( 108 | photo=local_user_photo, 109 | quote=True, 110 | reply_markup=reply_markup, 111 | caption=message_out_str, 112 | parse_mode=enums.ParseMode.HTML, 113 | disable_notification=True 114 | ) 115 | os.remove(local_user_photo) 116 | else: 117 | buttons = [[ 118 | InlineKeyboardButton('🔐 Close', callback_data='close_data') 119 | ]] 120 | reply_markup = InlineKeyboardMarkup(buttons) 121 | await message.reply_text( 122 | text=message_out_str, 123 | reply_markup=reply_markup, 124 | quote=True, 125 | parse_mode=enums.ParseMode.HTML, 126 | disable_notification=True 127 | ) 128 | await status_message.delete() 129 | 130 | @Client.on_message(filters.command(["imdb", 'search'])) 131 | async def imdb_search(client, message): 132 | if ' ' in message.text: 133 | k = await message.reply('Searching ImDB') 134 | r, title = message.text.split(None, 1) 135 | movies = await get_poster(title, bulk=True) 136 | if not movies: 137 | return await message.reply("No results Found") 138 | btn = [ 139 | [ 140 | InlineKeyboardButton( 141 | text=f"{movie.get('title')} - {movie.get('year')}", 142 | callback_data=f"imdb#{movie.movieID}", 143 | ) 144 | ] 145 | for movie in movies 146 | ] 147 | await k.edit('Here is what i found on IMDb', reply_markup=InlineKeyboardMarkup(btn)) 148 | else: 149 | await message.reply('Give me a movie / series Name') 150 | 151 | @Client.on_callback_query(filters.regex('^imdb')) 152 | async def imdb_callback(bot: Client, quer_y: CallbackQuery): 153 | i, movie = quer_y.data.split('#') 154 | imdb = await get_poster(query=movie, id=True) 155 | btn = [ 156 | [ 157 | InlineKeyboardButton( 158 | text=f"{imdb.get('title')}", 159 | url=imdb['url'], 160 | ) 161 | ] 162 | ] 163 | message = quer_y.message.reply_to_message or quer_y.message 164 | if imdb: 165 | caption = IMDB_TEMPLATE.format( 166 | query = imdb['title'], 167 | title = imdb['title'], 168 | votes = imdb['votes'], 169 | aka = imdb["aka"], 170 | seasons = imdb["seasons"], 171 | box_office = imdb['box_office'], 172 | localized_title = imdb['localized_title'], 173 | kind = imdb['kind'], 174 | imdb_id = imdb["imdb_id"], 175 | cast = imdb["cast"], 176 | runtime = imdb["runtime"], 177 | countries = imdb["countries"], 178 | certificates = imdb["certificates"], 179 | languages = imdb["languages"], 180 | director = imdb["director"], 181 | writer = imdb["writer"], 182 | producer = imdb["producer"], 183 | composer = imdb["composer"], 184 | cinematographer = imdb["cinematographer"], 185 | music_team = imdb["music_team"], 186 | distributors = imdb["distributors"], 187 | release_date = imdb['release_date'], 188 | year = imdb['year'], 189 | genres = imdb['genres'], 190 | poster = imdb['poster'], 191 | plot = imdb['plot'], 192 | rating = imdb['rating'], 193 | url = imdb['url'], 194 | **locals() 195 | ) 196 | else: 197 | caption = "No Results" 198 | if imdb.get('poster'): 199 | try: 200 | await quer_y.message.reply_photo(photo=imdb['poster'], caption=caption, reply_markup=InlineKeyboardMarkup(btn)) 201 | except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty): 202 | pic = imdb.get('poster') 203 | poster = pic.replace('.jpg', "._V1_UX360.jpg") 204 | await quer_y.message.reply_photo(photo=poster, caption=caption, reply_markup=InlineKeyboardMarkup(btn)) 205 | except Exception as e: 206 | logger.exception(e) 207 | await quer_y.message.reply(caption, reply_markup=InlineKeyboardMarkup(btn), disable_web_page_preview=False) 208 | await quer_y.message.delete() 209 | else: 210 | await quer_y.message.edit(caption, reply_markup=InlineKeyboardMarkup(btn), disable_web_page_preview=False) 211 | await quer_y.answer() 212 | 213 | 214 | 215 | -------------------------------------------------------------------------------- /plugins/p_ttishow.py: -------------------------------------------------------------------------------- 1 | from pyrogram import Client, filters, enums 2 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery 3 | from pyrogram.errors.exceptions.bad_request_400 import MessageTooLong, PeerIdInvalid 4 | from info import ADMINS, LOG_CHANNEL, SUPPORT_CHAT, MELCOW_NEW_USERS, MELCOW_VID, CHNL_LNK, GRP_LNK 5 | from database.users_chats_db import db 6 | from database.ia_filterdb import Media 7 | from utils import get_size, temp, get_settings 8 | from Script import script 9 | from pyrogram.errors import ChatAdminRequired 10 | import asyncio 11 | 12 | """-----------------------------------------https://t.me/GetTGLink/4179 --------------------------------------""" 13 | 14 | @Client.on_message(filters.new_chat_members & filters.group) 15 | async def save_group(bot, message): 16 | r_j_check = [u.id for u in message.new_chat_members] 17 | if temp.ME in r_j_check: 18 | if not await db.get_chat(message.chat.id): 19 | total=await bot.get_chat_members_count(message.chat.id) 20 | r_j = message.from_user.mention if message.from_user else "Anonymous" 21 | await bot.send_message(LOG_CHANNEL, script.LOG_TEXT_G.format(message.chat.title, message.chat.id, total, r_j)) 22 | await db.add_chat(message.chat.id, message.chat.title) 23 | if message.chat.id in temp.BANNED_CHATS: 24 | # Inspired from a boat of a banana tree 25 | buttons = [[ 26 | InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}') 27 | ]] 28 | reply_markup=InlineKeyboardMarkup(buttons) 29 | k = await message.reply( 30 | text='CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..', 31 | reply_markup=reply_markup, 32 | ) 33 | 34 | try: 35 | await k.pin() 36 | except: 37 | pass 38 | await bot.leave_chat(message.chat.id) 39 | return 40 | buttons = [ 41 | [ 42 | InlineKeyboardButton('📣 Uᴘᴅᴀᴛᴇs 📣', url='https://t.me/VJ_Bots') 43 | ], 44 | [ 45 | InlineKeyboardButton('♠️ Subscribe ♠️', url='https://youtube.com/@Tech_VJ'), 46 | ], 47 | [ 48 | InlineKeyboardButton('🎗️ Owner 🎗️',url='https://t.me/anjel_neha') 49 | ] 50 | ] 51 | reply_markup=InlineKeyboardMarkup(buttons) 52 | await message.reply_text( 53 | text=f"Thankyou For Adding Me In {message.chat.title} ❣️\n\nIf you have any questions & doubts about using me contact support.", 54 | reply_markup=reply_markup) 55 | else: 56 | settings = await get_settings(message.chat.id) 57 | if settings["welcome"]: 58 | for u in message.new_chat_members: 59 | if (temp.MELCOW).get('welcome') is not None: 60 | try: 61 | await (temp.MELCOW['welcome']).delete() 62 | except: 63 | pass 64 | temp.MELCOW['welcome'] = await message.reply_photo( 65 | photo="https://telegra.ph/file/dc2438eb0094b7301f2e0.jpg", 66 | caption=f'ʜᴇʏ, {u.mention} 👋🏻\nᴡᴇʟᴄᴏᴍᴇ ᴛᴏ ᴏᴜʀ ɢʀᴏᴜᴘ {message.chat.title}\n\nʏᴏᴜ ᴄᴀɴ ꜰɪɴᴅ ᴍᴏᴠɪᴇꜱ / ꜱᴇʀɪᴇꜱ / ᴀɴɪᴍᴇꜱ ᴇᴛᴄ. ꜰʀᴏᴍ ʜᴇʀᴇ. ᴇɴᴊᴏʏ😉.\n\n┏≫ ғᴏʟʟᴏᴡ ɢʀᴏᴜᴘ ʀᴜʟᴇs\n┣ ᴍᴀɪɴ ᴄʜᴀɴɴᴇʟ ›› @VJ_Bots\n┗≫ ғᴏʟʟᴏᴡ ɢʀᴏᴜᴘ ʀᴜʟᴇs', 67 | reply_markup=InlineKeyboardMarkup( [ [ InlineKeyboardButton('🍿 Update Channel 🍿', url='http://t.me/vj_bots') ] ] ) 68 | ) 69 | 70 | 71 | @Client.on_message(filters.command('leave') & filters.user(ADMINS)) 72 | async def leave_a_chat(bot, message): 73 | if len(message.command) == 1: 74 | return await message.reply('Give me a chat id') 75 | chat = message.command[1] 76 | try: 77 | chat = int(chat) 78 | except: 79 | chat = chat 80 | try: 81 | buttons = [[ 82 | InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}') 83 | ]] 84 | reply_markup=InlineKeyboardMarkup(buttons) 85 | await bot.send_message( 86 | chat_id=chat, 87 | text='Hello Friends, \nMy admin has told me to leave from group so i go! If you wanna add me again contact my support group.', 88 | reply_markup=reply_markup, 89 | ) 90 | 91 | await bot.leave_chat(chat) 92 | await message.reply(f"left the chat `{chat}`") 93 | except Exception as e: 94 | await message.reply(f'Error - {e}') 95 | 96 | @Client.on_message(filters.command('disable') & filters.user(ADMINS)) 97 | async def disable_chat(bot, message): 98 | if len(message.command) == 1: 99 | return await message.reply('Give me a chat id') 100 | r = message.text.split(None) 101 | if len(r) > 2: 102 | reason = message.text.split(None, 2)[2] 103 | chat = message.text.split(None, 2)[1] 104 | else: 105 | chat = message.command[1] 106 | reason = "No reason Provided" 107 | try: 108 | chat_ = int(chat) 109 | except: 110 | return await message.reply('Give Me A Valid Chat ID') 111 | cha_t = await db.get_chat(int(chat_)) 112 | if not cha_t: 113 | return await message.reply("Chat Not Found In DB") 114 | if cha_t['is_disabled']: 115 | return await message.reply(f"This chat is already disabled:\nReason- {cha_t['reason']} ") 116 | await db.disable_chat(int(chat_), reason) 117 | temp.BANNED_CHATS.append(int(chat_)) 118 | await message.reply('Chat Successfully Disabled') 119 | try: 120 | buttons = [[ 121 | InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}') 122 | ]] 123 | reply_markup=InlineKeyboardMarkup(buttons) 124 | await bot.send_message( 125 | chat_id=chat_, 126 | text=f'Hello Friends, \nMy admin has told me to leave from group so i go! If you wanna add me again contact my support group. \nReason : {reason}', 127 | reply_markup=reply_markup) 128 | await bot.leave_chat(chat_) 129 | except Exception as e: 130 | await message.reply(f"Error - {e}") 131 | 132 | 133 | @Client.on_message(filters.command('enable') & filters.user(ADMINS)) 134 | async def re_enable_chat(bot, message): 135 | if len(message.command) == 1: 136 | return await message.reply('Give me a chat id') 137 | chat = message.command[1] 138 | try: 139 | chat_ = int(chat) 140 | except: 141 | return await message.reply('Give Me A Valid Chat ID') 142 | sts = await db.get_chat(int(chat)) 143 | if not sts: 144 | return await message.reply("Chat Not Found In DB !") 145 | if not sts.get('is_disabled'): 146 | return await message.reply('This chat is not yet disabled.') 147 | await db.re_enable_chat(int(chat_)) 148 | temp.BANNED_CHATS.remove(int(chat_)) 149 | await message.reply("Chat Successfully re-enabled") 150 | 151 | 152 | @Client.on_message(filters.command('stats') & filters.incoming) 153 | async def get_ststs(bot, message): 154 | rju = await message.reply('Fetching stats..') 155 | total_users = await db.total_users_count() 156 | totl_chats = await db.total_chat_count() 157 | files = await Media.count_documents() 158 | size = await db.get_db_size() 159 | free = 536870912 - size 160 | size = get_size(size) 161 | free = get_size(free) 162 | await rju.edit(script.STATUS_TXT.format(files, total_users, totl_chats, size, free)) 163 | 164 | 165 | @Client.on_message(filters.command('invite') & filters.user(ADMINS)) 166 | async def gen_invite(bot, message): 167 | if len(message.command) == 1: 168 | return await message.reply('Give me a chat id') 169 | chat = message.command[1] 170 | try: 171 | chat = int(chat) 172 | except: 173 | return await message.reply('Give Me A Valid Chat ID') 174 | try: 175 | link = await bot.create_chat_invite_link(chat) 176 | except ChatAdminRequired: 177 | return await message.reply("Invite Link Generation Failed, Iam Not Having Sufficient Rights") 178 | except Exception as e: 179 | return await message.reply(f'Error {e}') 180 | await message.reply(f'Here is your Invite Link {link.invite_link}') 181 | 182 | @Client.on_message(filters.command('ban') & filters.user(ADMINS)) 183 | async def ban_a_user(bot, message): 184 | # https://t.me/GetTGLink/4185 185 | if len(message.command) == 1: 186 | return await message.reply('Give me a user id / username') 187 | r = message.text.split(None) 188 | if len(r) > 2: 189 | reason = message.text.split(None, 2)[2] 190 | chat = message.text.split(None, 2)[1] 191 | else: 192 | chat = message.command[1] 193 | reason = "No reason Provided" 194 | try: 195 | chat = int(chat) 196 | except: 197 | pass 198 | try: 199 | k = await bot.get_users(chat) 200 | except PeerIdInvalid: 201 | return await message.reply("This is an invalid user, make sure ia have met him before.") 202 | except IndexError: 203 | return await message.reply("This might be a channel, make sure its a user.") 204 | except Exception as e: 205 | return await message.reply(f'Error - {e}') 206 | else: 207 | jar = await db.get_ban_status(k.id) 208 | if jar['is_banned']: 209 | return await message.reply(f"{k.mention} is already banned\nReason: {jar['ban_reason']}") 210 | await db.ban_user(k.id, reason) 211 | temp.BANNED_USERS.append(k.id) 212 | await message.reply(f"Successfully banned {k.mention}") 213 | 214 | 215 | 216 | @Client.on_message(filters.command('unban') & filters.user(ADMINS)) 217 | async def unban_a_user(bot, message): 218 | if len(message.command) == 1: 219 | return await message.reply('Give me a user id / username') 220 | r = message.text.split(None) 221 | if len(r) > 2: 222 | reason = message.text.split(None, 2)[2] 223 | chat = message.text.split(None, 2)[1] 224 | else: 225 | chat = message.command[1] 226 | reason = "No reason Provided" 227 | try: 228 | chat = int(chat) 229 | except: 230 | pass 231 | try: 232 | k = await bot.get_users(chat) 233 | except PeerIdInvalid: 234 | return await message.reply("This is an invalid user, make sure ia have met him before.") 235 | except IndexError: 236 | return await message.reply("Thismight be a channel, make sure its a user.") 237 | except Exception as e: 238 | return await message.reply(f'Error - {e}') 239 | else: 240 | jar = await db.get_ban_status(k.id) 241 | if not jar['is_banned']: 242 | return await message.reply(f"{k.mention} is not yet banned.") 243 | await db.remove_ban(k.id) 244 | temp.BANNED_USERS.remove(k.id) 245 | await message.reply(f"Successfully unbanned {k.mention}") 246 | 247 | 248 | 249 | @Client.on_message(filters.command('users') & filters.user(ADMINS)) 250 | async def list_users(bot, message): 251 | # https://t.me/GetTGLink/4184 252 | raju = await message.reply('Getting List Of Users') 253 | users = await db.get_all_users() 254 | out = "Users Saved In DB Are:\n\n" 255 | async for user in users: 256 | out += f"{user['name']}" 257 | if user['ban_status']['is_banned']: 258 | out += '( Banned User )' 259 | out += '\n' 260 | try: 261 | await raju.edit_text(out) 262 | except MessageTooLong: 263 | with open('users.txt', 'w+') as outfile: 264 | outfile.write(out) 265 | await message.reply_document('users.txt', caption="List Of Users") 266 | 267 | @Client.on_message(filters.command('chats') & filters.user(ADMINS)) 268 | async def list_chats(bot, message): 269 | raju = await message.reply('Getting List Of chats') 270 | chats = await db.get_all_chats() 271 | out = "Chats Saved In DB Are:\n\n" 272 | async for chat in chats: 273 | out += f"**Title:** `{chat['title']}`\n**- ID:** `{chat['id']}`" 274 | if chat['chat_status']['is_disabled']: 275 | out += '( Disabled Chat )' 276 | out += '\n' 277 | try: 278 | await raju.edit_text(out) 279 | except MessageTooLong: 280 | with open('chats.txt', 'w+') as outfile: 281 | outfile.write(out) 282 | await message.reply_document('chats.txt', caption="List Of Chats") 283 | -------------------------------------------------------------------------------- /plugins/route.py: -------------------------------------------------------------------------------- 1 | from aiohttp import web 2 | 3 | routes = web.RouteTableDef() 4 | 5 | @routes.get("/", allow_head=True) 6 | async def root_route_handler(request): 7 | return web.json_response("DQTheFileDonor") 8 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pyrogram>=2.0.30 2 | tgcrypto 3 | pymongo[srv]==3.12.3 4 | motor==2.5.1 5 | marshmallow==3.14.1 6 | umongo==3.0.1 7 | requests 8 | bs4 9 | git+https://github.com/Joelkb/cinemagoer 10 | datetime 11 | pytz 12 | aiohttp 13 | -------------------------------------------------------------------------------- /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.8.7 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 | 25 | -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | if [ -z $UPSTREAM_REPO ] 2 | then 3 | echo "Cloning main Repository" 4 | git clone https://github.com/VJBots/Advance-Auto-Filter /Advance-Auto-Filter 5 | else 6 | echo "Cloning Custom Repo from $UPSTREAM_REPO " 7 | git clone $UPSTREAM_REPO /Advance-Auto-Filter 8 | fi 9 | cd /Advance-Auto-Filter 10 | pip3 install -U -r requirements.txt 11 | echo "Starting Bot...." 12 | python3 bot.py 13 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from pyrogram.errors import InputUserDeactivated, UserNotParticipant, FloodWait, UserIsBlocked, PeerIdInvalid 3 | from info import AUTH_CHANNEL, LONG_IMDB_DESCRIPTION, MAX_LIST_ELM, SHORTLINK_URL, SHORTLINK_API 4 | from imdb import Cinemagoer 5 | import asyncio 6 | from pyrogram.types import Message, InlineKeyboardButton 7 | from pyrogram import enums 8 | from typing import Union 9 | import random 10 | import re 11 | import os 12 | from datetime import datetime 13 | from typing import List 14 | from database.users_chats_db import db 15 | from bs4 import BeautifulSoup 16 | import requests 17 | import aiohttp 18 | 19 | logger = logging.getLogger(__name__) 20 | logger.setLevel(logging.INFO) 21 | 22 | BTN_URL_REGEX = re.compile( 23 | r"(\[([^\[]+?)\]\((buttonurl|buttonalert):(?:/{0,2})(.+?)(:same)?\))" 24 | ) 25 | 26 | imdb = Cinemagoer() 27 | 28 | BANNED = {} 29 | SMART_OPEN = '“' 30 | SMART_CLOSE = '”' 31 | START_CHAR = ('\'', '"', SMART_OPEN) 32 | 33 | # temp db for banned 34 | class temp(object): 35 | BANNED_USERS = [] 36 | BANNED_CHATS = [] 37 | ME = None 38 | CURRENT=int(os.environ.get("SKIP", 2)) 39 | CANCEL = False 40 | MELCOW = {} 41 | U_NAME = None 42 | B_NAME = None 43 | SETTINGS = {} 44 | 45 | async def is_subscribed(bot, query): 46 | try: 47 | user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id) 48 | except UserNotParticipant: 49 | pass 50 | except Exception as e: 51 | logger.exception(e) 52 | else: 53 | if user.status != 'kicked': 54 | return True 55 | 56 | return False 57 | 58 | async def get_poster(query, bulk=False, id=False, file=None): 59 | if not id: 60 | # https://t.me/GetTGLink/4183 61 | query = (query.strip()).lower() 62 | title = query 63 | year = re.findall(r'[1-2]\d{3}$', query, re.IGNORECASE) 64 | if year: 65 | year = list_to_str(year[:1]) 66 | title = (query.replace(year, "")).strip() 67 | elif file is not None: 68 | year = re.findall(r'[1-2]\d{3}', file, re.IGNORECASE) 69 | if year: 70 | year = list_to_str(year[:1]) 71 | else: 72 | year = None 73 | movieid = imdb.search_movie(title.lower(), results=10) 74 | if not movieid: 75 | return None 76 | if year: 77 | filtered=list(filter(lambda k: str(k.get('year')) == str(year), movieid)) 78 | if not filtered: 79 | filtered = movieid 80 | else: 81 | filtered = movieid 82 | movieid=list(filter(lambda k: k.get('kind') in ['movie', 'tv series'], filtered)) 83 | if not movieid: 84 | movieid = filtered 85 | if bulk: 86 | return movieid 87 | movieid = movieid[0].movieID 88 | else: 89 | movieid = query 90 | movie = imdb.get_movie(movieid) 91 | if movie.get("original air date"): 92 | date = movie["original air date"] 93 | elif movie.get("year"): 94 | date = movie.get("year") 95 | else: 96 | date = "N/A" 97 | plot = "" 98 | if not LONG_IMDB_DESCRIPTION: 99 | plot = movie.get('plot') 100 | if plot and len(plot) > 0: 101 | plot = plot[0] 102 | else: 103 | plot = movie.get('plot outline') 104 | if plot and len(plot) > 800: 105 | plot = plot[0:800] + "..." 106 | 107 | return { 108 | 'title': movie.get('title'), 109 | 'votes': movie.get('votes'), 110 | "aka": list_to_str(movie.get("akas")), 111 | "seasons": movie.get("number of seasons"), 112 | "box_office": movie.get('box office'), 113 | 'localized_title': movie.get('localized title'), 114 | 'kind': movie.get("kind"), 115 | "imdb_id": f"tt{movie.get('imdbID')}", 116 | "cast": list_to_str(movie.get("cast")), 117 | "runtime": list_to_str(movie.get("runtimes")), 118 | "countries": list_to_str(movie.get("countries")), 119 | "certificates": list_to_str(movie.get("certificates")), 120 | "languages": list_to_str(movie.get("languages")), 121 | "director": list_to_str(movie.get("director")), 122 | "writer":list_to_str(movie.get("writer")), 123 | "producer":list_to_str(movie.get("producer")), 124 | "composer":list_to_str(movie.get("composer")) , 125 | "cinematographer":list_to_str(movie.get("cinematographer")), 126 | "music_team": list_to_str(movie.get("music department")), 127 | "distributors": list_to_str(movie.get("distributors")), 128 | 'release_date': date, 129 | 'year': movie.get('year'), 130 | 'genres': list_to_str(movie.get("genres")), 131 | 'poster': movie.get('full-size cover url'), 132 | 'plot': plot, 133 | 'rating': str(movie.get("rating")), 134 | 'url':f'https://www.imdb.com/title/tt{movieid}' 135 | } 136 | # https://github.com/odysseusmax/animated-lamp/blob/2ef4730eb2b5f0596ed6d03e7b05243d93e3415b/bot/utils/broadcast.py#L37 137 | 138 | async def broadcast_messages(user_id, message): 139 | try: 140 | await message.copy(chat_id=user_id) 141 | return True, "Success" 142 | except FloodWait as e: 143 | await asyncio.sleep(e.x) 144 | return await broadcast_messages(user_id, message) 145 | except InputUserDeactivated: 146 | await db.delete_user(int(user_id)) 147 | logging.info(f"{user_id}-Removed from Database, since deleted account.") 148 | return False, "Deleted" 149 | except UserIsBlocked: 150 | logging.info(f"{user_id} -Blocked the bot.") 151 | return False, "Blocked" 152 | except PeerIdInvalid: 153 | await db.delete_user(int(user_id)) 154 | logging.info(f"{user_id} - PeerIdInvalid") 155 | return False, "Error" 156 | except Exception as e: 157 | return False, "Error" 158 | 159 | async def search_gagala(text): 160 | usr_agent = { 161 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 162 | 'Chrome/61.0.3163.100 Safari/537.36' 163 | } 164 | text = text.replace(" ", '+') 165 | url = f'https://www.google.com/search?q={text}' 166 | response = requests.get(url, headers=usr_agent) 167 | response.raise_for_status() 168 | soup = BeautifulSoup(response.text, 'html.parser') 169 | titles = soup.find_all( 'h3' ) 170 | return [title.getText() for title in titles] 171 | 172 | async def get_settings(group_id): 173 | settings = temp.SETTINGS.get(group_id) 174 | if not settings: 175 | settings = await db.get_settings(group_id) 176 | temp.SETTINGS[group_id] = settings 177 | return settings 178 | 179 | async def save_group_settings(group_id, key, value): 180 | current = await get_settings(group_id) 181 | current[key] = value 182 | temp.SETTINGS[group_id] = current 183 | await db.update_settings(group_id, current) 184 | 185 | def get_size(size): 186 | """Get size in readable format""" 187 | 188 | units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"] 189 | size = float(size) 190 | i = 0 191 | while size >= 1024.0 and i < len(units): 192 | i += 1 193 | size /= 1024.0 194 | return "%.2f %s" % (size, units[i]) 195 | 196 | def split_list(l, n): 197 | for i in range(0, len(l), n): 198 | yield l[i:i + n] 199 | 200 | def get_file_id(msg: Message): 201 | if msg.media: 202 | for message_type in ( 203 | "photo", 204 | "animation", 205 | "audio", 206 | "document", 207 | "video", 208 | "video_note", 209 | "voice", 210 | "sticker" 211 | ): 212 | obj = getattr(msg, message_type) 213 | if obj: 214 | setattr(obj, "message_type", message_type) 215 | return obj 216 | 217 | def extract_user(message: Message) -> Union[int, str]: 218 | """extracts the user from a message""" 219 | # https://github.com/SpEcHiDe/PyroGramBot/blob/f30e2cca12002121bad1982f68cd0ff9814ce027/pyrobot/helper_functions/extract_user.py#L7 220 | user_id = None 221 | user_first_name = None 222 | if message.reply_to_message: 223 | user_id = message.reply_to_message.from_user.id 224 | user_first_name = message.reply_to_message.from_user.first_name 225 | 226 | elif len(message.command) > 1: 227 | if ( 228 | len(message.entities) > 1 and 229 | message.entities[1].type == enums.MessageEntityType.TEXT_MENTION 230 | ): 231 | 232 | required_entity = message.entities[1] 233 | user_id = required_entity.user.id 234 | user_first_name = required_entity.user.first_name 235 | else: 236 | user_id = message.command[1] 237 | # don't want to make a request -_- 238 | user_first_name = user_id 239 | try: 240 | user_id = int(user_id) 241 | except ValueError: 242 | pass 243 | else: 244 | user_id = message.from_user.id 245 | user_first_name = message.from_user.first_name 246 | return (user_id, user_first_name) 247 | 248 | def list_to_str(k): 249 | if not k: 250 | return "N/A" 251 | elif len(k) == 1: 252 | return str(k[0]) 253 | elif MAX_LIST_ELM: 254 | k = k[:int(MAX_LIST_ELM)] 255 | return ' '.join(f'{elem}, ' for elem in k) 256 | else: 257 | return ' '.join(f'{elem}, ' for elem in k) 258 | 259 | def last_online(from_user): 260 | time = "" 261 | if from_user.is_bot: 262 | time += "🤖 Bot :(" 263 | elif from_user.status == enums.UserStatus.RECENTLY: 264 | time += "Recently" 265 | elif from_user.status == enums.UserStatus.LAST_WEEK: 266 | time += "Within the last week" 267 | elif from_user.status == enums.UserStatus.LAST_MONTH: 268 | time += "Within the last month" 269 | elif from_user.status == enums.UserStatus.LONG_AGO: 270 | time += "A long time ago :(" 271 | elif from_user.status == enums.UserStatus.ONLINE: 272 | time += "Currently Online" 273 | elif from_user.status == enums.UserStatus.OFFLINE: 274 | time += from_user.last_online_date.strftime("%a, %d %b %Y, %H:%M:%S") 275 | return time 276 | 277 | 278 | def split_quotes(text: str) -> List: 279 | if not any(text.startswith(char) for char in START_CHAR): 280 | return text.split(None, 1) 281 | counter = 1 # ignore first char -> is some kind of quote 282 | while counter < len(text): 283 | if text[counter] == "\\": 284 | counter += 1 285 | elif text[counter] == text[0] or (text[0] == SMART_OPEN and text[counter] == SMART_CLOSE): 286 | break 287 | counter += 1 288 | else: 289 | return text.split(None, 1) 290 | 291 | # 1 to avoid starting quote, and counter is exclusive so avoids ending 292 | key = remove_escapes(text[1:counter].strip()) 293 | # index will be in range, or `else` would have been executed and returned 294 | rest = text[counter + 1:].strip() 295 | if not key: 296 | key = text[0] + text[0] 297 | return list(filter(None, [key, rest])) 298 | 299 | def gfilterparser(text, keyword): 300 | if "buttonalert" in text: 301 | text = (text.replace("\n", "\\n").replace("\t", "\\t")) 302 | buttons = [] 303 | note_data = "" 304 | prev = 0 305 | i = 0 306 | alerts = [] 307 | for match in BTN_URL_REGEX.finditer(text): 308 | # Check if btnurl is escaped 309 | n_escapes = 0 310 | to_check = match.start(1) - 1 311 | while to_check > 0 and text[to_check] == "\\": 312 | n_escapes += 1 313 | to_check -= 1 314 | 315 | # if even, not escaped -> create button 316 | if n_escapes % 2 == 0: 317 | note_data += text[prev:match.start(1)] 318 | prev = match.end(1) 319 | if match.group(3) == "buttonalert": 320 | # create a thruple with button label, url, and newline status 321 | if bool(match.group(5)) and buttons: 322 | buttons[-1].append(InlineKeyboardButton( 323 | text=match.group(2), 324 | callback_data=f"gfilteralert:{i}:{keyword}" 325 | )) 326 | else: 327 | buttons.append([InlineKeyboardButton( 328 | text=match.group(2), 329 | callback_data=f"gfilteralert:{i}:{keyword}" 330 | )]) 331 | i += 1 332 | alerts.append(match.group(4)) 333 | elif bool(match.group(5)) and buttons: 334 | buttons[-1].append(InlineKeyboardButton( 335 | text=match.group(2), 336 | url=match.group(4).replace(" ", "") 337 | )) 338 | else: 339 | buttons.append([InlineKeyboardButton( 340 | text=match.group(2), 341 | url=match.group(4).replace(" ", "") 342 | )]) 343 | 344 | else: 345 | note_data += text[prev:to_check] 346 | prev = match.start(1) - 1 347 | else: 348 | note_data += text[prev:] 349 | 350 | try: 351 | return note_data, buttons, alerts 352 | except: 353 | return note_data, buttons, None 354 | 355 | def parser(text, keyword): 356 | if "buttonalert" in text: 357 | text = (text.replace("\n", "\\n").replace("\t", "\\t")) 358 | buttons = [] 359 | note_data = "" 360 | prev = 0 361 | i = 0 362 | alerts = [] 363 | for match in BTN_URL_REGEX.finditer(text): 364 | # Check if btnurl is escaped 365 | n_escapes = 0 366 | to_check = match.start(1) - 1 367 | while to_check > 0 and text[to_check] == "\\": 368 | n_escapes += 1 369 | to_check -= 1 370 | 371 | # if even, not escaped -> create button 372 | if n_escapes % 2 == 0: 373 | note_data += text[prev:match.start(1)] 374 | prev = match.end(1) 375 | if match.group(3) == "buttonalert": 376 | # create a thruple with button label, url, and newline status 377 | if bool(match.group(5)) and buttons: 378 | buttons[-1].append(InlineKeyboardButton( 379 | text=match.group(2), 380 | callback_data=f"alertmessage:{i}:{keyword}" 381 | )) 382 | else: 383 | buttons.append([InlineKeyboardButton( 384 | text=match.group(2), 385 | callback_data=f"alertmessage:{i}:{keyword}" 386 | )]) 387 | i += 1 388 | alerts.append(match.group(4)) 389 | elif bool(match.group(5)) and buttons: 390 | buttons[-1].append(InlineKeyboardButton( 391 | text=match.group(2), 392 | url=match.group(4).replace(" ", "") 393 | )) 394 | else: 395 | buttons.append([InlineKeyboardButton( 396 | text=match.group(2), 397 | url=match.group(4).replace(" ", "") 398 | )]) 399 | 400 | else: 401 | note_data += text[prev:to_check] 402 | prev = match.start(1) - 1 403 | else: 404 | note_data += text[prev:] 405 | 406 | try: 407 | return note_data, buttons, alerts 408 | except: 409 | return note_data, buttons, None 410 | 411 | def remove_escapes(text: str) -> str: 412 | res = "" 413 | is_escaped = False 414 | for counter in range(len(text)): 415 | if is_escaped: 416 | res += text[counter] 417 | is_escaped = False 418 | elif text[counter] == "\\": 419 | is_escaped = True 420 | else: 421 | res += text[counter] 422 | return res 423 | 424 | 425 | def humanbytes(size): 426 | if not size: 427 | return "" 428 | power = 2**10 429 | n = 0 430 | Dic_powerN = {0: ' ', 1: 'Ki', 2: 'Mi', 3: 'Gi', 4: 'Ti'} 431 | while size > power: 432 | size /= power 433 | n += 1 434 | return str(round(size, 2)) + " " + Dic_powerN[n] + 'B' 435 | 436 | async def get_shortlink(chat_id, link): 437 | settings = await get_settings(chat_id) #fetching settings for group 438 | if 'shortlink' in settings.keys(): 439 | URL = settings['shortlink'] 440 | else: 441 | URL = SHORTLINK_URL 442 | if 'shortlink_api' in settings.keys(): 443 | API = settings['shortlink_api'] 444 | else: 445 | API = SHORTLINK_API 446 | https = link.split(":")[0] #splitting https or http from link 447 | if "http" == https: #if https == "http": 448 | https = "https" 449 | link = link.replace("http", https) #replacing http to https 450 | if URL == "api.shareus.io": 451 | url = f'https://{URL}/directLink' 452 | params = { 453 | "token": API, 454 | "format": "json", 455 | "link": link, 456 | } 457 | try: 458 | async with aiohttp.ClientSession() as session: 459 | async with session.get(url, params=params, raise_for_status=True, ssl=False) as response: 460 | data = await response.json(content_type="text/html") 461 | if data["status"] == "success": 462 | return data["shortlink"] 463 | else: 464 | logger.error(f"Error: {data['message']}") 465 | return f'https://{URL}/directLink?token={API}&format=json&link={link}' 466 | except Exception as e: 467 | logger.error(e) 468 | return f'https://{URL}/directLink?token={API}&format=json&link={link}' 469 | else: 470 | url = f'https://{URL}/api' 471 | params = { 472 | "api": API, 473 | "url": link, 474 | } 475 | try: 476 | async with aiohttp.ClientSession() as session: 477 | async with session.get(url, params=params, raise_for_status=True, ssl=False) as response: 478 | data = await response.json() 479 | if data["status"] == "success": 480 | return data["shortenedUrl"] 481 | else: 482 | logger.error(f"Error: {data['message']}") 483 | return f'https://{URL}/api?api={API}&link={link}' 484 | except Exception as e: 485 | logger.error(e) 486 | return f'https://{URL}/api?api={API}&link={link}' 487 | --------------------------------------------------------------------------------