├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── Script.py
├── app.json
├── bot.py
├── database
├── connections_mdb.py
├── filters_mdb.py
├── ia_filterdb.py
└── users_chats_db.py
├── heroku.yml
├── info.py
├── logging.conf
├── plugins
├── banned.py
├── broadcast.py
├── channel.py
├── commands.py
├── connection.py
├── filters.py
├── genlink.py
├── index.py
├── inline.py
├── misc.py
├── p_ttishow.py
└── pm_filter.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 /EvaMaria
10 | WORKDIR /EvaMaria
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 |
2 |
52 |
62 |
3 |
5 | file-filter-bot
6 |
7 |
8 |
9 |
10 | [](https://github.com/malik7983/file-filter-bot/stargazers)
11 | [](https://github.com/malik7983/file-filter-bot/fork)
12 | [](https://github.com/malik7983/file-filter-bot)
13 | [](https://github.com/malik7983/file-filter-bot)
14 | ## Features
15 |
16 | - [x] Auto Filter
17 | - [x] Manual Filter
18 | - [x] IMDB
19 | - [x] Admin Commands
20 | - [x] Broadcast
21 | - [x] Index
22 | - [x] IMDB search
23 | - [x] Inline Search
24 | - [x] Random pics
25 | - [x] ids and User info
26 | - [x] Stats, Users, Chats, Ban, Unban, Leave, Disable, Channel
27 | - [x] Spelling Check Feature
28 |
29 | ## Variables
30 |
31 | ### Required Variables
32 | * `BOT_TOKEN`: Create a bot using [@BotFather](https://telegram.dog/BotFather), and get the Telegram API token.
33 | * `API_ID`: Get this value from [telegram.org](https://my.telegram.org/apps)
34 | * `API_HASH`: Get this value from [telegram.org](https://my.telegram.org/apps)
35 | * `CHANNELS`: Username or ID of channel or group. Separate multiple IDs by space
36 | * `ADMINS`: Username or ID of Admin. Separate multiple Admins by space
37 | * `DATABASE_URI`: [mongoDB](https://www.mongodb.com) URI. Get this value from [mongoDB](https://www.mongodb.com).
38 | * `DATABASE_NAME`: Name of the database in [mongoDB](https://www.mongodb.com). For more help watch this
39 | * `LOG_CHANNEL` : A channel to log the activities of bot. Make sure bot is an admin in the channel.
40 | ### Optional Variables
41 | * `PICS`: Telegraph links of images to show in start message.( Multiple images can be used seperated by space )
42 |
43 |
44 | ## Deploy
45 | You can deploy this bot anywhere.
46 |
47 | **[HOW TO DEPLOY WTCH THIS VIDEO...](https://youtu.be/v7Vbu3u_VrE)**
48 |
49 |
50 |
Deploy To Heroku
51 |
53 |
54 |
55 |
56 |
57 |
Deploy To VPS
61 |
63 | git clone https://github.com/Aadhi000/Ajax
64 | # Install Packages
65 | pip3 install -r requirements.txt
66 | Edit info.py with variables as given below then run bot
67 | python3 bot.py
68 |
69 |
add a filter in chat
30 | • /filters - list all the filters of a chat
31 | • /del - delete a specific filter in chat
32 | • /delall - delete the whole filters in a chat (chat owner only)
"""
33 | BUTTON_TXT = """Help: Buttons
34 |
35 | - movies house Supports both url and alert inline buttons.
36 |
37 | NOTE:
38 | 1. Telegram will not allows you to send buttons without any content, so content is mandatory.
39 | 2. movies house supports buttons with any telegram media type.
40 | 3. Buttons should be properly parsed as markdown format
41 |
42 | URL buttons:
43 | [Button Text](buttonurl:https://t.me/sahid_malik)
44 |
45 | Alert buttons:
46 | [Button Text](buttonalert:This is an alert message)
"""
47 | AUTOFILTER_TXT = """Help: Auto Filter
48 |
49 | NOTE:
50 | 1. Make me the admin of your channel if it's private.
51 | 2. make sure that your channel does not contains camrips, porn and fake files.
52 | 3. Forward the last message to me with quotes.
53 | I'll add all the files in that channel to my db."""
54 | CONNECTION_TXT = """Help: Connections
55 |
56 | - Used to connect bot to PM for managing filters
57 | - it helps to avoid spamming in groups.
58 |
59 | NOTE:
60 | 1. Only admins can add a connection.
61 | 2. Send /connect
for connecting me to ur PM
62 |
63 | Commands and Usage:
64 | • /connect - connect a particular chat to your PM
65 | • /disconnect - disconnect from a chat
66 | • /connections - list all your connections
"""
67 | EXTRAMOD_TXT = """Help: Extra Modules
68 |
69 | NOTE:
70 | these are the extra features of Eva Maria
71 |
72 | Commands and Usage:
73 | • /id - get id of a specified user.
74 | • /info - get information about a user.
75 | • /imdb - get the film information from IMDb source.
76 | • /search - get the film information from various sources.
"""
77 | ADMIN_TXT = """Help: Admin mods
78 |
79 | NOTE:
80 | This module only works for my admins
81 |
82 | Commands and Usage:
83 | • /logs - to get the rescent errors
84 | • /stats - to get status of files in db.
85 | • /delete - to delete a specific file from db.
86 | • /users - to get list of my users and ids.
87 | • /chats - to get list of the my chats and ids
88 | • /leave - to leave from a chat.
89 | • /disable - do disable a chat.
90 | • /ban - to ban a user.
91 | • /unban - to unban a user.
92 | • /channel - to get list of total connected channels
93 | • /broadcast - to broadcast a message to all users
"""
94 | STATUS_TXT = """★ 𝚃𝙾𝚃𝙰𝙻 𝙵𝙸𝙻𝙴𝚂: {}
95 | ★ 𝚃𝙾𝚃𝙰𝙻 𝚄𝚂𝙴𝚁𝚂: {}
96 | ★ 𝚃𝙾𝚃𝙰𝙻 𝙲𝙷𝙰𝚃𝚂: {}
97 | ★ 𝚄𝚂𝙴𝙳 𝚂𝚃𝙾𝚁𝙰𝙶𝙴: {}
𝙼𝚒𝙱
98 | ★ 𝙵𝚁𝙴𝙴 𝚂𝚃𝙾𝚁𝙰𝙶𝙴: {}
𝙼𝚒𝙱
99 | ★ 𝙲𝚁𝙴𝙰𝚃𝙾𝚁: Sahid malik """
100 | LOG_TEXT_G = """#NewGroup
101 | Group = {}({}
)
102 | Total Members = {}
103 | Added By - {}
104 | """
105 | LOG_TEXT_P = """#NewUser
106 | ID - {}
107 | Name - {}
108 | """
109 |
110 | START_TXT = """Hay {},
111 |
112 | I'm ⚡️ Powerful Auto-Filter Bot...
113 | 😎 You Can Use Me As A Auto-filter in Your Group ....
114 | Its Easy To Use Me; Just Add Me To Your Group As Admin, Thats All, i will Provide Movies There...😎
115 | ⚠️ More Help Check Help Button Below
116 |
117 | ©️Mantained Bʏ @sahid_malik"""
118 |
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "file-filter-bot",
3 | "description": "When you going to send file on telegram channel this bot will save that in database, So you can search that easily in inline mode",
4 | "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://github.com/malik7983/file-filter-bot",
19 | "repository": "https://github.com/Maliksahid786/file-filter-botv5",
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 | "SINGLE_BUTTON": {
71 | "description": "choose b/w single or double buttons",
72 | "value": "True",
73 | "required": false
74 | },
75 | "P_TTI_SHOW_OFF": {
76 | "description": "Customize Result Buttons to Callback or Url by (True = url / False = callback)",
77 | "value": "True",
78 | "required": false
79 | },
80 | "SUPPORT_CHAT": {
81 | "description": "Username of a Support Group / ADMIN. ( Should be username without @ and not ID)",
82 | "value": "m_house786",
83 | "required": false
84 | }
85 | },
86 | "addons": [],
87 | "buildpacks": [{
88 | "url": "heroku/python"
89 | }],
90 | "formation": {
91 | "worker": {
92 | "quantity": 1,
93 | "size": "free"
94 | }
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/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
15 | from utils import temp
16 |
17 | class Bot(Client):
18 |
19 | def __init__(self):
20 | super().__init__(
21 | session_name=SESSION,
22 | api_id=API_ID,
23 | api_hash=API_HASH,
24 | bot_token=BOT_TOKEN,
25 | workers=50,
26 | plugins={"root": "plugins"},
27 | sleep_threshold=5,
28 | )
29 |
30 | async def start(self):
31 | b_users, b_chats = await db.get_banned()
32 | temp.BANNED_USERS = b_users
33 | temp.BANNED_CHATS = b_chats
34 | await super().start()
35 | await Media.ensure_indexes()
36 | me = await self.get_me()
37 | temp.ME = me.id
38 | temp.U_NAME = me.username
39 | temp.B_NAME = me.first_name
40 | self.username = '@' + me.username
41 | logging.info(f"{me.first_name} with for Pyrogram v{__version__} (Layer {layer}) started on {me.username}.")
42 | logging.info(LOG_STR)
43 |
44 | async def stop(self, *args):
45 | await super().stop()
46 | logging.info("Bot stopped. Bye.")
47 |
48 |
49 | app = Bot()
50 | app.run()
51 |
--------------------------------------------------------------------------------
/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 | import logging
4 | logger = logging.getLogger(__name__)
5 | logger.setLevel(logging.ERROR)
6 |
7 | myclient = pymongo.MongoClient(DATABASE_URI)
8 | mydb = myclient[DATABASE_NAME]
9 |
10 |
11 |
12 | async def add_filter(grp_id, text, reply_text, btn, file, alert):
13 | mycol = mydb[str(grp_id)]
14 | # mycol.create_index([('text', 'text')])
15 |
16 | data = {
17 | 'text':str(text),
18 | 'reply':str(reply_text),
19 | 'btn':str(btn),
20 | 'file':str(file),
21 | 'alert':str(alert)
22 | }
23 |
24 | try:
25 | mycol.update_one({'text': str(text)}, {"$set": data}, upsert=True)
26 | except:
27 | logger.exception('Some error occured!', exc_info=True)
28 |
29 |
30 | async def find_filter(group_id, name):
31 | mycol = mydb[str(group_id)]
32 |
33 | query = mycol.find( {"text":name})
34 | # query = mycol.find( { "$text": {"$search": name}})
35 | try:
36 | for file in query:
37 | reply_text = file['reply']
38 | btn = file['btn']
39 | fileid = file['file']
40 | try:
41 | alert = file['alert']
42 | except:
43 | alert = None
44 | return reply_text, btn, alert, fileid
45 | except:
46 | return None, None, None, None
47 |
48 |
49 | async def get_filters(group_id):
50 | mycol = mydb[str(group_id)]
51 |
52 | texts = []
53 | query = mycol.find()
54 | try:
55 | for file in query:
56 | text = file['text']
57 | texts.append(text)
58 | except:
59 | pass
60 | return texts
61 |
62 |
63 | async def delete_filter(message, text, group_id):
64 | mycol = mydb[str(group_id)]
65 |
66 | myquery = {'text':text }
67 | query = mycol.count_documents(myquery)
68 | if query == 1:
69 | mycol.delete_one(myquery)
70 | await message.reply_text(
71 | f"'`{text}`' deleted. I'll not respond to that filter anymore.",
72 | quote=True,
73 | parse_mode="md"
74 | )
75 | else:
76 | await message.reply_text("Couldn't find that filter!", quote=True)
77 |
78 |
79 | async def del_all(message, group_id, title):
80 | if str(group_id) not in mydb.list_collection_names():
81 | await message.edit_text(f"Nothing to remove in {title}!")
82 | return
83 |
84 | mycol = mydb[str(group_id)]
85 | try:
86 | mycol.drop()
87 | await message.edit_text(f"All filters from {title} has been removed")
88 | except:
89 | await message.edit_text("Couldn't remove all filters from group!")
90 | return
91 |
92 |
93 | async def count_filters(group_id):
94 | mycol = mydb[str(group_id)]
95 |
96 | count = mycol.count()
97 | return False if count == 0 else count
98 |
99 |
100 | async def filter_stats():
101 | collections = mydb.list_collection_names()
102 |
103 | if "CONNECTION" in collections:
104 | collections.remove("CONNECTION")
105 |
106 | totalcount = 0
107 | for collection in collections:
108 | mycol = mydb[collection]
109 | count = mycol.count()
110 | totalcount += count
111 |
112 | totalcollections = len(collections)
113 |
114 | return totalcollections, totalcount
115 |
--------------------------------------------------------------------------------
/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
11 |
12 | logger = logging.getLogger(__name__)
13 | logger.setLevel(logging.INFO)
14 |
15 |
16 | client = AsyncIOMotorClient(DATABASE_URI)
17 | db = client[DATABASE_NAME]
18 | instance = Instance.from_db(db)
19 |
20 | @instance.register
21 | class Media(Document):
22 | file_id = fields.StrField(attribute='_id')
23 | file_ref = fields.StrField(allow_none=True)
24 | file_name = fields.StrField(required=True)
25 | file_size = fields.IntField(required=True)
26 | file_type = fields.StrField(allow_none=True)
27 | mime_type = fields.StrField(allow_none=True)
28 | caption = fields.StrField(allow_none=True)
29 |
30 | class Meta:
31 | indexes = ('$file_name', )
32 | collection_name = COLLECTION_NAME
33 |
34 |
35 | async def save_file(media):
36 | """Save file in database"""
37 |
38 | # TODO: Find better way to get same file_id for same media to avoid duplicates
39 | file_id, file_ref = unpack_new_file_id(media.file_id)
40 | file_name = re.sub(r"(_|\-|\.|\+)", " ", str(media.file_name))
41 | try:
42 | file = Media(
43 | file_id=file_id,
44 | file_ref=file_ref,
45 | file_name=file_name,
46 | file_size=media.file_size,
47 | file_type=media.file_type,
48 | mime_type=media.mime_type,
49 | caption=media.caption.html if media.caption else None,
50 | )
51 | except ValidationError:
52 | logger.exception('Error occurred while saving file in database')
53 | return False, 2
54 | else:
55 | try:
56 | await file.commit()
57 | except DuplicateKeyError:
58 | logger.warning(
59 | f'{getattr(media, "file_name", "NO_FILE")} is already saved in database'
60 | )
61 |
62 | return False, 0
63 | else:
64 | logger.info(f'{getattr(media, "file_name", "NO_FILE")} is saved to database')
65 | return True, 1
66 |
67 |
68 |
69 | async def get_search_results(query, file_type=None, max_results=10, offset=0, filter=False):
70 | """For given query return (results, next_offset)"""
71 |
72 | query = query.strip()
73 | #if filter:
74 | #better ?
75 | #query = query.replace(' ', r'(\s|\.|\+|\-|_)')
76 | #raw_pattern = r'(\s|_|\-|\.|\+)' + query + r'(\s|_|\-|\.|\+)'
77 | if not query:
78 | raw_pattern = '.'
79 | elif ' ' not in query:
80 | raw_pattern = r'(\b|[\.\+\-_])' + query + r'(\b|[\.\+\-_])'
81 | else:
82 | raw_pattern = query.replace(' ', r'.*[\s\.\+\-_]')
83 |
84 | try:
85 | regex = re.compile(raw_pattern, flags=re.IGNORECASE)
86 | except:
87 | return []
88 |
89 | if USE_CAPTION_FILTER:
90 | filter = {'$or': [{'file_name': regex}, {'caption': regex}]}
91 | else:
92 | filter = {'file_name': regex}
93 |
94 | if file_type:
95 | filter['file_type'] = file_type
96 |
97 | total_results = await Media.count_documents(filter)
98 | next_offset = offset + max_results
99 |
100 | if next_offset > total_results:
101 | next_offset = ''
102 |
103 | cursor = Media.find(filter)
104 | # Sort by recent
105 | cursor.sort('$natural', -1)
106 | # Slice files according to offset and max results
107 | cursor.skip(offset).limit(max_results)
108 | # Get list of files
109 | files = await cursor.to_list(length=max_results)
110 |
111 | return files, next_offset, total_results
112 |
113 |
114 |
115 | async def get_file_details(query):
116 | filter = {'file_id': query}
117 | cursor = Media.find(filter)
118 | filedetails = await cursor.to_list(length=1)
119 | return filedetails
120 |
121 |
122 | def encode_file_id(s: bytes) -> str:
123 | r = b""
124 | n = 0
125 |
126 | for i in s + bytes([22]) + bytes([4]):
127 | if i == 0:
128 | n += 1
129 | else:
130 | if n:
131 | r += b"\x00" + bytes([n])
132 | n = 0
133 |
134 | r += bytes([i])
135 |
136 | return base64.urlsafe_b64encode(r).decode().rstrip("=")
137 |
138 |
139 | def encode_file_ref(file_ref: bytes) -> str:
140 | return base64.urlsafe_b64encode(file_ref).decode().rstrip("=")
141 |
142 |
143 | def unpack_new_file_id(new_file_id):
144 | """Return file_id, file_ref"""
145 | decoded = FileId.decode(new_file_id)
146 | file_id = encode_file_id(
147 | pack(
148 | "{vazha['reason']}
.",
34 | reply_markup=reply_markup)
35 | try:
36 | await k.pin()
37 | except:
38 | pass
39 | await bot.leave_chat(message.chat.id)
40 |
--------------------------------------------------------------------------------
/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}")
--------------------------------------------------------------------------------
/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
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
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
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 & ~filters.edited)
22 | async def start(client, message):
23 | if message.chat.type in ['group', 'supergroup']:
24 | buttons = [
25 | [
26 | InlineKeyboardButton('❇️ Add Me To Your Groups ❇️', url=f'http://t.me/{temp.U_NAME}?startgroup=true')
27 | ],
28 | [
29 | InlineKeyboardButton('♻️ Updates Channel ♻️', url='https://t.me/m_house786')
30 | ],
31 | [
32 | InlineKeyboardButton('❇️ Help ❇️', url=f"https://t.me/{temp.U_NAME}?start=help"),
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 ❇️', url=f'http://t.me/{temp.U_NAME}?startgroup=true')
49 | ],[
50 | InlineKeyboardButton('💠 CHANNEL 💠', url='https://t.me/+ZeZNvt43B4o3ZmJl'),
51 | InlineKeyboardButton('☎️CONTACT ME', url='https://t.me/sahid_malik'),
52 | InlineKeyboardButton('💠 UPDATES 💠', url='https://t.me/m_house786')
53 | ],[
54 | InlineKeyboardButton('♻️ Help ♻️', callback_data='help'),
55 | InlineKeyboardButton('🌷Join my group', url='https://t.me/+gXuMKXOWm1UyOTdl'),
56 | InlineKeyboardButton('♻️ About ♻️', callback_data='about')
57 | ],[
58 | InlineKeyboardButton('✅ Subscribe my YouTube channel ✅', url='https://youtube.com/channel/UCPaHDqWf3D3w2nxb8p3sr4A')
59 | ]]
60 | reply_markup = InlineKeyboardMarkup(buttons)
61 | await message.reply_photo(
62 | photo=random.choice(PICS),
63 | caption=script.START_TXT.format(message.from_user.mention, temp.U_NAME, temp.B_NAME),
64 | reply_markup=reply_markup,
65 | parse_mode='html'
66 | )
67 | return
68 | if AUTH_CHANNEL and not await is_subscribed(client, message):
69 | try:
70 | invite_link = await client.create_chat_invite_link(int(AUTH_CHANNEL))
71 | except ChatAdminRequired:
72 | logger.error("Make sure Bot is admin in Forcesub channel")
73 | return
74 | btn = [
75 | [
76 | InlineKeyboardButton(
77 | "👉 Join Updates Channel 👈", url=invite_link.invite_link
78 | )
79 | ]
80 | ]
81 |
82 | if message.command[1] != "subscribe":
83 | try:
84 | kk, file_id = message.command[1].split("_", 1)
85 | pre = 'checksubp' if kk == 'filep' else 'checksub'
86 | btn.append([InlineKeyboardButton(" ♻️ Try Again ♻️", callback_data=f"{pre}#{file_id}")])
87 | except IndexError:
88 | btn.append([InlineKeyboardButton(" ♻️ Try Again ♻️", url=f"https://t.me/{temp.U_NAME}/{message.command[1]}")])
89 | await client.send_message(
90 | chat_id=message.from_user.id,
91 | text="**⚠️ Please Join My Updates Channel to use this Bot... ━━━━━━━━━━━━━━━━━ हमारे निचे दिए गये update चैनल को join करे जब तक आप हमारे update चैनल को join नहीं करेंगे तब तक bot आपको मूवी नहीं देगा. 👇👇👇 **",
92 | reply_markup=InlineKeyboardMarkup(btn),
93 | parse_mode="markdown"
94 | )
95 | return
96 | if len(message.command) == 2 and message.command[1] in ["subscribe", "error", "okay", "help"]:
97 | buttons = [[
98 | InlineKeyboardButton('✳️ Add Me To Your Groups ✳️', url=f'http://t.me/{temp.U_NAME}?startgroup=true')
99 | ],[
100 | InlineKeyboardButton('💠 CHANNEL 💠', url='https://t.me/+ZeZNvt43B4o3ZmJl'),
101 | InlineKeyboardButton('☎️ CONTACT ME', url='https://t.me/sahid_malik'),
102 | InlineKeyboardButton('💠 UPDATES 💠', url='https://t.me/m_house786')
103 | ],[
104 | InlineKeyboardButton('♻️ HΞLᎮ ♻️', callback_data='help'),
105 | InlineKeyboardButton('🌷Join my group', url='https://t.me/+gXuMKXOWm1UyOTdl'),
106 | InlineKeyboardButton('♻️ ΛBOUT ♻️', callback_data='about')
107 | ],[
108 | InlineKeyboardButton('✅ Subscribe my YouTube channel ✅', url='https://youtube.com/channel/UCPaHDqWf3D3w2nxb8p3sr4A')
109 | ]]
110 | reply_markup = InlineKeyboardMarkup(buttons)
111 | await message.reply_photo(
112 | photo=random.choice(PICS),
113 | caption=script.START_TXT.format(message.from_user.mention, temp.U_NAME, temp.B_NAME),
114 | reply_markup=reply_markup,
115 | parse_mode='html'
116 | )
117 | return
118 | data = message.command[1]
119 | try:
120 | pre, file_id = data.split('_', 1)
121 | except:
122 | file_id = data
123 | pre = ""
124 | if data.split("-", 1)[0] == "BATCH":
125 | sts = await message.reply("Please wait")
126 | file_id = data.split("-", 1)[1]
127 | msgs = BATCH_FILES.get(file_id)
128 | if not msgs:
129 | file = await client.download_media(file_id)
130 | try:
131 | with open(file) as file_data:
132 | msgs=json.loads(file_data.read())
133 | except:
134 | await sts.edit("FAILED")
135 | return await client.send_message(LOG_CHANNEL, "UNABLE TO OPEN FILE.")
136 | os.remove(file)
137 | BATCH_FILES[file_id] = msgs
138 | for msg in msgs:
139 | title = msg.get("title")
140 | size=get_size(int(msg.get("size", 0)))
141 | f_caption=msg.get("caption", "")
142 | if BATCH_FILE_CAPTION:
143 | try:
144 | 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)
145 | except Exception as e:
146 | logger.exception(e)
147 | f_caption=f_caption
148 | if f_caption is None:
149 | f_caption = f"{title}"
150 | try:
151 | await client.send_cached_media(
152 | chat_id=message.from_user.id,
153 | file_id=msg.get("file_id"),
154 | caption=f_caption,
155 | protect_content=msg.get('protect', False),
156 | )
157 | except FloodWait as e:
158 | await asyncio.sleep(e.x)
159 | logger.warning(f"Floodwait of {e.x} sec.")
160 | await client.send_cached_media(
161 | chat_id=message.from_user.id,
162 | file_id=msg.get("file_id"),
163 | caption=f_caption,
164 | protect_content=msg.get('protect', False),
165 | )
166 | except Exception as e:
167 | logger.warning(e, exc_info=True)
168 | continue
169 | await asyncio.sleep(1)
170 | await sts.delete()
171 | return
172 | elif data.split("-", 1)[0] == "DSTORE":
173 | sts = await message.reply("Please wait")
174 | b_string = data.split("-", 1)[1]
175 | decoded = (base64.urlsafe_b64decode(b_string + "=" * (-len(b_string) % 4))).decode("ascii")
176 | try:
177 | f_msg_id, l_msg_id, f_chat_id, protect = decoded.split("_", 3)
178 | except:
179 | f_msg_id, l_msg_id, f_chat_id = decoded.split("_", 2)
180 | protect = "/pbatch" if PROTECT_CONTENT else "batch"
181 | diff = int(l_msg_id) - int(f_msg_id)
182 | async for msg in client.iter_messages(int(f_chat_id), int(l_msg_id), int(f_msg_id)):
183 | if msg.media:
184 | media = getattr(msg, msg.media)
185 | if BATCH_FILE_CAPTION:
186 | try:
187 | f_caption=BATCH_FILE_CAPTION.format(file_name=getattr(media, 'file_name', ''), file_size=getattr(media, 'file_size', ''), file_caption=getattr(msg, 'caption', ''))
188 | except Exception as e:
189 | logger.exception(e)
190 | f_caption = getattr(msg, 'caption', '')
191 | else:
192 | media = getattr(msg, msg.media)
193 | file_name = getattr(media, 'file_name', '')
194 | f_caption = getattr(msg, 'caption', file_name)
195 | try:
196 | await msg.copy(message.chat.id, caption=f_caption, protect_content=True if protect == "/pbatch" else False)
197 | except FloodWait as e:
198 | await asyncio.sleep(e.x)
199 | await msg.copy(message.chat.id, caption=f_caption, protect_content=True if protect == "/pbatch" else False)
200 | except Exception as e:
201 | logger.exception(e)
202 | continue
203 | elif msg.empty:
204 | continue
205 | else:
206 | try:
207 | await msg.copy(message.chat.id, protect_content=True if protect == "/pbatch" else False)
208 | except FloodWait as e:
209 | await asyncio.sleep(e.x)
210 | await msg.copy(message.chat.id, protect_content=True if protect == "/pbatch" else False)
211 | except Exception as e:
212 | logger.exception(e)
213 | continue
214 | await asyncio.sleep(1)
215 | return await sts.delete()
216 |
217 |
218 | files_ = await get_file_details(file_id)
219 | if not files_:
220 | pre, file_id = ((base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))).decode("ascii")).split("_", 1)
221 | try:
222 | msg = await client.send_cached_media(
223 | chat_id=message.from_user.id,
224 | file_id=file_id,
225 | protect_content=True if pre == 'filep' else False,
226 | )
227 | filetype = msg.media
228 | file = getattr(msg, filetype)
229 | title = file.file_name
230 | size=get_size(file.file_size)
231 | f_caption = f"{title}
"
232 | if CUSTOM_FILE_CAPTION:
233 | try:
234 | f_caption=CUSTOM_FILE_CAPTION.format(file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='')
235 | except:
236 | return
237 | await msg.edit_caption(f_caption)
238 | return
239 | except:
240 | pass
241 | return await message.reply('No such file exist.')
242 | files = files_[0]
243 | title = files.file_name
244 | size=get_size(files.file_size)
245 | f_caption=files.caption
246 | if CUSTOM_FILE_CAPTION:
247 | try:
248 | 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)
249 | except Exception as e:
250 | logger.exception(e)
251 | f_caption=f_caption
252 | if f_caption is None:
253 | f_caption = f"{files.file_name}"
254 | await client.send_cached_media(
255 | chat_id=message.from_user.id,
256 | file_id=file_id,
257 | caption=f_caption,
258 | protect_content=True if pre == 'filep' else False,
259 | reply_markup=InlineKeyboardMarkup(
260 | [
261 | [
262 | InlineKeyboardButton('♻️ 𝐉𝐨𝐢𝐧 𝙂𝙧𝙤𝙪𝙥 ', url="https://t.me/+gXuMKXOWm1UyOTdl")
263 | ]
264 | ]
265 | )
266 | )
267 |
268 | @Client.on_message(filters.command('channel') & filters.user(ADMINS))
269 | async def channel_info(bot, message):
270 |
271 | """Send basic information of channel"""
272 | if isinstance(CHANNELS, (int, str)):
273 | channels = [CHANNELS]
274 | elif isinstance(CHANNELS, list):
275 | channels = CHANNELS
276 | else:
277 | raise ValueError("Unexpected type of CHANNELS")
278 |
279 | text = '📑 **Indexed channels/groups**\n'
280 | for channel in channels:
281 | chat = await bot.get_chat(channel)
282 | if chat.username:
283 | text += '\n@' + chat.username
284 | else:
285 | text += '\n' + chat.title or chat.first_name
286 |
287 | text += f'\n\n**Total:** {len(CHANNELS)}'
288 |
289 | if len(text) < 4096:
290 | await message.reply(text)
291 | else:
292 | file = 'Indexed channels.txt'
293 | with open(file, 'w') as f:
294 | f.write(text)
295 | await message.reply_document(file)
296 | os.remove(file)
297 |
298 |
299 | @Client.on_message(filters.command('logs') & filters.user(ADMINS))
300 | async def log_file(bot, message):
301 | """Send log file"""
302 | try:
303 | await message.reply_document('TelegramBot.log')
304 | except Exception as e:
305 | await message.reply(str(e))
306 |
307 | @Client.on_message(filters.command('delete') & filters.user(ADMINS))
308 | async def delete(bot, message):
309 | """Delete file from database"""
310 | reply = message.reply_to_message
311 | if reply and reply.media:
312 | msg = await message.reply("Processing...⏳", quote=True)
313 | else:
314 | await message.reply('Reply to file with /delete which you want to delete', quote=True)
315 | return
316 |
317 | for file_type in ("document", "video", "audio"):
318 | media = getattr(reply, file_type, None)
319 | if media is not None:
320 | break
321 | else:
322 | await msg.edit('This is not supported file format')
323 | return
324 |
325 | file_id, file_ref = unpack_new_file_id(media.file_id)
326 |
327 | result = await Media.collection.delete_one({
328 | '_id': file_id,
329 | })
330 | if result.deleted_count:
331 | await msg.edit('File is successfully deleted from database')
332 | else:
333 | file_name = re.sub(r"(_|\-|\.|\+)", " ", str(media.file_name))
334 | result = await Media.collection.delete_many({
335 | 'file_name': file_name,
336 | 'file_size': media.file_size,
337 | 'mime_type': media.mime_type
338 | })
339 | if result.deleted_count:
340 | await msg.edit('File is successfully deleted from database')
341 | else:
342 | # files indexed before https://github.com/EvamariaTG/EvaMaria/commit/f3d2a1bcb155faf44178e5d7a685a1b533e714bf#diff-86b613edf1748372103e94cacff3b578b36b698ef9c16817bb98fe9ef22fb669R39
343 | # have original file name.
344 | result = await Media.collection.delete_many({
345 | 'file_name': media.file_name,
346 | 'file_size': media.file_size,
347 | 'mime_type': media.mime_type
348 | })
349 | if result.deleted_count:
350 | await msg.edit('File is successfully deleted from database')
351 | else:
352 | await msg.edit('File not found in database')
353 |
354 |
355 | @Client.on_message(filters.command('deleteall') & filters.user(ADMINS))
356 | async def delete_all_index(bot, message):
357 | await message.reply_text(
358 | 'This will delete all indexed files.\nDo you want to continue??',
359 | reply_markup=InlineKeyboardMarkup(
360 | [
361 | [
362 | InlineKeyboardButton(
363 | text="YES", callback_data="autofilter_delete"
364 | )
365 | ],
366 | [
367 | InlineKeyboardButton(
368 | text="CANCEL", callback_data="close_data"
369 | )
370 | ],
371 | ]
372 | ),
373 | quote=True,
374 | )
375 |
376 |
377 | @Client.on_callback_query(filters.regex(r'^autofilter_delete'))
378 | async def delete_all_index_confirm(bot, message):
379 | await Media.collection.drop()
380 | await message.answer('Piracy Is Crime')
381 | await message.message.edit('Succesfully Deleted All The Indexed Files.')
382 |
383 |
384 | @Client.on_message(filters.command('settings'))
385 | async def settings(client, message):
386 | userid = message.from_user.id if message.from_user else None
387 | if not userid:
388 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
389 | chat_type = message.chat.type
390 |
391 | if chat_type == "private":
392 | grpid = await active_connection(str(userid))
393 | if grpid is not None:
394 | grp_id = grpid
395 | try:
396 | chat = await client.get_chat(grpid)
397 | title = chat.title
398 | except:
399 | await message.reply_text("Make sure I'm present in your group!!", quote=True)
400 | return
401 | else:
402 | await message.reply_text("I'm not connected to any groups!", quote=True)
403 | return
404 |
405 | elif chat_type in ["group", "supergroup"]:
406 | grp_id = message.chat.id
407 | title = message.chat.title
408 |
409 | else:
410 | return
411 |
412 | st = await client.get_chat_member(grp_id, userid)
413 | if (
414 | st.status != "administrator"
415 | and st.status != "creator"
416 | and str(userid) not in ADMINS
417 | ):
418 | return
419 |
420 | settings = await get_settings(grp_id)
421 |
422 | if settings is not None:
423 | buttons = [
424 | [
425 | InlineKeyboardButton(
426 | 'Filter Button',
427 | callback_data=f'setgs#button#{settings["button"]}#{grp_id}',
428 | ),
429 | InlineKeyboardButton(
430 | 'Single' if settings["button"] else 'Double',
431 | callback_data=f'setgs#button#{settings["button"]}#{grp_id}',
432 | ),
433 | ],
434 | [
435 | InlineKeyboardButton(
436 | 'Bot PM',
437 | callback_data=f'setgs#botpm#{settings["botpm"]}#{grp_id}',
438 | ),
439 | InlineKeyboardButton(
440 | '✅ Yes' if settings["botpm"] else '❌ No',
441 | callback_data=f'setgs#botpm#{settings["botpm"]}#{grp_id}',
442 | ),
443 | ],
444 | [
445 | InlineKeyboardButton(
446 | 'File Secure',
447 | callback_data=f'setgs#file_secure#{settings["file_secure"]}#{grp_id}',
448 | ),
449 | InlineKeyboardButton(
450 | '✅ Yes' if settings["file_secure"] else '❌ No',
451 | callback_data=f'setgs#file_secure#{settings["file_secure"]}#{grp_id}',
452 | ),
453 | ],
454 | [
455 | InlineKeyboardButton(
456 | 'IMDB',
457 | callback_data=f'setgs#imdb#{settings["imdb"]}#{grp_id}',
458 | ),
459 | InlineKeyboardButton(
460 | '✅ Yes' if settings["imdb"] else '❌ No',
461 | callback_data=f'setgs#imdb#{settings["imdb"]}#{grp_id}',
462 | ),
463 | ],
464 | [
465 | InlineKeyboardButton(
466 | 'Spell Check',
467 | callback_data=f'setgs#spell_check#{settings["spell_check"]}#{grp_id}',
468 | ),
469 | InlineKeyboardButton(
470 | '✅ Yes' if settings["spell_check"] else '❌ No',
471 | callback_data=f'setgs#spell_check#{settings["spell_check"]}#{grp_id}',
472 | ),
473 | ],
474 | [
475 | InlineKeyboardButton(
476 | 'Welcome',
477 | callback_data=f'setgs#welcome#{settings["welcome"]}#{grp_id}',
478 | ),
479 | InlineKeyboardButton(
480 | '✅ Yes' if settings["welcome"] else '❌ No',
481 | callback_data=f'setgs#welcome#{settings["welcome"]}#{grp_id}',
482 | ),
483 | ],
484 | ]
485 |
486 | reply_markup = InlineKeyboardMarkup(buttons)
487 |
488 | await message.reply_text(
489 | text=f"Change Your Settings for {title} As Your Wish ⚙",
490 | reply_markup=reply_markup,
491 | disable_web_page_preview=True,
492 | parse_mode="html",
493 | reply_to_message_id=message.message_id
494 | )
495 |
496 |
497 |
498 | @Client.on_message(filters.command('set_template'))
499 | async def save_template(client, message):
500 | sts = await message.reply("Checking template")
501 | userid = message.from_user.id if message.from_user else None
502 | if not userid:
503 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
504 | chat_type = message.chat.type
505 |
506 | if chat_type == "private":
507 | grpid = await active_connection(str(userid))
508 | if grpid is not None:
509 | grp_id = grpid
510 | try:
511 | chat = await client.get_chat(grpid)
512 | title = chat.title
513 | except:
514 | await message.reply_text("Make sure I'm present in your group!!", quote=True)
515 | return
516 | else:
517 | await message.reply_text("I'm not connected to any groups!", quote=True)
518 | return
519 |
520 | elif chat_type in ["group", "supergroup"]:
521 | grp_id = message.chat.id
522 | title = message.chat.title
523 |
524 | else:
525 | return
526 |
527 | st = await client.get_chat_member(grp_id, userid)
528 | if (
529 | st.status != "administrator"
530 | and st.status != "creator"
531 | and str(userid) not in ADMINS
532 | ):
533 | return
534 |
535 | if len(message.command) < 2:
536 | return await sts.edit("No Input!!")
537 | template = message.text.split(" ", 1)[1]
538 | await save_group_settings(grp_id, 'template', template)
539 | await sts.edit(f"Successfully changed template for {title} to\n\n{template}")
540 |
--------------------------------------------------------------------------------
/plugins/connection.py:
--------------------------------------------------------------------------------
1 | from pyrogram import filters, Client
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 == "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 ["group", "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 != "administrator"
37 | and st.status != "creator"
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 == "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="md"
62 | )
63 | if chat_type in ["group", "supergroup"]:
64 | await client.send_message(
65 | userid,
66 | f"Connected to **{title}** !",
67 | parse_mode="md"
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 == "private":
90 | await message.reply_text("Run /connections to view or disconnect from groups!", quote=True)
91 |
92 | elif chat_type in ["group", "supergroup"]:
93 | group_id = message.chat.id
94 |
95 | st = await client.get_chat_member(group_id, userid)
96 | if (
97 | st.status != "administrator"
98 | and st.status != "creator"
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/filters.py:
--------------------------------------------------------------------------------
1 | import io
2 | from pyrogram import filters, Client
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 == "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 ["group", "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 != "administrator"
48 | and st.status != "creator"
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="md"
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 == "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 ["group", "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 != "administrator"
151 | and st.status != "creator"
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="md"
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 == "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 ["group", "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 != "administrator"
213 | and st.status != "creator"
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 == "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 ["group", "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 == "creator") 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
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 ["video", 'audio', '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)).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://t.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://t.me/TeamEvamaria/10 https://t.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://t.me/TeamEvamaria/10 https://t.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://t.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)
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://t.me/{temp.U_NAME}?start=BATCH-{file_id}")
126 |
--------------------------------------------------------------------------------
/plugins/index.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import asyncio
3 | from pyrogram import Client, filters
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 == '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.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 ['audio', 'video', 'document']:
166 | unsupported += 1
167 | continue
168 | media = getattr(message, message.media, None)
169 | if not media:
170 | unsupported += 1
171 | continue
172 | media.file_type = message.media
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 |
9 | logger = logging.getLogger(__name__)
10 | cache_time = 0 if AUTH_USERS or AUTH_CHANNEL else CACHE_TIME
11 |
12 | async def inline_users(query: InlineQuery):
13 | if AUTH_USERS:
14 | if query.from_user and query.from_user.id in AUTH_USERS:
15 | return True
16 | else:
17 | return False
18 | if query.from_user and query.from_user.id not in temp.BANNED_USERS:
19 | return True
20 | return False
21 |
22 | @Client.on_inline_query()
23 | async def answer(bot, query):
24 | """Show search results for given inline query"""
25 |
26 | if not await inline_users(query):
27 | await query.answer(results=[],
28 | cache_time=0,
29 | switch_pm_text='okDa',
30 | switch_pm_parameter="hehe")
31 | return
32 |
33 | if AUTH_CHANNEL and not await is_subscribed(bot, query):
34 | await query.answer(results=[],
35 | cache_time=0,
36 | switch_pm_text='You have to subscribe my channel to use the bot',
37 | switch_pm_parameter="subscribe")
38 | return
39 |
40 | results = []
41 | if '|' in query.query:
42 | string, file_type = query.query.split('|', maxsplit=1)
43 | string = string.strip()
44 | file_type = file_type.strip().lower()
45 | else:
46 | string = query.query.strip()
47 | file_type = None
48 |
49 | offset = int(query.offset or 0)
50 | reply_markup = get_reply_markup(query=string)
51 | files, next_offset, total = await get_search_results(string,
52 | file_type=file_type,
53 | max_results=10,
54 | offset=offset)
55 |
56 | for file in files:
57 | title=file.file_name
58 | size=get_size(file.file_size)
59 | f_caption=file.caption
60 | if CUSTOM_FILE_CAPTION:
61 | try:
62 | 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)
63 | except Exception as e:
64 | logger.exception(e)
65 | f_caption=f_caption
66 | if f_caption is None:
67 | f_caption = f"{file.file_name}"
68 | results.append(
69 | InlineQueryResultCachedDocument(
70 | title=file.file_name,
71 | file_id=file.file_id,
72 | caption=f_caption,
73 | description=f'Size: {get_size(file.file_size)}\nType: {file.file_type}',
74 | reply_markup=reply_markup))
75 |
76 | if results:
77 | switch_pm_text = f"{emoji.FILE_FOLDER} Results - {total}"
78 | if string:
79 | switch_pm_text += f" for {string}"
80 | try:
81 | await query.answer(results=results,
82 | is_personal = True,
83 | cache_time=cache_time,
84 | switch_pm_text=switch_pm_text,
85 | switch_pm_parameter="start",
86 | next_offset=str(next_offset))
87 | except QueryIdInvalid:
88 | pass
89 | except Exception as e:
90 | logging.exception(str(e))
91 | else:
92 | switch_pm_text = f'{emoji.CROSS_MARK} No results'
93 | if string:
94 | switch_pm_text += f' for "{string}"'
95 |
96 | await query.answer(results=[],
97 | is_personal = True,
98 | cache_time=cache_time,
99 | switch_pm_text=switch_pm_text,
100 | switch_pm_parameter="okay")
101 |
102 |
103 | def get_reply_markup(query):
104 | buttons = [
105 | [
106 | InlineKeyboardButton('Search again', switch_inline_query_current_chat=query)
107 | ]
108 | ]
109 | return InlineKeyboardMarkup(buttons)
110 |
111 |
112 |
113 |
114 |
--------------------------------------------------------------------------------
/plugins/misc.py:
--------------------------------------------------------------------------------
1 | import os
2 | from pyrogram import Client, filters
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 == "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 ["group", "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 (("supergroup", "channel")):
86 | try:
87 | chat_member_p = await message.chat.get_member(from_user.id)
88 | joined_date = datetime.fromtimestamp(
89 | chat_member_p.joined_date or time.time()
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="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="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
2 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
3 | from pyrogram.errors.exceptions.bad_request_400 import MessageTooLong, PeerIdInvalid
4 | from info import ADMINS, LOG_CHANNEL, SUPPORT_CHAT, MELCOW_NEW_USERS
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 |
11 | """-----------------------------------------https://t.me/GetTGLink/4179 --------------------------------------"""
12 |
13 | @Client.on_message(filters.new_chat_members & filters.group)
14 | async def save_group(bot, message):
15 | r_j_check = [u.id for u in message.new_chat_members]
16 | if temp.ME in r_j_check:
17 | if not await db.get_chat(message.chat.id):
18 | total=await bot.get_chat_members_count(message.chat.id)
19 | r_j = message.from_user.mention if message.from_user else "Anonymous"
20 | await bot.send_message(LOG_CHANNEL, script.LOG_TEXT_G.format(message.chat.title, message.chat.id, total, r_j))
21 | await db.add_chat(message.chat.id, message.chat.title)
22 | if message.chat.id in temp.BANNED_CHATS:
23 | # Inspired from a boat of a banana tree
24 | buttons = [[
25 | InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}')
26 | ]]
27 | reply_markup=InlineKeyboardMarkup(buttons)
28 | k = await message.reply(
29 | text='CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it Contact support..',
30 | reply_markup=reply_markup,
31 | )
32 |
33 | try:
34 | await k.pin()
35 | except:
36 | pass
37 | await bot.leave_chat(message.chat.id)
38 | return
39 | buttons = [[
40 | InlineKeyboardButton('♻️ HΞLᎮ ♻️', url=f"https://t.me/{temp.U_NAME}?start=help"),
41 | InlineKeyboardButton('💎 Updates 💎', url='https://t.me/m_house786')
42 | ],[
43 | InlineKeyboardButton('🌴 Bots Channel 🌴', url='https://t.me/malik_bots')
44 | ]]
45 | reply_markup=InlineKeyboardMarkup(buttons)
46 | await message.reply_text(
47 | text=f"Thankyou For Adding Me In {message.chat.title} ❣️\n\nIf you have any questions & doubts about using me Contact Owner >> @sahid_malik.",
48 | reply_markup=reply_markup)
49 | else:
50 | settings = await get_settings(message.chat.id)
51 | if settings["welcome"]:
52 | for u in message.new_chat_members:
53 | if (temp.MELCOW).get('welcome') is not None:
54 | try:
55 | await (temp.MELCOW['welcome']).delete()
56 | except:
57 | pass
58 | temp.MELCOW['welcome'] = await message.reply(f"Hey , {u.mention}, Welcome to {message.chat.title}")
59 |
60 |
61 | @Client.on_message(filters.command('leave') & filters.user(ADMINS))
62 | async def leave_a_chat(bot, message):
63 | if len(message.command) == 1:
64 | return await message.reply('Give me a chat id')
65 | chat = message.command[1]
66 | try:
67 | chat = int(chat)
68 | except:
69 | chat = chat
70 | try:
71 | buttons = [[
72 | InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}')
73 | ]]
74 | reply_markup=InlineKeyboardMarkup(buttons)
75 | await bot.send_message(
76 | chat_id=chat,
77 | 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.',
78 | reply_markup=reply_markup,
79 | )
80 |
81 | await bot.leave_chat(chat)
82 | await message.reply(f"left the chat `{chat}`")
83 | except Exception as e:
84 | await message.reply(f'Error - {e}')
85 |
86 | @Client.on_message(filters.command('disable') & filters.user(ADMINS))
87 | async def disable_chat(bot, message):
88 | if len(message.command) == 1:
89 | return await message.reply('Give me a chat id')
90 | r = message.text.split(None)
91 | if len(r) > 2:
92 | reason = message.text.split(None, 2)[2]
93 | chat = message.text.split(None, 2)[1]
94 | else:
95 | chat = message.command[1]
96 | reason = "No reason Provided"
97 | try:
98 | chat_ = int(chat)
99 | except:
100 | return await message.reply('Give Me A Valid Chat ID')
101 | cha_t = await db.get_chat(int(chat_))
102 | if not cha_t:
103 | return await message.reply("Chat Not Found In DB")
104 | if cha_t['is_disabled']:
105 | return await message.reply(f"This chat is already disabled:\nReason- {cha_t['reason']}
")
106 | await db.disable_chat(int(chat_), reason)
107 | temp.BANNED_CHATS.append(int(chat_))
108 | await message.reply('Chat Successfully Disabled')
109 | try:
110 | buttons = [[
111 | InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}')
112 | ]]
113 | reply_markup=InlineKeyboardMarkup(buttons)
114 | await bot.send_message(
115 | chat_id=chat_,
116 | 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}
',
117 | reply_markup=reply_markup)
118 | await bot.leave_chat(chat_)
119 | except Exception as e:
120 | await message.reply(f"Error - {e}")
121 |
122 |
123 | @Client.on_message(filters.command('enable') & filters.user(ADMINS))
124 | async def re_enable_chat(bot, message):
125 | if len(message.command) == 1:
126 | return await message.reply('Give me a chat id')
127 | chat = message.command[1]
128 | try:
129 | chat_ = int(chat)
130 | except:
131 | return await message.reply('Give Me A Valid Chat ID')
132 | sts = await db.get_chat(int(chat))
133 | if not sts:
134 | return await message.reply("Chat Not Found In DB !")
135 | if not sts.get('is_disabled'):
136 | return await message.reply('This chat is not yet disabled.')
137 | await db.re_enable_chat(int(chat_))
138 | temp.BANNED_CHATS.remove(int(chat_))
139 | await message.reply("Chat Successfully re-enabled")
140 |
141 |
142 | @Client.on_message(filters.command('stats') & filters.incoming)
143 | async def get_ststs(bot, message):
144 | rju = await message.reply('Fetching stats..')
145 | total_users = await db.total_users_count()
146 | totl_chats = await db.total_chat_count()
147 | files = await Media.count_documents()
148 | size = await db.get_db_size()
149 | free = 536870912 - size
150 | size = get_size(size)
151 | free = get_size(free)
152 | await rju.edit(script.STATUS_TXT.format(files, total_users, totl_chats, size, free))
153 |
154 |
155 | # a function for trespassing into others groups, Inspired by a Vazha
156 | # Not to be used , But Just to showcase his vazhatharam.
157 | # @Client.on_message(filters.command('invite') & filters.user(ADMINS))
158 | async def gen_invite(bot, message):
159 | if len(message.command) == 1:
160 | return await message.reply('Give me a chat id')
161 | chat = message.command[1]
162 | try:
163 | chat = int(chat)
164 | except:
165 | return await message.reply('Give Me A Valid Chat ID')
166 | try:
167 | link = await bot.create_chat_invite_link(chat)
168 | except ChatAdminRequired:
169 | return await message.reply("Invite Link Generation Failed, Iam Not Having Sufficient Rights")
170 | except Exception as e:
171 | return await message.reply(f'Error {e}')
172 | await message.reply(f'Here is your Invite Link {link.invite_link}')
173 |
174 | @Client.on_message(filters.command('ban') & filters.user(ADMINS))
175 | async def ban_a_user(bot, message):
176 | # https://t.me/GetTGLink/4185
177 | if len(message.command) == 1:
178 | return await message.reply('Give me a user id / username')
179 | r = message.text.split(None)
180 | if len(r) > 2:
181 | reason = message.text.split(None, 2)[2]
182 | chat = message.text.split(None, 2)[1]
183 | else:
184 | chat = message.command[1]
185 | reason = "No reason Provided"
186 | try:
187 | chat = int(chat)
188 | except:
189 | pass
190 | try:
191 | k = await bot.get_users(chat)
192 | except PeerIdInvalid:
193 | return await message.reply("This is an invalid user, make sure ia have met him before.")
194 | except IndexError:
195 | return await message.reply("This might be a channel, make sure its a user.")
196 | except Exception as e:
197 | return await message.reply(f'Error - {e}')
198 | else:
199 | jar = await db.get_ban_status(k.id)
200 | if jar['is_banned']:
201 | return await message.reply(f"{k.mention} is already banned\nReason: {jar['ban_reason']}")
202 | await db.ban_user(k.id, reason)
203 | temp.BANNED_USERS.append(k.id)
204 | await message.reply(f"Successfully banned {k.mention}")
205 |
206 |
207 |
208 | @Client.on_message(filters.command('unban') & filters.user(ADMINS))
209 | async def unban_a_user(bot, message):
210 | if len(message.command) == 1:
211 | return await message.reply('Give me a user id / username')
212 | r = message.text.split(None)
213 | if len(r) > 2:
214 | reason = message.text.split(None, 2)[2]
215 | chat = message.text.split(None, 2)[1]
216 | else:
217 | chat = message.command[1]
218 | reason = "No reason Provided"
219 | try:
220 | chat = int(chat)
221 | except:
222 | pass
223 | try:
224 | k = await bot.get_users(chat)
225 | except PeerIdInvalid:
226 | return await message.reply("This is an invalid user, make sure ia have met him before.")
227 | except IndexError:
228 | return await message.reply("Thismight be a channel, make sure its a user.")
229 | except Exception as e:
230 | return await message.reply(f'Error - {e}')
231 | else:
232 | jar = await db.get_ban_status(k.id)
233 | if not jar['is_banned']:
234 | return await message.reply(f"{k.mention} is not yet banned.")
235 | await db.remove_ban(k.id)
236 | temp.BANNED_USERS.remove(k.id)
237 | await message.reply(f"Successfully unbanned {k.mention}")
238 |
239 |
240 |
241 | @Client.on_message(filters.command('users') & filters.user(ADMINS))
242 | async def list_users(bot, message):
243 | # https://t.me/GetTGLink/4184
244 | raju = await message.reply('Getting List Of Users')
245 | users = await db.get_all_users()
246 | out = "Users Saved In DB Are:\n\n"
247 | async for user in users:
248 | out += f"{user['name']}"
249 | if user['ban_status']['is_banned']:
250 | out += '( Banned User )'
251 | out += '\n'
252 | try:
253 | await raju.edit_text(out)
254 | except MessageTooLong:
255 | with open('users.txt', 'w+') as outfile:
256 | outfile.write(out)
257 | await message.reply_document('users.txt', caption="List Of Users")
258 |
259 | @Client.on_message(filters.command('chats') & filters.user(ADMINS))
260 | async def list_chats(bot, message):
261 | raju = await message.reply('Getting List Of chats')
262 | chats = await db.get_all_chats()
263 | out = "Chats Saved In DB Are:\n\n"
264 | async for chat in chats:
265 | out += f"**Title:** `{chat['title']}`\n**- ID:** `{chat['id']}`"
266 | if chat['chat_status']['is_disabled']:
267 | out += '( Disabled Chat )'
268 | out += '\n'
269 | try:
270 | await raju.edit_text(out)
271 | except MessageTooLong:
272 | with open('chats.txt', 'w+') as outfile:
273 | outfile.write(out)
274 | await message.reply_document('chats.txt', caption="List Of Chats")
275 |
--------------------------------------------------------------------------------
/plugins/pm_filter.py:
--------------------------------------------------------------------------------
1 | # Kanged From @sahid malik
2 | import asyncio
3 | import re
4 | import ast
5 |
6 | from pyrogram.errors.exceptions.bad_request_400 import MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty
7 | from Script import script
8 | import pyrogram
9 | from database.connections_mdb import active_connection, all_connections, delete_connection, if_active, make_active, \
10 | make_inactive
11 | from info import ADMINS, AUTH_CHANNEL, AUTH_USERS, CUSTOM_FILE_CAPTION, AUTH_GROUPS, P_TTI_SHOW_OFF, IMDB, \
12 | SINGLE_BUTTON, SPELL_CHECK_REPLY, IMDB_TEMPLATE
13 | from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
14 | from pyrogram import Client, filters
15 | from pyrogram.errors import FloodWait, UserIsBlocked, MessageNotModified, PeerIdInvalid
16 | from utils import get_size, is_subscribed, get_poster, search_gagala, temp, get_settings, save_group_settings
17 | from database.users_chats_db import db
18 | from database.ia_filterdb import Media, get_file_details, get_search_results
19 | from database.filters_mdb import (
20 | del_all,
21 | find_filter,
22 | get_filters,
23 | )
24 | import logging
25 |
26 | logger = logging.getLogger(__name__)
27 | logger.setLevel(logging.ERROR)
28 |
29 | BUTTONS = {}
30 | SPELL_CHECK = {}
31 |
32 |
33 | @Client.on_message(filters.group & filters.text & ~filters.edited & filters.incoming)
34 | async def give_filter(client, message):
35 | k = await manual_filters(client, message)
36 | if k == False:
37 | await auto_filter(client, message)
38 |
39 |
40 | @Client.on_callback_query(filters.regex(r"^next"))
41 | async def next_page(bot, query):
42 | ident, req, key, offset = query.data.split("_")
43 | if int(req) not in [query.from_user.id, 0]:
44 | return await query.answer("😎 Hey bro Search Your Own", show_alert=True)
45 | try:
46 | offset = int(offset)
47 | except:
48 | offset = 0
49 | search = BUTTONS.get(key)
50 | if not search:
51 | await query.answer("You are using one of my old messages, please send the request again.", show_alert=True)
52 | return
53 |
54 | files, n_offset, total = await get_search_results(search, offset=offset, filter=True)
55 | try:
56 | n_offset = int(n_offset)
57 | except:
58 | n_offset = 0
59 |
60 | if not files:
61 | return
62 | settings = await get_settings(query.message.chat.id)
63 | if settings['button']:
64 | btn = [
65 | [
66 | InlineKeyboardButton(
67 | text=f"[{get_size(file.file_size)}] {file.file_name}", callback_data=f'files#{file.file_id}'
68 | ),
69 | ]
70 | for file in files
71 | ]
72 | else:
73 | btn = [
74 | [
75 | InlineKeyboardButton(
76 | text=f"{file.file_name}", callback_data=f'files#{file.file_id}'
77 | ),
78 | InlineKeyboardButton(
79 | text=f"{get_size(file.file_size)}",
80 | callback_data=f'files_#{file.file_id}',
81 | ),
82 | ]
83 | for file in files
84 | ]
85 |
86 | if 0 < offset <= 10:
87 | off_set = 0
88 | elif offset == 0:
89 | off_set = None
90 | else:
91 | off_set = offset - 10
92 | if n_offset == 0:
93 | btn.append(
94 | [InlineKeyboardButton("⏪ BACK", callback_data=f"next_{req}_{key}_{off_set}"),
95 | InlineKeyboardButton(f"📃 Pages {round(int(offset) / 10) + 1} / {round(total / 10)}",
96 | callback_data="pages")]
97 | )
98 | elif off_set is None:
99 | btn.append(
100 | [InlineKeyboardButton(f"🗓 {round(int(offset) / 10) + 1} / {round(total / 10)}", callback_data="pages"),
101 | InlineKeyboardButton("NEXT ⏩", callback_data=f"next_{req}_{key}_{n_offset}")])
102 | else:
103 | btn.append(
104 | [
105 | InlineKeyboardButton("⏪ BACK", callback_data=f"next_{req}_{key}_{off_set}"),
106 | InlineKeyboardButton(f"🗓 {round(int(offset) / 10) + 1} / {round(total / 10)}", callback_data="pages"),
107 | InlineKeyboardButton("NEXT ⏩", callback_data=f"next_{req}_{key}_{n_offset}")
108 | ],
109 | )
110 | btn.append(
111 | [InlineKeyboardButton("𝗖𝗹𝗼𝘀𝗲", callback_data="close_data")]
112 | )
113 | btn.insert(0, [
114 | InlineKeyboardButton(text="⚠️ 𝐉𝐨𝐢𝐧 𝐌𝐨𝐯𝐢𝐞𝐬 Group ⚠️", url="https://t.me/+gXuMKXOWm1UyOTdl")
115 | ])
116 | try:
117 | await query.edit_message_reply_markup(
118 | reply_markup=InlineKeyboardMarkup(btn)
119 | )
120 | except MessageNotModified:
121 | pass
122 | await query.answer()
123 |
124 |
125 | @Client.on_callback_query(filters.regex(r"^spolling"))
126 | async def advantage_spoll_choker(bot, query):
127 | _, user, movie_ = query.data.split('#')
128 | if int(user) != 0 and query.from_user.id != int(user):
129 | return await query.answer("😎 Hey bro Search Your Own", show_alert=True)
130 | if movie_ == "close_spellcheck":
131 | return await query.message.delete()
132 | movies = SPELL_CHECK.get(query.message.reply_to_message.message_id)
133 | if not movies:
134 | return await query.answer("You are clicking on an old button which is expired.", show_alert=True)
135 | movie = movies[(int(movie_))]
136 | await query.answer('Checking for Movie in database...')
137 | k = await manual_filters(bot, query.message, text=movie)
138 | if k == False:
139 | files, offset, total_results = await get_search_results(movie, offset=0, filter=True)
140 | if files:
141 | k = (movie, files, offset, total_results)
142 | await auto_filter(bot, query, k)
143 | else:
144 | k = await query.message.edit('♻️ This Movie Not Found my Database ♾♾♾♾♾♾♾♾♾♾♾♾♾♾ ♻️ Request to admin 👉 @m_admins')
145 | await asyncio.sleep(15)
146 | await k.delete()
147 |
148 |
149 | @Client.on_callback_query()
150 | async def cb_handler(client: Client, query: CallbackQuery):
151 | if query.data == "close_data":
152 | await query.message.delete()
153 | elif query.data == "delallconfirm":
154 | userid = query.from_user.id
155 | chat_type = query.message.chat.type
156 |
157 | if chat_type == "private":
158 | grpid = await active_connection(str(userid))
159 | if grpid is not None:
160 | grp_id = grpid
161 | try:
162 | chat = await client.get_chat(grpid)
163 | title = chat.title
164 | except:
165 | await query.message.edit_text("Make sure I'm present in your group!!", quote=True)
166 | return await query.answer('Piracy Is Crime')
167 | else:
168 | await query.message.edit_text(
169 | "I'm not connected to any groups!\nCheck /connections or connect to any groups",
170 | quote=True
171 | )
172 | return await query.answer('Piracy Is Crime')
173 |
174 | elif chat_type in ["group", "supergroup"]:
175 | grp_id = query.message.chat.id
176 | title = query.message.chat.title
177 |
178 | else:
179 | return await query.answer('Piracy Is Crime')
180 |
181 | st = await client.get_chat_member(grp_id, userid)
182 | if (st.status == "creator") or (str(userid) in ADMINS):
183 | await del_all(query.message, grp_id, title)
184 | else:
185 | await query.answer("You need to be Group Owner or an Auth User to do that!", show_alert=True)
186 | elif query.data == "delallcancel":
187 | userid = query.from_user.id
188 | chat_type = query.message.chat.type
189 |
190 | if chat_type == "private":
191 | await query.message.reply_to_message.delete()
192 | await query.message.delete()
193 |
194 | elif chat_type in ["group", "supergroup"]:
195 | grp_id = query.message.chat.id
196 | st = await client.get_chat_member(grp_id, userid)
197 | if (st.status == "creator") or (str(userid) in ADMINS):
198 | await query.message.delete()
199 | try:
200 | await query.message.reply_to_message.delete()
201 | except:
202 | pass
203 | else:
204 | await query.answer("That's not for you!!", show_alert=True)
205 | elif "groupcb" in query.data:
206 | await query.answer()
207 |
208 | group_id = query.data.split(":")[1]
209 |
210 | act = query.data.split(":")[2]
211 | hr = await client.get_chat(int(group_id))
212 | title = hr.title
213 | user_id = query.from_user.id
214 |
215 | if act == "":
216 | stat = "CONNECT"
217 | cb = "connectcb"
218 | else:
219 | stat = "DISCONNECT"
220 | cb = "disconnect"
221 |
222 | keyboard = InlineKeyboardMarkup([
223 | [InlineKeyboardButton(f"{stat}", callback_data=f"{cb}:{group_id}"),
224 | InlineKeyboardButton("DELETE", callback_data=f"deletecb:{group_id}")],
225 | [InlineKeyboardButton("BACK", callback_data="backcb")]
226 | ])
227 |
228 | await query.message.edit_text(
229 | f"Group Name : **{title}**\nGroup ID : `{group_id}`",
230 | reply_markup=keyboard,
231 | parse_mode="md"
232 | )
233 | return await query.answer('Piracy Is Crime')
234 | elif "connectcb" in query.data:
235 | await query.answer()
236 |
237 | group_id = query.data.split(":")[1]
238 |
239 | hr = await client.get_chat(int(group_id))
240 |
241 | title = hr.title
242 |
243 | user_id = query.from_user.id
244 |
245 | mkact = await make_active(str(user_id), str(group_id))
246 |
247 | if mkact:
248 | await query.message.edit_text(
249 | f"Connected to **{title}**",
250 | parse_mode="md"
251 | )
252 | else:
253 | await query.message.edit_text('Some error occurred!!', parse_mode="md")
254 | return await query.answer('Piracy Is Crime')
255 | elif "disconnect" in query.data:
256 | await query.answer()
257 |
258 | group_id = query.data.split(":")[1]
259 |
260 | hr = await client.get_chat(int(group_id))
261 |
262 | title = hr.title
263 | user_id = query.from_user.id
264 |
265 | mkinact = await make_inactive(str(user_id))
266 |
267 | if mkinact:
268 | await query.message.edit_text(
269 | f"Disconnected from **{title}**",
270 | parse_mode="md"
271 | )
272 | else:
273 | await query.message.edit_text(
274 | f"Some error occurred!!",
275 | parse_mode="md"
276 | )
277 | return await query.answer('Piracy Is Crime')
278 | elif "deletecb" in query.data:
279 | await query.answer()
280 |
281 | user_id = query.from_user.id
282 | group_id = query.data.split(":")[1]
283 |
284 | delcon = await delete_connection(str(user_id), str(group_id))
285 |
286 | if delcon:
287 | await query.message.edit_text(
288 | "Successfully deleted connection"
289 | )
290 | else:
291 | await query.message.edit_text(
292 | f"Some error occurred!!",
293 | parse_mode="md"
294 | )
295 | return await query.answer('Piracy Is Crime')
296 | elif query.data == "backcb":
297 | await query.answer()
298 |
299 | userid = query.from_user.id
300 |
301 | groupids = await all_connections(str(userid))
302 | if groupids is None:
303 | await query.message.edit_text(
304 | "There are no active connections!! Connect to some groups first.",
305 | )
306 | return await query.answer('Piracy Is Crime')
307 | buttons = []
308 | for groupid in groupids:
309 | try:
310 | ttl = await client.get_chat(int(groupid))
311 | title = ttl.title
312 | active = await if_active(str(userid), str(groupid))
313 | act = " - ACTIVE" if active else ""
314 | buttons.append(
315 | [
316 | InlineKeyboardButton(
317 | text=f"{title}{act}", callback_data=f"groupcb:{groupid}:{act}"
318 | )
319 | ]
320 | )
321 | except:
322 | pass
323 | if buttons:
324 | await query.message.edit_text(
325 | "Your connected group details ;\n\n",
326 | reply_markup=InlineKeyboardMarkup(buttons)
327 | )
328 | elif "alertmessage" in query.data:
329 | grp_id = query.message.chat.id
330 | i = query.data.split(":")[1]
331 | keyword = query.data.split(":")[2]
332 | reply_text, btn, alerts, fileid = await find_filter(grp_id, keyword)
333 | if alerts is not None:
334 | alerts = ast.literal_eval(alerts)
335 | alert = alerts[int(i)]
336 | alert = alert.replace("\\n", "\n").replace("\\t", "\t")
337 | await query.answer(alert, show_alert=True)
338 | if query.data.startswith("file"):
339 | ident, file_id = query.data.split("#")
340 | files_ = await get_file_details(file_id)
341 | if not files_:
342 | return await query.answer('No such file exist.')
343 | files = files_[0]
344 | title = files.file_name
345 | size = get_size(files.file_size)
346 | f_caption = files.caption
347 | settings = await get_settings(query.message.chat.id)
348 | if CUSTOM_FILE_CAPTION:
349 | try:
350 | f_caption = CUSTOM_FILE_CAPTION.format(file_name='' if title is None else title,
351 | file_size='' if size is None else size,
352 | file_caption='' if f_caption is None else f_caption)
353 | except Exception as e:
354 | logger.exception(e)
355 | f_caption = f_caption
356 | if f_caption is None:
357 | f_caption = f"{files.file_name}"
358 |
359 | try:
360 | if AUTH_CHANNEL and not await is_subscribed(client, query):
361 | await query.answer(url=f"https://t.me/{temp.U_NAME}?start={ident}_{file_id}")
362 | return
363 | elif settings['botpm']:
364 | await query.answer(url=f"https://t.me/{temp.U_NAME}?start={ident}_{file_id}")
365 | return
366 | else:
367 | await client.send_cached_media(
368 | chat_id=query.from_user.id,
369 | file_id=file_id,
370 | caption=f_caption,
371 | protect_content=True if ident == "filep" else False
372 | )
373 | await query.answer('Check PM, I have sent files in pm', show_alert=True)
374 | except UserIsBlocked:
375 | await query.answer('Unblock the bot mahn !', show_alert=True)
376 | except PeerIdInvalid:
377 | await query.answer(url=f"https://t.me/{temp.U_NAME}?start={ident}_{file_id}")
378 | except Exception as e:
379 | await query.answer(url=f"https://t.me/{temp.U_NAME}?start={ident}_{file_id}")
380 | elif query.data.startswith("checksub"):
381 | if AUTH_CHANNEL and not await is_subscribed(client, query):
382 | await query.answer("I Like Your Smartness, But Don't Be Oversmart 😒... 😳 bro niche diye gye updates channel ko join karo jab tak aap updates channel join nahi karte tab tak bot apko movie nahi dega! ", show_alert=True)
383 | return
384 | ident, file_id = query.data.split("#")
385 | files_ = await get_file_details(file_id)
386 | if not files_:
387 | return await query.answer('No such file exist.')
388 | files = files_[0]
389 | title = files.file_name
390 | size = get_size(files.file_size)
391 | f_caption = files.caption
392 | if CUSTOM_FILE_CAPTION:
393 | try:
394 | f_caption = CUSTOM_FILE_CAPTION.format(file_name='' if title is None else title,
395 | file_size='' if size is None else size,
396 | file_caption='' if f_caption is None else f_caption)
397 | except Exception as e:
398 | logger.exception(e)
399 | f_caption = f_caption
400 | if f_caption is None:
401 | f_caption = f"{title}"
402 | await query.answer()
403 | await client.send_cached_media(
404 | chat_id=query.from_user.id,
405 | file_id=file_id,
406 | caption=f_caption,
407 | protect_content=True if ident == 'checksubp' else False
408 | )
409 | elif query.data == "pages":
410 | await query.answer()
411 | elif query.data == "start":
412 | buttons = [[
413 | InlineKeyboardButton('✳️ Add Me To Your Groups ✳️', url=f'http://t.me/{temp.U_NAME}?startgroup=true')
414 | ],[
415 | InlineKeyboardButton('💠 CHANNEL 💠', url='https://t.me/+ZeZNvt43B4o3ZmJl'),
416 | InlineKeyboardButton('☎️ CONTACT ME', url='https://t.me/sahid_malik'),
417 | InlineKeyboardButton('💠 UPDATES 💠', url='https://t.me/m_house786')
418 | ],[
419 | InlineKeyboardButton('♻️ Help ♻️', callback_data='help'),
420 | InlineKeyboardButton('🌷Join my group', url='https://t.me/+gXuMKXOWm1UyOTdl'),
421 | InlineKeyboardButton('♻️ About ♻️', callback_data='about')
422 | ],[
423 | InlineKeyboardButton('✅ Subscribe my YouTube channel ✅', url='https://youtube.com/channel/UCPaHDqWf3D3w2nxb8p3sr4A')
424 | ]]
425 | reply_markup = InlineKeyboardMarkup(buttons)
426 | await query.message.edit_text(
427 | text=script.START_TXT.format(query.from_user.mention, temp.U_NAME, temp.B_NAME),
428 | reply_markup=reply_markup,
429 | parse_mode='html'
430 | )
431 | await query.answer('Piracy Is Crime')
432 | elif query.data == "help":
433 | buttons = [[
434 | InlineKeyboardButton('𝗠𝗮𝗻𝘂𝗲𝗹 𝗙𝗶𝗹𝘁𝗲𝗿', callback_data='manuelfilter'),
435 | InlineKeyboardButton('𝗔𝘂𝘁𝗼 𝗙𝗶𝗹𝘁𝗲𝗿', callback_data='autofilter')
436 | ], [
437 | InlineKeyboardButton('𝗖𝗼𝗻𝗻𝗲𝗰𝘁𝗶𝗼𝗻𝘀', callback_data='coct'),
438 | InlineKeyboardButton('𝗘𝘅𝘁𝗿𝗮 𝗠𝗼𝗱𝗲𝘀', callback_data='extra')
439 | ], [
440 | InlineKeyboardButton('🏠 𝗛𝗼𝗺𝗲 🏠', callback_data='start'),
441 | InlineKeyboardButton('⚚ 𝗦𝘁𝗮𝘁𝘀 ⚚', callback_data='stats')
442 | ]]
443 | reply_markup = InlineKeyboardMarkup(buttons)
444 | await query.message.edit_text(
445 | text=script.HELP_TXT.format(query.from_user.mention),
446 | reply_markup=reply_markup,
447 | parse_mode='html'
448 | )
449 | elif query.data == "about":
450 | buttons = [[
451 | InlineKeyboardButton('🌴 Bots Channel 🌴', url='https://t.me/malik_bots'),
452 | InlineKeyboardButton('♥️ Source', callback_data='source')
453 | ], [
454 | InlineKeyboardButton('🏠 𝗛𝗼𝗺𝗲 🏠', callback_data='start'),
455 | InlineKeyboardButton('🔐 𝗖𝗹𝗼𝘀𝗲 🔐', callback_data='close_data')
456 | ]]
457 | reply_markup = InlineKeyboardMarkup(buttons)
458 | await query.message.edit_text(
459 | text=script.ABOUT_TXT.format(temp.B_NAME),
460 | reply_markup=reply_markup,
461 | parse_mode='html'
462 | )
463 | elif query.data == "source":
464 | buttons = [[
465 | InlineKeyboardButton('🚶 𝗕𝗮𝗰𝗸 🚶', callback_data='about')
466 | ]]
467 | reply_markup = InlineKeyboardMarkup(buttons)
468 | await query.message.edit_text(
469 | text=script.SOURCE_TXT,
470 | reply_markup=reply_markup,
471 | parse_mode='html'
472 | )
473 | elif query.data == "manuelfilter":
474 | buttons = [[
475 | InlineKeyboardButton('🚶 𝗕𝗮𝗰𝗸 🚶', callback_data='help'),
476 | InlineKeyboardButton('⏹️ 𝗕𝘂𝘁𝘁𝗼𝗻𝘀 ⏹', callback_data='button')
477 | ]]
478 | reply_markup = InlineKeyboardMarkup(buttons)
479 | await query.message.edit_text(
480 | text=script.MANUELFILTER_TXT,
481 | reply_markup=reply_markup,
482 | parse_mode='html'
483 | )
484 | elif query.data == "button":
485 | buttons = [[
486 | InlineKeyboardButton('🚶 𝗕𝗮𝗰𝗸 🚶', callback_data='manuelfilter')
487 | ]]
488 | reply_markup = InlineKeyboardMarkup(buttons)
489 | await query.message.edit_text(
490 | text=script.BUTTON_TXT,
491 | reply_markup=reply_markup,
492 | parse_mode='html'
493 | )
494 | elif query.data == "autofilter":
495 | buttons = [[
496 | InlineKeyboardButton('🚶 𝗕𝗮𝗰𝗸 🚶', callback_data='help')
497 | ]]
498 | reply_markup = InlineKeyboardMarkup(buttons)
499 | await query.message.edit_text(
500 | text=script.AUTOFILTER_TXT,
501 | reply_markup=reply_markup,
502 | parse_mode='html'
503 | )
504 | elif query.data == "coct":
505 | buttons = [[
506 | InlineKeyboardButton('🚶 𝗕𝗮𝗰𝗸 🚶', callback_data='help')
507 | ]]
508 | reply_markup = InlineKeyboardMarkup(buttons)
509 | await query.message.edit_text(
510 | text=script.CONNECTION_TXT,
511 | reply_markup=reply_markup,
512 | parse_mode='html'
513 | )
514 | elif query.data == "extra":
515 | buttons = [[
516 | InlineKeyboardButton('🚶 𝗕𝗮𝗰𝗸 🚶', callback_data='help'),
517 | InlineKeyboardButton('👮♂️ owner👮', callback_data='admin')
518 | ]]
519 | reply_markup = InlineKeyboardMarkup(buttons)
520 | await query.message.edit_text(
521 | text=script.EXTRAMOD_TXT,
522 | reply_markup=reply_markup,
523 | parse_mode='html'
524 | )
525 | elif query.data == "admin":
526 | buttons = [[
527 | InlineKeyboardButton('🚶 𝗕𝗮𝗰𝗸 🚶', callback_data='extra')
528 | ]]
529 | reply_markup = InlineKeyboardMarkup(buttons)
530 | await query.message.edit_text(
531 | text=script.ADMIN_TXT,
532 | reply_markup=reply_markup,
533 | parse_mode='html'
534 | )
535 | elif query.data == "stats":
536 | buttons = [[
537 | InlineKeyboardButton('🚶 𝗕𝗮𝗰𝗸 🚶', callback_data='help'),
538 | InlineKeyboardButton('♻️', callback_data='rfrsh')
539 | ]]
540 | reply_markup = InlineKeyboardMarkup(buttons)
541 | total = await Media.count_documents()
542 | users = await db.total_users_count()
543 | chats = await db.total_chat_count()
544 | monsize = await db.get_db_size()
545 | free = 536870912 - monsize
546 | monsize = get_size(monsize)
547 | free = get_size(free)
548 | await query.message.edit_text(
549 | text=script.STATUS_TXT.format(total, users, chats, monsize, free),
550 | reply_markup=reply_markup,
551 | parse_mode='html'
552 | )
553 | elif query.data == "rfrsh":
554 | await query.answer("Fetching MongoDb DataBase")
555 | buttons = [[
556 | InlineKeyboardButton('🚶 𝗕𝗮𝗰𝗸 🚶', callback_data='help'),
557 | InlineKeyboardButton('♻️', callback_data='rfrsh')
558 | ]]
559 | reply_markup = InlineKeyboardMarkup(buttons)
560 | total = await Media.count_documents()
561 | users = await db.total_users_count()
562 | chats = await db.total_chat_count()
563 | monsize = await db.get_db_size()
564 | free = 536870912 - monsize
565 | monsize = get_size(monsize)
566 | free = get_size(free)
567 | await query.message.edit_text(
568 | text=script.STATUS_TXT.format(total, users, chats, monsize, free),
569 | reply_markup=reply_markup,
570 | parse_mode='html'
571 | )
572 | elif query.data.startswith("setgs"):
573 | ident, set_type, status, grp_id = query.data.split("#")
574 | grpid = await active_connection(str(query.from_user.id))
575 |
576 | if str(grp_id) != str(grpid):
577 | await query.message.edit("Your Active Connection Has Been Changed. Go To /settings.")
578 | return await query.answer('Piracy Is Crime')
579 |
580 | if status == "True":
581 | await save_group_settings(grpid, set_type, False)
582 | else:
583 | await save_group_settings(grpid, set_type, True)
584 |
585 | settings = await get_settings(grpid)
586 |
587 | if settings is not None:
588 | buttons = [
589 | [
590 | InlineKeyboardButton('Filter Button',
591 | callback_data=f'setgs#button#{settings["button"]}#{str(grp_id)}'),
592 | InlineKeyboardButton('Single' if settings["button"] else 'Double',
593 | callback_data=f'setgs#button#{settings["button"]}#{str(grp_id)}')
594 | ],
595 | [
596 | InlineKeyboardButton('Bot PM', callback_data=f'setgs#botpm#{settings["botpm"]}#{str(grp_id)}'),
597 | InlineKeyboardButton('✅ Yes' if settings["botpm"] else '❌ No',
598 | callback_data=f'setgs#botpm#{settings["botpm"]}#{str(grp_id)}')
599 | ],
600 | [
601 | InlineKeyboardButton('File Secure',
602 | callback_data=f'setgs#file_secure#{settings["file_secure"]}#{str(grp_id)}'),
603 | InlineKeyboardButton('✅ Yes' if settings["file_secure"] else '❌ No',
604 | callback_data=f'setgs#file_secure#{settings["file_secure"]}#{str(grp_id)}')
605 | ],
606 | [
607 | InlineKeyboardButton('IMDB', callback_data=f'setgs#imdb#{settings["imdb"]}#{str(grp_id)}'),
608 | InlineKeyboardButton('✅ Yes' if settings["imdb"] else '❌ No',
609 | callback_data=f'setgs#imdb#{settings["imdb"]}#{str(grp_id)}')
610 | ],
611 | [
612 | InlineKeyboardButton('Spell Check',
613 | callback_data=f'setgs#spell_check#{settings["spell_check"]}#{str(grp_id)}'),
614 | InlineKeyboardButton('✅ Yes' if settings["spell_check"] else '❌ No',
615 | callback_data=f'setgs#spell_check#{settings["spell_check"]}#{str(grp_id)}')
616 | ],
617 | [
618 | InlineKeyboardButton('Welcome', callback_data=f'setgs#welcome#{settings["welcome"]}#{str(grp_id)}'),
619 | InlineKeyboardButton('✅ Yes' if settings["welcome"] else '❌ No',
620 | callback_data=f'setgs#welcome#{settings["welcome"]}#{str(grp_id)}')
621 | ]
622 | ]
623 | reply_markup = InlineKeyboardMarkup(buttons)
624 | await query.message.edit_reply_markup(reply_markup)
625 | await query.answer('Piracy Is Crime')
626 |
627 |
628 | async def auto_filter(client, msg, spoll=False):
629 | if not spoll:
630 | message = msg
631 | settings = await get_settings(message.chat.id)
632 | if message.text.startswith("/"): return # ignore commands
633 | if re.findall("((^\/|^,|^!|^\.|^[\U0001F600-\U000E007F]).*)", message.text):
634 | return
635 | if 2 < len(message.text) < 100:
636 | search = message.text
637 | files, offset, total_results = await get_search_results(search.lower(), offset=0, filter=True)
638 | if not files:
639 | if settings["spell_check"]:
640 | return await advantage_spell_chok(msg)
641 | else:
642 | return
643 | else:
644 | return
645 | else:
646 | settings = await get_settings(msg.message.chat.id)
647 | message = msg.message.reply_to_message # msg will be callback query
648 | search, files, offset, total_results = spoll
649 | pre = 'filep' if settings['file_secure'] else 'file'
650 | if settings["button"]:
651 | btn = [
652 | [
653 | InlineKeyboardButton(
654 | text=f"[{get_size(file.file_size)}] {file.file_name}", callback_data=f'{pre}#{file.file_id}'
655 | ),
656 | ]
657 | for file in files
658 | ]
659 | else:
660 | btn = [
661 | [
662 | InlineKeyboardButton(
663 | text=f"{file.file_name}",
664 | callback_data=f'{pre}#{file.file_id}',
665 | ),
666 | InlineKeyboardButton(
667 | text=f"{get_size(file.file_size)}",
668 | callback_data=f'{pre}_#{file.file_id}',
669 | ),
670 | ]
671 | for file in files
672 | ]
673 |
674 | if offset != "":
675 | key = f"{message.chat.id}-{message.message_id}"
676 | BUTTONS[key] = search
677 | req = message.from_user.id if message.from_user else 0
678 | btn.append(
679 | [InlineKeyboardButton(text=f"🌹 𝗣𝗮𝗴𝗲 1/{round(int(total_results) / 10)}", callback_data="pages"),
680 | InlineKeyboardButton(text="NEXT ⏩", callback_data=f"next_{req}_{key}_{offset}")]
681 | )
682 | else:
683 | btn.append(
684 | [InlineKeyboardButton(text="🌹 𝗣𝗮𝗴𝗲 1/1", callback_data="pages")]
685 | )
686 | btn.insert(0, [
687 | InlineKeyboardButton(text="⚠️ 𝐉𝐨𝐢𝐧 𝐌𝐨𝐯𝐢𝐞𝐬 𝙂𝙧𝙤𝙪𝙥 ⚠️", url="https://t.me/+gXuMKXOWm1UyOTdl")
688 | ])
689 | imdb = await get_poster(search, file=(files[0]).file_name) if settings["imdb"] else None
690 | TEMPLATE = settings['template']
691 | if imdb:
692 | cap = TEMPLATE.format(
693 | query=search,
694 | title=imdb['title'],
695 | votes=imdb['votes'],
696 | aka=imdb["aka"],
697 | seasons=imdb["seasons"],
698 | box_office=imdb['box_office'],
699 | localized_title=imdb['localized_title'],
700 | kind=imdb['kind'],
701 | imdb_id=imdb["imdb_id"],
702 | cast=imdb["cast"],
703 | runtime=imdb["runtime"],
704 | countries=imdb["countries"],
705 | certificates=imdb["certificates"],
706 | languages=imdb["languages"],
707 | director=imdb["director"],
708 | writer=imdb["writer"],
709 | producer=imdb["producer"],
710 | composer=imdb["composer"],
711 | cinematographer=imdb["cinematographer"],
712 | music_team=imdb["music_team"],
713 | distributors=imdb["distributors"],
714 | release_date=imdb['release_date'],
715 | year=imdb['year'],
716 | genres=imdb['genres'],
717 | poster=imdb['poster'],
718 | plot=imdb['plot'],
719 | rating=imdb['rating'],
720 | url=imdb['url'],
721 | **locals()
722 | )
723 | else:
724 | cap = f"Here is what i found for your query {search}"
725 | if imdb and imdb.get('poster'):
726 | try:
727 | await message.reply_photo(photo=imdb.get('poster'), caption=cap[:1024],
728 | reply_markup=InlineKeyboardMarkup(btn))
729 | except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty):
730 | pic = imdb.get('poster')
731 | poster = pic.replace('.jpg', "._V1_UX360.jpg")
732 | await message.reply_photo(photo=poster, caption=cap[:1024], reply_markup=InlineKeyboardMarkup(btn))
733 | except Exception as e:
734 | logger.exception(e)
735 | await message.reply_text(cap, reply_markup=InlineKeyboardMarkup(btn))
736 | else:
737 | await message.reply_text(cap, reply_markup=InlineKeyboardMarkup(btn))
738 | if spoll:
739 | await msg.message.delete()
740 |
741 |
742 | async def advantage_spell_chok(msg):
743 | query = re.sub(
744 | r"\b(pl(i|e)*?(s|z+|ease|se|ese|(e+)s(e)?)|((send|snd|giv(e)?|gib)(\sme)?)|movie(s)?|new|latest|br((o|u)h?)*|^h(e|a)?(l)*(o)*|mal(ayalam)?|t(h)?amil|file|that|find|und(o)*|kit(t(i|y)?)?o(w)?|thar(u)?(o)*w?|kittum(o)*|aya(k)*(um(o)*)?|full\smovie|any(one)|with\ssubtitle(s)?)",
745 | "", msg.text, flags=re.IGNORECASE) # plis contribute some common words
746 | query = query.strip() + " movie"
747 | g_s = await search_gagala(query)
748 | g_s += await search_gagala(msg.text)
749 | gs_parsed = []
750 | if not g_s:
751 | k = await msg.reply("I couldn't find any movie in that name.")
752 | await asyncio.sleep(8)
753 | await k.delete()
754 | return
755 | regex = re.compile(r".*(imdb|wikipedia).*", re.IGNORECASE) # look for imdb / wiki results
756 | gs = list(filter(regex.match, g_s))
757 | gs_parsed = [re.sub(
758 | r'\b(\-([a-zA-Z-\s])\-\simdb|(\-\s)?imdb|(\-\s)?wikipedia|\(|\)|\-|reviews|full|all|episode(s)?|film|movie|series)',
759 | '', i, flags=re.IGNORECASE) for i in gs]
760 | if not gs_parsed:
761 | reg = re.compile(r"watch(\s[a-zA-Z0-9_\s\-\(\)]*)*\|.*",
762 | re.IGNORECASE) # match something like Watch Niram | Amazon Prime
763 | for mv in g_s:
764 | match = reg.match(mv)
765 | if match:
766 | gs_parsed.append(match.group(1))
767 | user = msg.from_user.id if msg.from_user else 0
768 | movielist = []
769 | gs_parsed = list(dict.fromkeys(gs_parsed)) # removing duplicates https://stackoverflow.com/a/7961425
770 | if len(gs_parsed) > 3:
771 | gs_parsed = gs_parsed[:3]
772 | if gs_parsed:
773 | for mov in gs_parsed:
774 | imdb_s = await get_poster(mov.strip(), bulk=True) # searching each keyword in imdb
775 | if imdb_s:
776 | movielist += [movie.get('title') for movie in imdb_s]
777 | movielist += [(re.sub(r'(\-|\(|\)|_)', '', i, flags=re.IGNORECASE)).strip() for i in gs_parsed]
778 | movielist = list(dict.fromkeys(movielist)) # removing duplicates
779 | if not movielist:
780 | k = await msg.reply("I couldn't find anything related to that. Check your spelling")
781 | await asyncio.sleep(8)
782 | await k.delete()
783 | return
784 | SPELL_CHECK[msg.message_id] = movielist
785 | btn = [[
786 | InlineKeyboardButton(
787 | text=movie.strip(),
788 | callback_data=f"spolling#{user}#{k}",
789 | )
790 | ] for k, movie in enumerate(movielist)]
791 | btn.append([InlineKeyboardButton(text="Close", callback_data=f'spolling#{user}#close_spellcheck')])
792 | await msg.reply("CHECK YOUR MOVIE ON THE GIVEN LIST AND SELECT YOUR MOVIE.. ━━━━━━━━━━━━━━━━━ दी गई सूची में अपनी फिल्म देखें और अपनी फिल्म चुनें 👇👇👇 ",
793 | reply_markup=InlineKeyboardMarkup(btn))
794 |
795 |
796 | async def manual_filters(client, message, text=False):
797 | group_id = message.chat.id
798 | name = text or message.text
799 | reply_id = message.reply_to_message.message_id if message.reply_to_message else message.message_id
800 | keywords = await get_filters(group_id)
801 | for keyword in reversed(sorted(keywords, key=len)):
802 | pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])"
803 | if re.search(pattern, name, flags=re.IGNORECASE):
804 | reply_text, btn, alert, fileid = await find_filter(group_id, keyword)
805 |
806 | if reply_text:
807 | reply_text = reply_text.replace("\\n", "\n").replace("\\t", "\t")
808 |
809 | if btn is not None:
810 | try:
811 | if fileid == "None":
812 | if btn == "[]":
813 | await client.send_message(group_id, reply_text, disable_web_page_preview=True)
814 | else:
815 | button = eval(btn)
816 | await client.send_message(
817 | group_id,
818 | reply_text,
819 | disable_web_page_preview=True,
820 | reply_markup=InlineKeyboardMarkup(button),
821 | reply_to_message_id=reply_id
822 | )
823 | elif btn == "[]":
824 | await client.send_cached_media(
825 | group_id,
826 | fileid,
827 | caption=reply_text or "",
828 | reply_to_message_id=reply_id
829 | )
830 | else:
831 | button = eval(btn)
832 | await message.reply_cached_media(
833 | fileid,
834 | caption=reply_text or "",
835 | reply_markup=InlineKeyboardMarkup(button),
836 | reply_to_message_id=reply_id
837 | )
838 | except Exception as e:
839 | logger.exception(e)
840 | break
841 | else:
842 | return False
843 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | git+https://github.com/subinps/pyrogram@inline-m
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 | imdbpy
10 |
--------------------------------------------------------------------------------
/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/Malik7983/file-filter-bot.git /file-filter-bot
5 | else
6 | echo "Cloning Custom Repo from $UPSTREAM_REPO "
7 | git clone $UPSTREAM_REPO /file-filter-bot
8 | fi
9 | cd /file-filter-bot
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
4 | from imdb import IMDb
5 | import asyncio
6 | from pyrogram.types import Message
7 | from typing import Union
8 | import re
9 | import os
10 | from datetime import datetime
11 | from typing import List
12 | from pyrogram.types import InlineKeyboardButton
13 | from database.users_chats_db import db
14 | from bs4 import BeautifulSoup
15 | import requests
16 |
17 | logger = logging.getLogger(__name__)
18 | logger.setLevel(logging.INFO)
19 |
20 | BTN_URL_REGEX = re.compile(
21 | r"(\[([^\[]+?)\]\((buttonurl|buttonalert):(?:/{0,2})(.+?)(:same)?\))"
22 | )
23 |
24 | imdb = IMDb()
25 |
26 | BANNED = {}
27 | SMART_OPEN = '“'
28 | SMART_CLOSE = '”'
29 | START_CHAR = ('\'', '"', SMART_OPEN)
30 |
31 | # temp db for banned
32 | class temp(object):
33 | BANNED_USERS = []
34 | BANNED_CHATS = []
35 | ME = None
36 | CURRENT=int(os.environ.get("SKIP", 2))
37 | CANCEL = False
38 | MELCOW = {}
39 | U_NAME = None
40 | B_NAME = None
41 | SETTINGS = {}
42 |
43 | async def is_subscribed(bot, query):
44 | try:
45 | user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id)
46 | except UserNotParticipant:
47 | pass
48 | except Exception as e:
49 | logger.exception(e)
50 | else:
51 | if user.status != 'kicked':
52 | return True
53 |
54 | return False
55 |
56 | async def get_poster(query, bulk=False, id=False, file=None):
57 | if not id:
58 | # https://t.me/GetTGLink/4183
59 | query = (query.strip()).lower()
60 | title = query
61 | year = re.findall(r'[1-2]\d{3}$', query, re.IGNORECASE)
62 | if year:
63 | year = list_to_str(year[:1])
64 | title = (query.replace(year, "")).strip()
65 | elif file is not None:
66 | year = re.findall(r'[1-2]\d{3}', file, re.IGNORECASE)
67 | if year:
68 | year = list_to_str(year[:1])
69 | else:
70 | year = None
71 | movieid = imdb.search_movie(title.lower(), results=10)
72 | if not movieid:
73 | return None
74 | if year:
75 | filtered=list(filter(lambda k: str(k.get('year')) == str(year), movieid))
76 | if not filtered:
77 | filtered = movieid
78 | else:
79 | filtered = movieid
80 | movieid=list(filter(lambda k: k.get('kind') in ['movie', 'tv series'], filtered))
81 | if not movieid:
82 | movieid = filtered
83 | if bulk:
84 | return movieid
85 | movieid = movieid[0].movieID
86 | else:
87 | movieid = query
88 | movie = imdb.get_movie(movieid)
89 | if movie.get("original air date"):
90 | date = movie["original air date"]
91 | elif movie.get("year"):
92 | date = movie.get("year")
93 | else:
94 | date = "N/A"
95 | plot = ""
96 | if not LONG_IMDB_DESCRIPTION:
97 | plot = movie.get('plot')
98 | if plot and len(plot) > 0:
99 | plot = plot[0]
100 | else:
101 | plot = movie.get('plot outline')
102 | if plot and len(plot) > 800:
103 | plot = plot[0:800] + "..."
104 |
105 | return {
106 | 'title': movie.get('title'),
107 | 'votes': movie.get('votes'),
108 | "aka": list_to_str(movie.get("akas")),
109 | "seasons": movie.get("number of seasons"),
110 | "box_office": movie.get('box office'),
111 | 'localized_title': movie.get('localized title'),
112 | 'kind': movie.get("kind"),
113 | "imdb_id": f"tt{movie.get('imdbID')}",
114 | "cast": list_to_str(movie.get("cast")),
115 | "runtime": list_to_str(movie.get("runtimes")),
116 | "countries": list_to_str(movie.get("countries")),
117 | "certificates": list_to_str(movie.get("certificates")),
118 | "languages": list_to_str(movie.get("languages")),
119 | "director": list_to_str(movie.get("director")),
120 | "writer":list_to_str(movie.get("writer")),
121 | "producer":list_to_str(movie.get("producer")),
122 | "composer":list_to_str(movie.get("composer")) ,
123 | "cinematographer":list_to_str(movie.get("cinematographer")),
124 | "music_team": list_to_str(movie.get("music department")),
125 | "distributors": list_to_str(movie.get("distributors")),
126 | 'release_date': date,
127 | 'year': movie.get('year'),
128 | 'genres': list_to_str(movie.get("genres")),
129 | 'poster': movie.get('full-size cover url'),
130 | 'plot': plot,
131 | 'rating': str(movie.get("rating")),
132 | 'url':f'https://www.imdb.com/title/tt{movieid}'
133 | }
134 | # https://github.com/odysseusmax/animated-lamp/blob/2ef4730eb2b5f0596ed6d03e7b05243d93e3415b/bot/utils/broadcast.py#L37
135 |
136 | async def broadcast_messages(user_id, message):
137 | try:
138 | await message.copy(chat_id=user_id)
139 | return True, "Success"
140 | except FloodWait as e:
141 | await asyncio.sleep(e.x)
142 | return await broadcast_messages(user_id, message)
143 | except InputUserDeactivated:
144 | await db.delete_user(int(user_id))
145 | logging.info(f"{user_id}-Removed from Database, since deleted account.")
146 | return False, "Deleted"
147 | except UserIsBlocked:
148 | logging.info(f"{user_id} -Blocked the bot.")
149 | return False, "Blocked"
150 | except PeerIdInvalid:
151 | await db.delete_user(int(user_id))
152 | logging.info(f"{user_id} - PeerIdInvalid")
153 | return False, "Error"
154 | except Exception as e:
155 | return False, "Error"
156 |
157 | async def search_gagala(text):
158 | usr_agent = {
159 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
160 | 'Chrome/61.0.3163.100 Safari/537.36'
161 | }
162 | text = text.replace(" ", '+')
163 | url = f'https://www.google.com/search?q={text}'
164 | response = requests.get(url, headers=usr_agent)
165 | response.raise_for_status()
166 | soup = BeautifulSoup(response.text, 'html.parser')
167 | titles = soup.find_all( 'h3' )
168 | return [title.getText() for title in titles]
169 |
170 |
171 | async def get_settings(group_id):
172 | settings = temp.SETTINGS.get(group_id)
173 | if not settings:
174 | settings = await db.get_settings(group_id)
175 | temp.SETTINGS[group_id] = settings
176 | return settings
177 |
178 | async def save_group_settings(group_id, key, value):
179 | current = await get_settings(group_id)
180 | current[key] = value
181 | temp.SETTINGS[group_id] = current
182 | await db.update_settings(group_id, current)
183 |
184 | def get_size(size):
185 | """Get size in readable format"""
186 |
187 | units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
188 | size = float(size)
189 | i = 0
190 | while size >= 1024.0 and i < len(units):
191 | i += 1
192 | size /= 1024.0
193 | return "%.2f %s" % (size, units[i])
194 |
195 | def split_list(l, n):
196 | for i in range(0, len(l), n):
197 | yield l[i:i + n]
198 |
199 | def get_file_id(msg: Message):
200 | if msg.media:
201 | for message_type in (
202 | "photo",
203 | "animation",
204 | "audio",
205 | "document",
206 | "video",
207 | "video_note",
208 | "voice",
209 | "sticker"
210 | ):
211 | obj = getattr(msg, message_type)
212 | if obj:
213 | setattr(obj, "message_type", message_type)
214 | return obj
215 |
216 | def extract_user(message: Message) -> Union[int, str]:
217 | """extracts the user from a message"""
218 | # https://github.com/SpEcHiDe/PyroGramBot/blob/f30e2cca12002121bad1982f68cd0ff9814ce027/pyrobot/helper_functions/extract_user.py#L7
219 | user_id = None
220 | user_first_name = None
221 | if message.reply_to_message:
222 | user_id = message.reply_to_message.from_user.id
223 | user_first_name = message.reply_to_message.from_user.first_name
224 |
225 | elif len(message.command) > 1:
226 | if (
227 | len(message.entities) > 1 and
228 | message.entities[1].type == "text_mention"
229 | ):
230 |
231 | required_entity = message.entities[1]
232 | user_id = required_entity.user.id
233 | user_first_name = required_entity.user.first_name
234 | else:
235 | user_id = message.command[1]
236 | # don't want to make a request -_-
237 | user_first_name = user_id
238 | try:
239 | user_id = int(user_id)
240 | except ValueError:
241 | pass
242 | else:
243 | user_id = message.from_user.id
244 | user_first_name = message.from_user.first_name
245 | return (user_id, user_first_name)
246 |
247 | def list_to_str(k):
248 | if not k:
249 | return "N/A"
250 | elif len(k) == 1:
251 | return str(k[0])
252 | elif MAX_LIST_ELM:
253 | k = k[:int(MAX_LIST_ELM)]
254 | return ' '.join(f'{elem}, ' for elem in k)
255 | else:
256 | return ' '.join(f'{elem}, ' for elem in k)
257 |
258 | def last_online(from_user):
259 | time = ""
260 | if from_user.is_bot:
261 | time += "🤖 Bot :("
262 | elif from_user.status == 'recently':
263 | time += "Recently"
264 | elif from_user.status == 'within_week':
265 | time += "Within the last week"
266 | elif from_user.status == 'within_month':
267 | time += "Within the last month"
268 | elif from_user.status == 'long_time_ago':
269 | time += "A long time ago :("
270 | elif from_user.status == 'online':
271 | time += "Currently Online"
272 | elif from_user.status == 'offline':
273 | time += datetime.fromtimestamp(from_user.last_online_date).strftime("%a, %d %b %Y, %H:%M:%S")
274 | return time
275 |
276 |
277 | def split_quotes(text: str) -> List:
278 | if not any(text.startswith(char) for char in START_CHAR):
279 | return text.split(None, 1)
280 | counter = 1 # ignore first char -> is some kind of quote
281 | while counter < len(text):
282 | if text[counter] == "\\":
283 | counter += 1
284 | elif text[counter] == text[0] or (text[0] == SMART_OPEN and text[counter] == SMART_CLOSE):
285 | break
286 | counter += 1
287 | else:
288 | return text.split(None, 1)
289 |
290 | # 1 to avoid starting quote, and counter is exclusive so avoids ending
291 | key = remove_escapes(text[1:counter].strip())
292 | # index will be in range, or `else` would have been executed and returned
293 | rest = text[counter + 1:].strip()
294 | if not key:
295 | key = text[0] + text[0]
296 | return list(filter(None, [key, rest]))
297 |
298 | def parser(text, keyword):
299 | if "buttonalert" in text:
300 | text = (text.replace("\n", "\\n").replace("\t", "\\t"))
301 | buttons = []
302 | note_data = ""
303 | prev = 0
304 | i = 0
305 | alerts = []
306 | for match in BTN_URL_REGEX.finditer(text):
307 | # Check if btnurl is escaped
308 | n_escapes = 0
309 | to_check = match.start(1) - 1
310 | while to_check > 0 and text[to_check] == "\\":
311 | n_escapes += 1
312 | to_check -= 1
313 |
314 | # if even, not escaped -> create button
315 | if n_escapes % 2 == 0:
316 | note_data += text[prev:match.start(1)]
317 | prev = match.end(1)
318 | if match.group(3) == "buttonalert":
319 | # create a thruple with button label, url, and newline status
320 | if bool(match.group(5)) and buttons:
321 | buttons[-1].append(InlineKeyboardButton(
322 | text=match.group(2),
323 | callback_data=f"alertmessage:{i}:{keyword}"
324 | ))
325 | else:
326 | buttons.append([InlineKeyboardButton(
327 | text=match.group(2),
328 | callback_data=f"alertmessage:{i}:{keyword}"
329 | )])
330 | i += 1
331 | alerts.append(match.group(4))
332 | elif bool(match.group(5)) and buttons:
333 | buttons[-1].append(InlineKeyboardButton(
334 | text=match.group(2),
335 | url=match.group(4).replace(" ", "")
336 | ))
337 | else:
338 | buttons.append([InlineKeyboardButton(
339 | text=match.group(2),
340 | url=match.group(4).replace(" ", "")
341 | )])
342 |
343 | else:
344 | note_data += text[prev:to_check]
345 | prev = match.start(1) - 1
346 | else:
347 | note_data += text[prev:]
348 |
349 | try:
350 | return note_data, buttons, alerts
351 | except:
352 | return note_data, buttons, None
353 |
354 | def remove_escapes(text: str) -> str:
355 | res = ""
356 | is_escaped = False
357 | for counter in range(len(text)):
358 | if is_escaped:
359 | res += text[counter]
360 | is_escaped = False
361 | elif text[counter] == "\\":
362 | is_escaped = True
363 | else:
364 | res += text[counter]
365 | return res
366 |
367 |
368 | def humanbytes(size):
369 | if not size:
370 | return ""
371 | power = 2**10
372 | n = 0
373 | Dic_powerN = {0: ' ', 1: 'Ki', 2: 'Mi', 3: 'Gi', 4: 'Ti'}
374 | while size > power:
375 | size /= power
376 | n += 1
377 | return str(round(size, 2)) + " " + Dic_powerN[n] + 'B'
378 |
--------------------------------------------------------------------------------