├── .env-example
├── .github
└── workflows
│ └── rust.yml
├── .gitignore
├── .idea
├── .gitignore
├── grpmr-rs.iml
├── modules.xml
└── vcs.xml
├── Cargo.toml
├── Dockerfile
├── LICENSE
├── README.md
└── src
├── database
├── db.rs
├── db_utils.rs
└── mod.rs
├── main.rs
├── modules
├── admin.rs
├── bans.rs
├── chat.rs
├── commands.rs
├── disable.rs
├── filters.rs
├── log_channel.rs
├── misc.rs
├── mod.rs
├── msg_delete.rs
├── restrict.rs
├── start.rs
├── sudo.rs
├── user.rs
└── warning.rs
└── util
├── consts.rs
├── custom_types.rs
├── mod.rs
└── utils.rs
/.env-example:
--------------------------------------------------------------------------------
1 | export TELOXIDE_TOKEN = //Get token from @BotFather
2 | export MONGO_URI = //Get URI from mongodb
3 | export OWNER_ID = 1332139172
4 | export SUDO_USERS = //ID's of Sudo users seperated by comma ex:- export SUDO_USERS=1332139172,1332139173
--------------------------------------------------------------------------------
/.github/workflows/rust.yml:
--------------------------------------------------------------------------------
1 | on: [push,pull_request]
2 |
3 | name: CI
4 |
5 | jobs:
6 | fmt:
7 | name: Rustfmt
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: actions/checkout@v2
11 | - uses: actions-rs/toolchain@v1
12 | with:
13 | profile: minimal
14 | toolchain: stable
15 | override: true
16 | - run: rustup component add rustfmt
17 | - uses: actions-rs/cargo@v1
18 | with:
19 | command: fmt
20 | args: --all -- --check
21 |
22 | clippy:
23 | name: Clippy
24 | runs-on: ubuntu-latest
25 | steps:
26 | - uses: actions/checkout@v2
27 | - uses: actions-rs/toolchain@v1
28 | with:
29 | profile: minimal
30 | toolchain: stable
31 | override: true
32 | - run: rustup component add clippy
33 | - uses: actions-rs/cargo@v1
34 | with:
35 | command: clippy
36 | args: -- -D warnings
37 |
38 | build:
39 | name: build
40 | runs-on: ubuntu-latest
41 | steps:
42 | - uses: actions/checkout@v2
43 | - uses: actions-rs/toolchain@v1
44 | with:
45 | toolchain: stable
46 | - uses: actions-rs/cargo@v1
47 | with:
48 | command: build
49 | args: --release --all-features
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .env
2 | /target
3 | Cargo.lock
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/.idea/grpmr-rs.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "tgbot"
3 | version = "0.1.0"
4 | authors = ["dracarys18 "]
5 | edition = "2021"
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | anyhow = "1.0.52"
10 | async_once = "0.2.6"
11 | chrono = "0.4"
12 | dotenv = "0.15.0"
13 | lazy_static = "1.4.0"
14 | log = "0.4.8"
15 | mime = "0.3.16"
16 | mongodb = "2.1.0"
17 | pretty_env_logger = "0.4.0"
18 | regex = "1.5.4"
19 | reqwest = { version = "0.11.9", features = ["json"] }
20 | serde = { version = "1.0.133", features = ["derive"] }
21 | serde_json = "1.0.74"
22 | teloxide = { version = "0.5.3", features = ["auto-send", "macros"] }
23 | tokio = { version = "1.15.0", features = ["rt-multi-thread", "macros","time"] }
24 | tokio-stream = "0.1.8"
25 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM rustlang/rust:nightly
2 |
3 | WORKDIR /app
4 | COPY . .
5 |
6 | RUN cargo build --release
7 |
8 | CMD cargo run --release
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 |
294 | Copyright (C)
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | , 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | TgBot-RS
2 |
3 |
4 |
5 | This is a Telegram group manager bot written in rust. Some of the available features in this bot are:
6 |
7 |
Admin
8 |
9 | Banning:
These commands ban/unban a user from a chat.
10 |
11 |
12 | User Restriction:
This command will mute/unmute a user from a particular chat.
13 |
14 |
15 | Warning:
Allows Admins to warn a user with a reason if the wanrs exceed the preset warn limit the user will be banned/kicked/muted based on warn settings.
16 |
17 |
18 | Kicking:
Kicks a particular user from a chat.
19 |
20 |
21 | Pinning:
Pins/Unpins the message in a chat.
22 |
23 |
24 | Promote:
Promotes a user to admin/Demotes the user and removes his admin permissions.
25 |
26 |
27 | Chat Restriction:
Admins can restrict the whole chat from sending certain type of messages.
28 |
29 |
30 |
Chat Methods
31 |
32 | Invitelink:
Sends the invitelink of the chat.
33 |
34 |
35 | Disabling
Disables the use of a command in a group.
36 |
37 |
38 | Filter:
Enables a trigger on keyword
and replies with reply
whenever it matches with keyword. All document,stickers,audio,video,photo
can be used as a trigger replies.
39 |
40 |
41 | Blacklist:
You can set any words as "blacklist" in your group and let the bot deal with whoever sends the blacklisted words automatically. The modes which are available currently are Warn , Ban , Kick , Delete
42 |
43 | Chat Settings:
You can set chat title, chat picture directly from the bot
44 | Logging:
Recent actions are great but you can't see the changes that are older than 48 hours. So you can set-up a custom log channels to log the group properly and access it whenever you want.
45 | Reporting:
If you spot any suspicious activity in a group you can report that to admin by replying with /report it will send the report with the message that was reported to admins.
46 |
47 |
48 |
User Methods
49 |
50 | Info:
Gives info about a user Including his first name,last name,user id,permanent url
of the user
51 |
52 |
53 | Id:
Gives user id if mentioned or just gives the id of the chat.
54 |
55 |
56 | Kickme:
Kicks the user who sent the command from the group
57 |
58 |
59 |
60 |
Sudo
61 | Global Bans:
Globally bans/unbans the user from the chats which are in common with the bot.
62 |
63 |
64 |
65 |
Other
66 |
67 | Urban Dictionary:
Find the meaning of a word in urban dictionary.
68 |
69 |
70 | PasteBin:
Pastes the given text into Katbin and sends the link of the paste.
71 |
72 |
73 |
74 |
75 | How to Use?
76 | First off you would need to go to @Botfather
in telegram and create a new bot and get the API token of the bot. And fill the TELOXIDE_TOKEN
in .env-example with the bot token. Fill OWNER_ID
with your telegram user id and fill SUDO_USERS
with the user id of your friends. Note that SUDO_USERS
will have access to some of the admin commands in the groups which bot is in.
77 |
78 | Now go to MongoDB and create an instance and get the URI of your database. Paste the URI in MONGO_URI
. Now rename .env-example
to .env
.
79 |
80 |
81 | Now after all these are set-up to run the bot just execute
82 |
83 | cargo run
84 |
85 | from your terminal.
86 |
87 | Credits
88 |
89 | teloxide : The telegram framework bot uses.
90 |
91 |
92 | MarieBot : For the basic idea of the many of the features.
93 |
--------------------------------------------------------------------------------
/src/database/db.rs:
--------------------------------------------------------------------------------
1 | pub struct Db {
2 | db_uri: String,
3 | }
4 |
5 | impl Db {
6 | pub fn new(uri: String) -> Self {
7 | Db { db_uri: uri }
8 | }
9 | pub async fn client(self) -> mongodb::Database {
10 | let conf = mongodb::options::ClientOptions::parse(self.db_uri)
11 | .await
12 | .unwrap();
13 | let client = mongodb::Client::with_options(conf).unwrap();
14 | client.database("tgbot")
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/database/db_utils.rs:
--------------------------------------------------------------------------------
1 | use super::{
2 | BlacklistFilter, BlacklistKind, Chat, DisableCommand, Filters, Gban, GbanStat, Logging,
3 | Reporting, User, Warn, WarnKind, Warnlimit,
4 | };
5 | use crate::{Cxt, TgErr};
6 | use mongodb::{bson::doc, Database};
7 | use teloxide::prelude::StreamExt;
8 | use teloxide::types::ChatKind;
9 |
10 | type DbResult = Result;
11 |
12 | fn user_collection(db: &Database) -> mongodb::Collection {
13 | db.collection("User")
14 | }
15 | fn chat_collection(db: &Database) -> mongodb::Collection {
16 | db.collection("Chats")
17 | }
18 | fn gban_collection(db: &Database) -> mongodb::Collection {
19 | db.collection("Gban")
20 | }
21 | fn warn_collection(db: &Database) -> mongodb::Collection {
22 | db.collection("Warn")
23 | }
24 | fn warn_kind_collection(db: &Database) -> mongodb::Collection {
25 | db.collection("WarnKind")
26 | }
27 | fn warn_limit_collection(db: &Database) -> mongodb::Collection {
28 | db.collection("Warnlimit")
29 | }
30 | fn gbanstat_collection(db: &Database) -> mongodb::Collection {
31 | db.collection("GbanStat")
32 | }
33 | fn disable_collection(db: &Database) -> mongodb::Collection {
34 | db.collection("DisableCommand")
35 | }
36 | fn chat_filters(db: &Database) -> mongodb::Collection {
37 | db.collection("ChatFilters")
38 | }
39 | fn chat_blacklist(db: &Database) -> mongodb::Collection {
40 | db.collection("ChatBlacklist")
41 | }
42 | fn chat_blacklist_mode(db: &Database) -> mongodb::Collection {
43 | db.collection("ChatBlacklistMode")
44 | }
45 | fn log_collection(db: &Database) -> mongodb::Collection {
46 | db.collection("Logchannel")
47 | }
48 | fn report_collection(db: &Database) -> mongodb::Collection {
49 | db.collection("Reporting")
50 | }
51 | pub async fn insert_user(db: &Database, us: &User) -> DbResult {
52 | let user = user_collection(db);
53 | user.update_one(
54 | doc! {"user_id":us.user_id},
55 | doc! {"$set":{"user_name":us.user_name.to_owned()}},
56 | mongodb::options::UpdateOptions::builder()
57 | .upsert(true)
58 | .build(),
59 | )
60 | .await
61 | }
62 | pub async fn get_userid_from_name(db: &Database, username: String) -> DbResult> {
63 | let user = user_collection(db);
64 | let id = user.find_one(doc! {"user_name":username}, None).await?;
65 | Ok(id.map(|u| u.user_id))
66 | }
67 |
68 | pub async fn save_user(cx: &Cxt, db: &Database) -> TgErr<()> {
69 | if let Some(user) = cx.update.from() {
70 | let uname = user.username.as_ref().map(|s| s.to_lowercase());
71 | let user = &User {
72 | user_id: user.id,
73 | user_name: uname.unwrap_or_else(|| "None".to_string()),
74 | };
75 | insert_user(db, user).await?;
76 | }
77 | Ok(())
78 | }
79 |
80 | pub async fn insert_chat(db: &Database, c: &Chat) -> DbResult {
81 | let chat = chat_collection(db);
82 | chat.update_one(
83 | doc! {"chat_id":&c.chat_id},
84 | doc! {"$set":{"chat_name":&c.chat_name}},
85 | mongodb::options::UpdateOptions::builder()
86 | .upsert(true)
87 | .build(),
88 | )
89 | .await
90 | }
91 |
92 | pub async fn get_all_chats(db: &Database) -> DbResult> {
93 | let chat = chat_collection(db);
94 | let cursor = chat.find(None, None).await?;
95 | let chats: Vec = cursor.map(|chat| chat.unwrap().chat_id).collect().await;
96 | Ok(chats)
97 | }
98 | pub async fn save_chat(cx: &Cxt, db: &Database) -> TgErr<()> {
99 | if cx.update.chat.is_chat() {
100 | let chat = &cx.update.chat;
101 | match &chat.kind {
102 | ChatKind::Public(ch) => {
103 | let c = Chat {
104 | chat_id: chat.id,
105 | chat_name: ch.title.clone().unwrap(),
106 | };
107 | insert_chat(db, &c).await?;
108 | }
109 | ChatKind::Private(_) => {}
110 | }
111 | }
112 | Ok(())
113 | }
114 |
115 | pub async fn gban_user(db: &Database, gb: &Gban) -> DbResult {
116 | let gban = gban_collection(db);
117 | gban.update_one(
118 | doc! {"user_id":&gb.user_id},
119 | doc! {"$set":{"reason":&gb.reason}},
120 | mongodb::options::UpdateOptions::builder()
121 | .upsert(true)
122 | .build(),
123 | )
124 | .await
125 | }
126 |
127 | pub async fn ungban_user(db: &Database, id: &i64) -> DbResult {
128 | let gban = gban_collection(db);
129 | gban.delete_one(doc! {"user_id":id}, None).await
130 | }
131 |
132 | pub async fn get_gban_reason(db: &Database, id: &i64) -> DbResult {
133 | let gban = gban_collection(db);
134 | let reason = gban.find_one(doc! {"user_id":id}, None).await?;
135 | Ok(reason.map(|r| r.reason).unwrap())
136 | }
137 |
138 | pub async fn is_gbanned(db: &Database, id: &i64) -> DbResult {
139 | let gban = gban_collection(db);
140 | let exist = gban.find_one(doc! {"user_id":id}, None).await?;
141 | Ok(exist.is_some())
142 | }
143 |
144 | pub async fn set_gbanstat(
145 | db: &Database,
146 | gs: &GbanStat,
147 | ) -> DbResult {
148 | let gbanstat = gbanstat_collection(db);
149 | gbanstat
150 | .update_one(
151 | doc! {"chat_id":gs.chat_id},
152 | doc! {"$set":{"is_on":gs.is_on}},
153 | mongodb::options::UpdateOptions::builder()
154 | .upsert(true)
155 | .build(),
156 | )
157 | .await
158 | }
159 |
160 | pub async fn get_gbanstat(db: &Database, id: i64) -> DbResult {
161 | let gbanstat = gbanstat_collection(db);
162 | let stat = gbanstat.find_one(doc! {"chat_id":id}, None).await?;
163 | if stat.is_none() {
164 | let gs = &GbanStat {
165 | chat_id: id,
166 | is_on: true,
167 | };
168 | set_gbanstat(db, gs).await?;
169 | return Ok(true);
170 | }
171 | Ok(stat.map(|d| d.is_on).unwrap())
172 | }
173 | pub async fn insert_warn(db: &Database, w: &Warn) -> DbResult {
174 | let warn = warn_collection(db);
175 | warn.update_one(
176 | doc! {"chat_id":w.chat_id},
177 | doc! {"$set":{"user_id":w.user_id,"reason":&w.reason,"count":w.count as i64}},
178 | mongodb::options::UpdateOptions::builder()
179 | .upsert(true)
180 | .build(),
181 | )
182 | .await
183 | }
184 |
185 | pub async fn get_warn_count(db: &Database, chat_id: i64, user_id: i64) -> DbResult {
186 | let warn = warn_collection(db);
187 | let count = warn
188 | .find_one(doc! {"chat_id":chat_id,"user_id":user_id}, None)
189 | .await?;
190 | Ok(count.map(|s| s.count as i64).unwrap_or(0_i64))
191 | }
192 |
193 | pub async fn set_warn_limit(
194 | db: &Database,
195 | wl: &Warnlimit,
196 | ) -> DbResult {
197 | let wc = warn_limit_collection(db);
198 | wc.update_one(
199 | doc! {"chat_id":wl.chat_id},
200 | doc! {"$set":{"limit":wl.limit as i64}},
201 | mongodb::options::UpdateOptions::builder()
202 | .upsert(true)
203 | .build(),
204 | )
205 | .await
206 | }
207 |
208 | pub async fn set_softwarn(
209 | db: &Database,
210 | wk: &WarnKind,
211 | ) -> DbResult {
212 | let wkc = warn_kind_collection(db);
213 | wkc.update_one(
214 | doc! {"chat_id":wk.chat_id},
215 | doc! {"$set":{"softwarn":wk.softwarn}},
216 | mongodb::options::UpdateOptions::builder()
217 | .upsert(true)
218 | .build(),
219 | )
220 | .await
221 | }
222 |
223 | pub async fn get_softwarn(db: &Database, id: i64) -> DbResult {
224 | let wkc = warn_kind_collection(db);
225 | let warn_kind = wkc.find_one(doc! {"chat_id":id}, None).await?;
226 | if warn_kind.is_none() {
227 | //Default
228 | let wk = &WarnKind {
229 | chat_id: id,
230 | softwarn: false,
231 | };
232 | set_softwarn(db, wk).await?;
233 | return Ok(false);
234 | }
235 | Ok(warn_kind.map(|d| d.softwarn).unwrap())
236 | }
237 |
238 | pub async fn get_warn_limit(db: &Database, id: i64) -> DbResult {
239 | let warn = warn_limit_collection(db);
240 | let warn_lim = warn.find_one(doc! {"chat_id":id}, None).await?;
241 | if warn_lim.is_none() {
242 | //set default limit to 3
243 | let wl = &Warnlimit {
244 | chat_id: id,
245 | limit: 3_u64,
246 | };
247 | set_warn_limit(db, wl).await?;
248 | Ok(3_i64)
249 | } else {
250 | Ok(warn_lim.map(|s| s.limit as i64).unwrap())
251 | }
252 | }
253 | pub async fn rm_single_warn(
254 | db: &Database,
255 | chat_id: i64,
256 | user_id: i64,
257 | ) -> DbResult {
258 | let warn = warn_collection(db);
259 | let count = get_warn_count(db, chat_id, user_id).await?;
260 | warn.update_one(
261 | doc! {"chat_id":chat_id},
262 | doc! {"$set":{"count":count-1}},
263 | mongodb::options::UpdateOptions::builder()
264 | .upsert(true)
265 | .build(),
266 | )
267 | .await
268 | }
269 | pub async fn reset_warn(
270 | db: &Database,
271 | chat_id: i64,
272 | user_id: i64,
273 | ) -> DbResult {
274 | let warn = warn_collection(db);
275 | warn.update_one(
276 | doc! {"chat_id":chat_id},
277 | doc! {"$set":{"user_id":user_id,"count":0_i64}},
278 | mongodb::options::UpdateOptions::builder()
279 | .upsert(true)
280 | .build(),
281 | )
282 | .await
283 | }
284 |
285 | pub async fn add_filter(db: &Database, fl: &Filters) -> DbResult {
286 | let fc = chat_filters(db);
287 | fc.update_one(
288 | doc! {"chat_id":fl.chat_id,"filter":&fl.filter},
289 | doc! {"$set":{"reply":&fl.reply,"f_type":&fl.f_type,"caption":&fl.caption}},
290 | mongodb::options::UpdateOptions::builder()
291 | .upsert(true)
292 | .build(),
293 | )
294 | .await
295 | }
296 | pub async fn get_reply_filter(db: &Database, chat_id: i64, filt: &str) -> DbResult> {
297 | let fc = chat_filters(db);
298 | let find = fc
299 | .find_one(doc! {"chat_id":chat_id,"filter":filt}, None)
300 | .await?;
301 | Ok(find.map(|f| (f.reply)))
302 | }
303 |
304 | pub async fn get_reply_type_filter(
305 | db: &Database,
306 | chat_id: i64,
307 | filt: &str,
308 | ) -> DbResult > {
309 | let fc = chat_filters(db);
310 | let find = fc
311 | .find_one(doc! {"chat_id":chat_id,"filter":filt}, None)
312 | .await?;
313 | Ok(find.map(|f| f.f_type))
314 | }
315 |
316 | pub async fn get_reply_caption(
317 | db: &Database,
318 | chat_id: i64,
319 | filt: &str,
320 | ) -> DbResult > {
321 | let fc = chat_filters(db);
322 | let find = fc
323 | .find_one(doc! {"chat_id":chat_id,"filter":filt}, None)
324 | .await?;
325 | Ok(find.map(|f| f.caption).unwrap_or(None))
326 | }
327 | pub async fn list_filters(db: &Database, chat_id: i64) -> DbResult> {
328 | let fc = chat_filters(db);
329 | let dist = fc
330 | .distinct("filter", doc! {"chat_id":chat_id}, None)
331 | .await?;
332 | Ok(dist.iter().map(|s| s.to_string()).collect())
333 | }
334 | pub async fn rm_filter(
335 | db: &Database,
336 | chat_id: i64,
337 | fit: &str,
338 | ) -> DbResult {
339 | let fc = chat_filters(db);
340 | fc.delete_one(doc! {"chat_id":chat_id,"filter":fit}, None)
341 | .await
342 | }
343 | pub async fn add_blacklist(
344 | db: &Database,
345 | bl: &BlacklistFilter,
346 | ) -> DbResult {
347 | let blc = chat_blacklist(db);
348 | blc.update_one(
349 | doc! {"chat_id":bl.chat_id},
350 | doc! {"$set":{"blacklist":&bl.filter}},
351 | mongodb::options::UpdateOptions::builder()
352 | .upsert(true)
353 | .build(),
354 | )
355 | .await
356 | }
357 | pub async fn get_blacklist(db: &Database, chat_id: i64) -> DbResult> {
358 | let blc = chat_blacklist(db);
359 | let find = blc
360 | .distinct("blacklist", doc! {"chat_id":chat_id}, None)
361 | .await?;
362 | Ok(find.iter().map(|b| b.to_string()).collect())
363 | }
364 | pub async fn rm_blacklist(
365 | db: &Database,
366 | bl: &BlacklistFilter,
367 | ) -> DbResult {
368 | let blc = chat_blacklist(db);
369 | blc.delete_one(doc! {"chat_id":bl.chat_id,"blacklist":&bl.filter}, None)
370 | .await
371 | }
372 | pub async fn set_blacklist_mode(
373 | db: &Database,
374 | bm: &BlacklistKind,
375 | ) -> DbResult {
376 | let blc = chat_blacklist_mode(db);
377 | blc.update_one(
378 | doc! {"chat_id":bm.chat_id},
379 | doc! {"$set":{"kind":&bm.kind}},
380 | mongodb::options::UpdateOptions::builder()
381 | .upsert(true)
382 | .build(),
383 | )
384 | .await
385 | }
386 | pub async fn get_blacklist_mode(db: &Database, id: i64) -> DbResult {
387 | let blc = chat_blacklist_mode(db);
388 | let fi = blc.find_one(doc! {"chat_id":id}, None).await?;
389 | if fi.is_none() {
390 | let blk = &BlacklistKind {
391 | chat_id: id,
392 | kind: String::from("delete"),
393 | };
394 | set_blacklist_mode(db, blk).await?;
395 | return Ok(String::from("delete"));
396 | }
397 | Ok(fi.map(|b| b.kind).unwrap())
398 | }
399 | pub async fn disable_command(
400 | db: &Database,
401 | dc: &DisableCommand,
402 | ) -> DbResult {
403 | let disable_coll = disable_collection(db);
404 | disable_coll
405 | .update_one(
406 | doc! {"chat_id":dc.chat_id},
407 | doc! {"$set":{"disabled_commands": dc.disabled_commands.clone()}},
408 | mongodb::options::UpdateOptions::builder()
409 | .upsert(true)
410 | .build(),
411 | )
412 | .await
413 | }
414 |
415 | pub async fn get_disabled_command(db: &Database, id: i64) -> DbResult> {
416 | let dc = disable_collection(db);
417 | let f = dc.find_one(doc! {"chat_id":id}, None).await?;
418 | if f.is_none() {
419 | let dc = &DisableCommand {
420 | chat_id: id,
421 | disabled_commands: Vec::new(),
422 | };
423 | disable_command(db, dc).await?;
424 | return Ok(Vec::new());
425 | }
426 |
427 | Ok(f.map(|d| d.disabled_commands.into_iter().collect())
428 | .unwrap())
429 | }
430 |
431 | pub async fn add_log_channel(
432 | db: &Database,
433 | lg: &Logging,
434 | ) -> DbResult {
435 | let lc = log_collection(db);
436 | lc.update_one(
437 | doc! {"chat_id":lg.chat_id},
438 | doc! {"$set":{"channel":lg.channel}},
439 | mongodb::options::UpdateOptions::builder()
440 | .upsert(true)
441 | .build(),
442 | )
443 | .await
444 | }
445 |
446 | pub async fn rm_log_channel(db: &Database, id: i64) -> DbResult {
447 | let lc = log_collection(db);
448 | lc.delete_one(doc! {"chat_id":id}, None).await
449 | }
450 |
451 | pub async fn get_log_channel(db: &Database, id: i64) -> DbResult> {
452 | let lc = log_collection(db);
453 | let fi = lc.find_one(doc! {"chat_id":id}, None).await?;
454 | Ok(fi.map(|l| l.channel))
455 | }
456 |
457 | pub async fn set_report_setting(
458 | db: &Database,
459 | r: &Reporting,
460 | ) -> DbResult {
461 | let rc = report_collection(db);
462 | rc.update_one(
463 | doc! {"chat_id":r.chat_id},
464 | doc! {"$set":{"allowed":r.allowed}},
465 | mongodb::options::UpdateOptions::builder()
466 | .upsert(true)
467 | .build(),
468 | )
469 | .await
470 | }
471 |
472 | pub async fn get_report_setting(db: &Database, chat_id: i64) -> DbResult {
473 | let rc = report_collection(db);
474 | let find = rc.find_one(doc! {"chat_id":chat_id}, None).await?;
475 | Ok(find.map(|r| r.allowed).unwrap_or(false))
476 | }
477 |
--------------------------------------------------------------------------------
/src/database/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod db;
2 | pub mod db_utils;
3 |
4 | pub use db::Db;
5 | use serde::{Deserialize, Serialize};
6 |
7 | #[derive(Serialize, Deserialize)]
8 | pub struct User {
9 | pub user_id: i64,
10 | pub user_name: String,
11 | }
12 | #[derive(Serialize, Deserialize)]
13 | pub struct Chat {
14 | pub chat_id: i64,
15 | pub chat_name: String,
16 | }
17 | #[derive(Serialize, Deserialize)]
18 | pub struct Gban {
19 | pub user_id: i64,
20 | pub reason: String,
21 | }
22 | #[derive(Serialize, Deserialize)]
23 | pub struct GbanStat {
24 | pub chat_id: i64,
25 | pub is_on: bool,
26 | }
27 | #[derive(Serialize, Deserialize)]
28 | pub struct Warn {
29 | pub chat_id: i64,
30 | pub user_id: i64,
31 | pub reason: String,
32 | pub count: u64,
33 | }
34 | #[derive(Serialize, Deserialize)]
35 | pub struct WarnKind {
36 | pub chat_id: i64,
37 | pub softwarn: bool,
38 | }
39 | #[derive(Serialize, Deserialize)]
40 | pub struct Warnlimit {
41 | pub chat_id: i64,
42 | pub limit: u64,
43 | }
44 | #[derive(Serialize, Deserialize)]
45 | pub struct DisableCommand {
46 | pub chat_id: i64,
47 | pub disabled_commands: Vec,
48 | }
49 |
50 | #[derive(Serialize, Deserialize)]
51 | pub struct Filters {
52 | pub chat_id: i64,
53 | pub filter: String,
54 | pub reply: String,
55 | pub caption: Option,
56 | pub f_type: String,
57 | }
58 | #[derive(Serialize, Deserialize)]
59 | pub struct BlacklistFilter {
60 | pub chat_id: i64,
61 | pub filter: String,
62 | }
63 | #[derive(Serialize, Deserialize)]
64 | pub struct BlacklistKind {
65 | pub chat_id: i64,
66 | pub kind: String,
67 | }
68 |
69 | #[derive(Serialize, Deserialize)]
70 | pub struct Logging {
71 | pub chat_id: i64,
72 | pub channel: i64,
73 | }
74 |
75 | #[derive(Serialize, Deserialize)]
76 | pub struct Reporting {
77 | pub chat_id: i64,
78 | pub allowed: bool,
79 | }
80 |
--------------------------------------------------------------------------------
/src/main.rs:
--------------------------------------------------------------------------------
1 | extern crate teloxide;
2 | mod database;
3 | mod modules;
4 | mod util;
5 | use crate::util::{consts, enforce_gban};
6 | use async_once::AsyncOnce;
7 | use database::db_utils::{save_chat, save_user};
8 | use database::Db;
9 | use lazy_static::lazy_static;
10 | use modules::*;
11 | use regex::Regex;
12 | use std::error::Error;
13 | use teloxide::prelude::*;
14 | use teloxide::utils::command::{parse_command, BotCommand as Cmd};
15 | use tokio_stream::wrappers::UnboundedReceiverStream;
16 |
17 | pub type Cxt = UpdateWithCx, Message>;
18 | pub type Ctx = UpdateWithCx, CallbackQuery>;
19 | pub type TgErr = anyhow::Result;
20 |
21 | lazy_static! {
22 | pub static ref MONGO_URI: String = dotenv::var("MONGO_URI").expect("MONGO_URI is not defined");
23 | pub static ref OWNER_ID: i64 = dotenv::var("OWNER_ID")
24 | .expect("OWNER_ID is not defined")
25 | .parse::()
26 | .unwrap_or(0);
27 | pub static ref BOT_TOKEN: String =
28 | dotenv::var("TELOXIDE_TOKEN").expect("TELOXIDE_TOKEN is empty");
29 | pub static ref SUDO_USERS: Vec = dotenv::var("SUDO_USERS")
30 | .expect("SUDO_USERS is not defined")
31 | .split(',')
32 | .map(|s| s.parse::().unwrap_or(0))
33 | .collect::>();
34 | pub static ref MDB: AsyncOnce =
35 | AsyncOnce::new(async { Db::new(MONGO_URI.to_owned()).client().await });
36 | }
37 | async fn get_mdb() -> mongodb::Database {
38 | MDB.get().await.clone()
39 | }
40 | async fn answer(cx: Cxt) -> Result<(), Box> {
41 | let mngdb = get_mdb().await;
42 | tokio::try_join!(save_user(&cx, &mngdb), save_chat(&cx, &mngdb))?;
43 |
44 | /*
45 | Gban and Chat Triggers
46 | */
47 | if cx.update.chat.is_group() || cx.update.chat.is_supergroup() {
48 | tokio::try_join!(enforce_gban(&cx))?;
49 | action_blacklist(&cx).await?;
50 | filter_reply(&cx).await?;
51 | }
52 | let txt = cx.update.text();
53 | if txt.is_none() {
54 | return Ok(());
55 | }
56 | let command = Cmd::parse(txt.unwrap(), consts::BOT_NAME);
57 | if let Ok(c) = command {
58 | let (cmnd, _) = parse_command(txt.unwrap(), consts::BOT_NAME).unwrap();
59 | match c {
60 | Command::Ban => {
61 | ban(&cx).await?;
62 | }
63 | Command::Tban => temp_ban(&cx).await?,
64 | Command::Unban => unban(&cx).await?,
65 | Command::Mute => mute(&cx).await?,
66 | Command::Tmute => temp_mute(&cx).await?,
67 | Command::Unmute => unmute(&cx).await?,
68 | Command::Start => start_handler(&cx, cmnd).await?,
69 | Command::Help => help_handler(&cx).await?,
70 | Command::Kick => kick(&cx).await?,
71 | Command::Kickme => kickme(&cx, cmnd).await?,
72 | Command::Info => info(&cx, cmnd).await?,
73 | Command::Id => get_id(&cx).await?,
74 | Command::Pin => pin(&cx).await?,
75 | Command::Unpin => unpin(&cx).await?,
76 | Command::Promote => promote(&cx).await?,
77 | Command::Demote => demote(&cx).await?,
78 | Command::Invitelink => invitelink(&cx).await?,
79 | Command::Adminlist => adminlist(&cx, cmnd).await?,
80 | Command::Purge => purge(&cx).await?,
81 | Command::Del => delete(&cx).await?,
82 | Command::Leavechat => leavechat(&cx).await?,
83 | Command::Ud => ud(&cx, cmnd).await?,
84 | Command::Paste => katbin(&cx, cmnd).await?,
85 | Command::Echo => echo(&cx, cmnd).await?,
86 | Command::Lock => lock(&cx).await?,
87 | Command::Unlock => unlock(&cx).await?,
88 | Command::Locktypes => locktypes(&cx).await?,
89 | Command::Chatlist => chatlist(&cx).await?,
90 | Command::Gban => gban(&cx).await?,
91 | Command::Ungban => ungban(&cx).await?,
92 | Command::Gbanstat => gbanstat(&cx).await?,
93 | Command::Warn => warn(&cx).await?,
94 | Command::Warnlimit => warn_limit(&cx).await?,
95 | Command::Warnmode => warnmode(&cx).await?,
96 | Command::Resetwarns => reset_warns(&cx).await?,
97 | Command::Warns => warns(&cx).await?,
98 | Command::Disable => disable(&cx).await?,
99 | Command::Enable => enable(&cx).await?,
100 | Command::Filter => filter(&cx).await?,
101 | Command::Filters => filter_list(&cx).await?,
102 | Command::Stop => remove_filter(&cx).await?,
103 | Command::Addblacklist => blacklist_filter(&cx).await?,
104 | Command::Blacklists => list_blacklist(&cx).await?,
105 | Command::Rmblacklist => remove_blacklist(&cx).await?,
106 | Command::Blacklistmode => set_blacklist_kind(&cx).await?,
107 | Command::Setchatpic => set_chatpic(&cx).await?,
108 | Command::Setchattitle => set_chat_tile(&cx).await?,
109 | Command::Setlog => add_logc(&cx).await?,
110 | Command::Unsetlog => remove_log(&cx).await?,
111 | Command::Report => report(&cx).await?,
112 | Command::Reports => report_set(&cx).await?,
113 | }
114 | }
115 | Ok(())
116 | }
117 | async fn answer_callback(cx: Ctx) -> TgErr<()> {
118 | let data = &cx.update.data;
119 | if let Some(d) = data {
120 | let warn_re = Regex::new(r#"rm_warn\((.+?)\)"#).unwrap();
121 | if warn_re.is_match(d) {
122 | handle_unwarn_button(&cx).await?;
123 | }
124 | }
125 | Ok(())
126 | }
127 | async fn run() {
128 | dotenv::dotenv().ok();
129 | teloxide::enable_logging!();
130 | let bot = Bot::from_env().auto_send();
131 | log::info!("Bot started");
132 | Dispatcher::new(bot)
133 | .messages_handler(|rx: DispatcherHandlerRx, Message>| {
134 | UnboundedReceiverStream::new(rx).for_each_concurrent(None, |cx| async move {
135 | answer(cx).await.log_on_error().await
136 | })
137 | })
138 | .callback_queries_handler(|rx: DispatcherHandlerRx, CallbackQuery>| {
139 | UnboundedReceiverStream::new(rx).for_each_concurrent(None, |cx| async move {
140 | answer_callback(cx).await.log_on_error().await
141 | })
142 | })
143 | .setup_ctrlc_handler()
144 | .dispatch()
145 | .await;
146 | }
147 | #[tokio::main]
148 | async fn main() {
149 | run().await;
150 | }
151 |
--------------------------------------------------------------------------------
/src/modules/admin.rs:
--------------------------------------------------------------------------------
1 | use crate::database::db_utils::{get_report_setting, set_report_setting};
2 | use crate::database::Reporting;
3 | use crate::util::{
4 | can_pin_messages, can_promote_members, check_command_disabled, consts,
5 | extract_text_id_from_reply, get_bot_id, get_chat_title, is_group, is_user_admin,
6 | user_should_be_admin, PinMode, ReportStatus,
7 | };
8 | use crate::{get_mdb, Cxt, TgErr, OWNER_ID, SUDO_USERS};
9 | use std::str::FromStr;
10 | use teloxide::payloads::SendMessageSetters;
11 | use teloxide::prelude::*;
12 | use teloxide::types::{ChatKind, ParseMode};
13 | use teloxide::utils::command::parse_command;
14 | use teloxide::utils::html::{self, user_mention, user_mention_or_link};
15 |
16 | pub async fn pin(cx: &Cxt) -> TgErr<()> {
17 | tokio::try_join!(
18 | is_group(cx),
19 | can_pin_messages(cx, get_bot_id(cx).await),
20 | can_pin_messages(cx, cx.update.from().unwrap().id)
21 | )?;
22 | let (_, args) = parse_command(cx.update.text().unwrap(), consts::BOT_NAME).unwrap();
23 | if let Some(mes) = cx.update.reply_to_message() {
24 | let pinmsg = html::link(mes.url().unwrap().as_str(), "this message");
25 | if !args.is_empty() {
26 | let pinmode = PinMode::from_str(&args[0].to_lowercase()).unwrap();
27 | match pinmode {
28 | PinMode::Loud => {
29 | cx.requester
30 | .pin_chat_message(cx.chat_id(), mes.id)
31 | .disable_notification(false)
32 | .await?;
33 | cx.reply_to(format!("Pinned {} Loudly", &pinmsg))
34 | .disable_web_page_preview(true)
35 | .parse_mode(ParseMode::Html)
36 | .await?;
37 | }
38 | PinMode::Silent => {
39 | cx.requester
40 | .pin_chat_message(cx.chat_id(), mes.id)
41 | .disable_notification(true)
42 | .await?;
43 | cx.reply_to(format!("Pinned {} Silently", &pinmsg))
44 | .disable_web_page_preview(true)
45 | .parse_mode(ParseMode::Html)
46 | .await?;
47 | }
48 | PinMode::Error => {
49 | cx.reply_to("Invalid PinMode! Available pinmodes are loud,hard,violent,silent")
50 | .await?;
51 | }
52 | }
53 | } else {
54 | cx.requester
55 | .pin_chat_message(cx.chat_id(), mes.id)
56 | .disable_notification(false)
57 | .await?;
58 | cx.reply_to(format!("Pinned {}", &pinmsg))
59 | .disable_web_page_preview(true)
60 | .parse_mode(ParseMode::Html)
61 | .await?;
62 | }
63 | } else {
64 | cx.reply_to("Reply to some message to pin").await?;
65 | }
66 | Ok(())
67 | }
68 |
69 | pub async fn unpin(cx: &Cxt) -> TgErr<()> {
70 | tokio::try_join!(
71 | is_group(cx),
72 | can_pin_messages(cx, get_bot_id(cx).await),
73 | can_pin_messages(cx, cx.update.from().unwrap().id),
74 | )?;
75 | if let Some(mes) = cx.update.reply_to_message() {
76 | match cx
77 | .requester
78 | .unpin_chat_message(cx.chat_id())
79 | .message_id(mes.id as i32)
80 | .await
81 | {
82 | Ok(_) => {
83 | cx.reply_to(format!(
84 | "Unpinned {}",
85 | html::link(mes.url().unwrap().as_str(), "this message")
86 | ))
87 | .disable_web_page_preview(true)
88 | .parse_mode(ParseMode::Html)
89 | .await?;
90 | }
91 | Err(_) => {
92 | cx.reply_to("The mentioned message was never pinned")
93 | .await?;
94 | }
95 | }
96 | } else {
97 | match cx.requester.unpin_all_chat_messages(cx.chat_id()).await {
98 | Ok(_) => {
99 | cx.reply_to("Unpinned all chat messages").await?;
100 | }
101 | Err(_) => {
102 | cx.reply_to("What are you trying to unpin").await?;
103 | }
104 | }
105 | }
106 | Ok(())
107 | }
108 |
109 | pub async fn promote(cx: &Cxt) -> TgErr<()> {
110 | tokio::try_join!(
111 | is_group(cx),
112 | can_promote_members(cx, get_bot_id(cx).await),
113 | can_promote_members(cx, cx.update.from().unwrap().id)
114 | )?;
115 | let (user_id, text) = extract_text_id_from_reply(cx).await;
116 | let botmem = cx
117 | .requester
118 | .get_chat_member(cx.chat_id(), get_bot_id(cx).await)
119 | .await?;
120 | if user_id.is_none() {
121 | cx.reply_to("Mention someone to promote").await?;
122 | return Ok(());
123 | }
124 | if let Ok(chatmem) = cx
125 | .requester
126 | .get_chat_member(cx.chat_id(), user_id.unwrap())
127 | .await
128 | {
129 | if chatmem.is_owner() {
130 | cx.reply_to("Mate the user is the creator of the group")
131 | .await?;
132 | return Ok(());
133 | }
134 | let promote_text = if chatmem.is_administrator() {
135 | if !chatmem.kind.can_be_edited() {
136 | cx.reply_to("I dont have enough rights to update the user's permissons!")
137 | .await?;
138 | return Ok(());
139 | }
140 | format!(
141 | "Admin Permissions has been updated for\n User: {}",
142 | user_mention_or_link(&chatmem.user)
143 | )
144 | } else {
145 | format!(
146 | "Promoted\nUser: {}",
147 | user_mention_or_link(&chatmem.user)
148 | )
149 | };
150 | cx.requester
151 | .promote_chat_member(cx.chat_id(), user_id.unwrap())
152 | .can_manage_chat(botmem.can_manage_chat())
153 | .can_change_info(botmem.can_change_info())
154 | .can_delete_messages(botmem.can_delete_messages())
155 | .can_invite_users(botmem.can_invite_users())
156 | .can_restrict_members(botmem.can_restrict_members())
157 | .can_pin_messages(botmem.can_pin_messages())
158 | .await?;
159 | if text.is_some() {
160 | cx.requester
161 | .set_chat_administrator_custom_title(cx.chat_id(), user_id.unwrap(), text.unwrap())
162 | .await?;
163 | }
164 | cx.reply_to(promote_text)
165 | .parse_mode(ParseMode::Html)
166 | .await?;
167 | } else {
168 | cx.reply_to("Who are you trying to promote? He is not even in the group")
169 | .await?;
170 | }
171 | Ok(())
172 | }
173 |
174 | pub async fn demote(cx: &Cxt) -> TgErr<()> {
175 | tokio::try_join!(
176 | is_group(cx),
177 | can_promote_members(cx, get_bot_id(cx).await),
178 | can_promote_members(cx, cx.update.from().unwrap().id)
179 | )?;
180 | let (user_id, _) = extract_text_id_from_reply(cx).await;
181 | if user_id.is_none() {
182 | cx.reply_to("Mention a user to demote").await?;
183 | return Ok(());
184 | }
185 |
186 | if user_id.unwrap() == *OWNER_ID || (*SUDO_USERS).contains(&user_id.unwrap()) {
187 | cx.reply_to("I can't kick the people who created me! I got loyalty")
188 | .await?;
189 | return Ok(());
190 | }
191 | if let Ok(chatmem) = cx
192 | .requester
193 | .get_chat_member(cx.chat_id(), user_id.unwrap())
194 | .await
195 | {
196 | if chatmem.is_owner() {
197 | cx.reply_to("This user is the Creator of the group, How can I possibly demote them")
198 | .await?;
199 | return Ok(());
200 | }
201 |
202 | if !chatmem.is_administrator() {
203 | cx.reply_to("The user has to admin in the first place to demote")
204 | .await?;
205 | return Ok(());
206 | }
207 |
208 | if chatmem.kind.can_be_edited() {
209 | cx.requester
210 | .promote_chat_member(cx.chat_id(), user_id.unwrap())
211 | .can_manage_chat(false)
212 | .can_change_info(false)
213 | .can_delete_messages(false)
214 | .can_manage_voice_chats(false)
215 | .can_invite_users(false)
216 | .can_restrict_members(false)
217 | .can_pin_messages(false)
218 | .can_promote_members(false)
219 | .await?;
220 | cx.reply_to(format!(
221 | "Demoted Successfully\nUser: {}",
222 | user_mention_or_link(&chatmem.user)
223 | ))
224 | .parse_mode(ParseMode::Html)
225 | .await?;
226 | } else {
227 | cx.reply_to("I don't seem to have enough rights to demote this user")
228 | .await?;
229 | return Ok(());
230 | }
231 | } else {
232 | cx.reply_to("Who are you trying demote?").await?;
233 | }
234 | Ok(())
235 | }
236 |
237 | pub async fn invitelink(cx: &Cxt) -> TgErr<()> {
238 | tokio::try_join!(
239 | is_group(cx),
240 | user_should_be_admin(cx, cx.update.from().unwrap().id)
241 | )?;
242 | let chat = &cx.update.chat;
243 | match &chat.kind {
244 | ChatKind::Public(c) => {
245 | if c.invite_link.is_some() {
246 | cx.reply_to(format!(
247 | "Here's the invite link of the chat \n{}",
248 | c.invite_link.as_ref().unwrap()
249 | ))
250 | .parse_mode(ParseMode::Html)
251 | .await?;
252 | } else if let Ok(inv) = cx.requester.export_chat_invite_link(cx.chat_id()).await {
253 | cx.reply_to(format!(
254 | "The invitelink was empty so I have created one for this chat \n{}",
255 | inv
256 | ))
257 | .parse_mode(ParseMode::Html)
258 | .await?;
259 | } else {
260 | cx.reply_to("I don't have enough rights to access the invite link")
261 | .await?;
262 | }
263 | }
264 | ChatKind::Private(_) => {
265 | cx.reply_to("I can only create invite links for chats or channels")
266 | .await?;
267 | }
268 | }
269 | Ok(())
270 | }
271 |
272 | pub async fn adminlist(cx: &Cxt, cmd: &str) -> TgErr<()> {
273 | tokio::try_join!(is_group(cx), check_command_disabled(cx, String::from(cmd)))?;
274 | let chatmem = cx.requester.get_chat_administrators(cx.chat_id()).await?;
275 | let adminlist = chatmem
276 | .iter()
277 | .map(|mem| format!("- {}", user_mention(mem.user.id, &mem.user.full_name())))
278 | .collect::>();
279 | cx.reply_to(format!(
280 | "Admin's in this group: \n{}",
281 | adminlist.join("\n")
282 | ))
283 | .parse_mode(ParseMode::Html)
284 | .await?;
285 | Ok(())
286 | }
287 |
288 | pub async fn report_set(cx: &Cxt) -> TgErr<()> {
289 | tokio::try_join!(is_group(cx))?;
290 | let db = get_mdb().await;
291 | let (_, arg) = parse_command(cx.update.text().unwrap(), consts::BOT_NAME).unwrap();
292 | if arg.is_empty() {
293 | cx.reply_to(format!(
294 | "Invalid option!\nUsage: {}",
295 | html::code_inline("/reports on/off/yes/no")
296 | ))
297 | .parse_mode(ParseMode::Html)
298 | .await?;
299 | return Ok(());
300 | }
301 | let option = arg[0].to_lowercase().parse::().unwrap();
302 | match option {
303 | ReportStatus::On => {
304 | let r = Reporting {
305 | chat_id: cx.chat_id(),
306 | allowed: true,
307 | };
308 | set_report_setting(&db, &r).await?;
309 | cx.reply_to("Reporting has been turned on for this chat now user's can report any users by sending /report").await?;
310 | }
311 | ReportStatus::Off => {
312 | let r = Reporting {
313 | chat_id: cx.chat_id(),
314 | allowed: false,
315 | };
316 | set_report_setting(&db, &r).await?;
317 | cx.reply_to("Reporting has been turned on for this chat now user's can report any users by sending /report").await?;
318 | }
319 | ReportStatus::Error => {
320 | cx.reply_to(format!(
321 | "Invalid option!\nUsage: {}",
322 | html::code_inline("/reports on/off")
323 | ))
324 | .parse_mode(ParseMode::Html)
325 | .await?;
326 | }
327 | }
328 | Ok(())
329 | }
330 | pub async fn report(cx: &Cxt) -> TgErr<()> {
331 | tokio::try_join!(is_group(cx))?;
332 | let db = get_mdb().await;
333 |
334 | // Early return if the reporting is false in a group or someone trying to bluetext spam
335 | if !get_report_setting(&db, cx.chat_id()).await? || cx.update.reply_to_message().is_none() {
336 | return Ok(());
337 | }
338 | let repo_msg = cx.update.reply_to_message().unwrap();
339 | let culprit = repo_msg.from().unwrap();
340 |
341 | if culprit.id == get_bot_id(cx).await {
342 | cx.reply_to("I am not reporting myself you cretin").await?;
343 | return Ok(());
344 | }
345 |
346 | //User is reporting himself, spam?
347 | if culprit.id == cx.update.from().unwrap().id {
348 | cx.reply_to("Why are you reporting yourself").await?;
349 | return Ok(());
350 | }
351 |
352 | //Ignore if user is trying to report an admin
353 | if is_user_admin(cx, culprit.id).await {
354 | return Ok(());
355 | }
356 |
357 | let adminlist = cx.requester.get_chat_administrators(cx.chat_id()).await?;
358 | let report_msg = format!(
359 | "Chat Title: {}\nReport Message: {}\nUser: {}\nReported User: {}",
360 | html::code_inline(get_chat_title(cx, cx.chat_id()).await.unwrap().as_str()),
361 | html::link(repo_msg.url().unwrap().as_str(), "this message"),
362 | html::user_mention(culprit.id, &culprit.full_name()),
363 | html::user_mention(
364 | cx.update.from().unwrap().id,
365 | cx.update.from().unwrap().full_name().as_str()
366 | )
367 | );
368 | for ad in adminlist {
369 | //Can't message a bot
370 | if ad.user.is_bot {
371 | continue;
372 | }
373 | //Forward the reported message to the admin and don't bother if there's an error
374 | cx.requester
375 | .forward_message(ad.user.id, cx.chat_id(), repo_msg.id)
376 | .await
377 | .ok();
378 |
379 | //Send the report and don't bother if there's any error
380 | cx.requester
381 | .send_message(ad.user.id, &report_msg)
382 | .parse_mode(ParseMode::Html)
383 | .disable_web_page_preview(true)
384 | .await
385 | .ok();
386 | }
387 | cx.reply_to(format!(
388 | "Reported {} to admins",
389 | html::user_mention(culprit.id, &culprit.full_name())
390 | ))
391 | .parse_mode(ParseMode::Html)
392 | .await?;
393 | Ok(())
394 | }
395 |
--------------------------------------------------------------------------------
/src/modules/bans.rs:
--------------------------------------------------------------------------------
1 | use chrono::{DateTime, NaiveDateTime, Utc};
2 | use teloxide::{
3 | payloads::{KickChatMemberSetters, SendMessageSetters},
4 | prelude::{GetChatId, Requester},
5 | types::ParseMode,
6 | utils::html::{self, user_mention_or_link},
7 | };
8 |
9 | use crate::{
10 | database::db_utils::get_log_channel,
11 | get_mdb,
12 | modules::send_log,
13 | util::{
14 | check_command_disabled, extract_text_id_from_reply, get_bot_id, get_chat_title, get_time,
15 | is_group, sudo_or_owner_filter, user_should_restrict, TimeUnit,
16 | },
17 | Cxt, TgErr, OWNER_ID, SUDO_USERS,
18 | };
19 |
20 | pub async fn ban(cx: &Cxt) -> TgErr<()> {
21 | tokio::try_join!(
22 | is_group(cx), //Should be a group
23 | user_should_restrict(cx, get_bot_id(cx).await), //Bot Should have restrict rights
24 | user_should_restrict(cx, cx.update.from().unwrap().id), //User should have restrict rights
25 | )?;
26 | let db = get_mdb().await;
27 | let bot_id = get_bot_id(cx).await;
28 | let (user_id, text) = extract_text_id_from_reply(cx).await;
29 | let reason = text.unwrap_or_else(|| String::from("None"));
30 | if user_id.is_none() {
31 | cx.reply_to("No user was targeted").await?;
32 | return Ok(());
33 | }
34 | if user_id.unwrap() == bot_id {
35 | cx.reply_to("I am not gonna ban myself fella! Try using your brain next time!")
36 | .await?;
37 | return Ok(());
38 | }
39 |
40 | if user_id.unwrap() == *OWNER_ID || (*SUDO_USERS).contains(&user_id.unwrap()) {
41 | cx.reply_to("I am not gonna ban my owner or my sudo users")
42 | .await?;
43 | return Ok(());
44 | }
45 | if let Ok(mem) = cx
46 | .requester
47 | .get_chat_member(cx.chat_id(), user_id.unwrap())
48 | .await
49 | {
50 | if mem.is_banned() {
51 | cx.reply_to("This user is already banned here!").await?;
52 | return Ok(());
53 | }
54 | if !mem.can_be_edited() {
55 | cx.reply_to("I am not gonna ban an Admin Here!").await?;
56 | return Ok(());
57 | }
58 | } else {
59 | cx.reply_to("I can't seem to get info for this user")
60 | .await?;
61 | return Ok(());
62 | };
63 | let user = cx
64 | .requester
65 | .get_chat_member(cx.chat_id(), user_id.unwrap())
66 | .await
67 | .unwrap()
68 | .user;
69 | let ban_text = format!(
70 | "Banned \nUser: {}\n\nReason: {}",
71 | user_mention_or_link(&user),
72 | reason
73 | );
74 | cx.requester
75 | .kick_chat_member(cx.chat_id(), user_id.unwrap())
76 | .await?;
77 | cx.reply_to(ban_text).parse_mode(ParseMode::Html).await?;
78 |
79 | if let Some(l) = get_log_channel(&db, cx.chat_id()).await? {
80 | let admin = cx
81 | .requester
82 | .get_chat_member(cx.chat_id(), cx.update.from().unwrap().id)
83 | .await?
84 | .user;
85 | let user = cx
86 | .requester
87 | .get_chat_member(cx.chat_id(), user_id.unwrap())
88 | .await?
89 | .user;
90 | let logm = format!(
91 | "Chat Title: {}\n#BANNED\nAdmin: {}\nUser: {}",
92 | html::code_inline(&get_chat_title(cx, cx.chat_id()).await.unwrap()),
93 | html::user_mention(admin.id, &admin.full_name()),
94 | html::user_mention(user_id.unwrap(), &user.full_name())
95 | );
96 | send_log(cx, &logm, l).await?;
97 | }
98 | Ok(())
99 | }
100 |
101 | pub async fn temp_ban(cx: &Cxt) -> TgErr<()> {
102 | tokio::try_join!(
103 | is_group(cx), //Should be a group
104 | user_should_restrict(cx, get_bot_id(cx).await), //Bot Should have restrict rights
105 | user_should_restrict(cx, cx.update.from().unwrap().id), //User should have restrict rights
106 | )?;
107 | let (user_id, text) = extract_text_id_from_reply(cx).await;
108 | let bot_id = get_bot_id(cx).await;
109 | let db = get_mdb().await;
110 | if user_id.is_none() {
111 | cx.reply_to("No user was targetted").await?;
112 | return Ok(());
113 | }
114 |
115 | if text.is_none() {
116 | cx.reply_to("Mention muting time in s,m,h,d").await?;
117 | return Ok(());
118 | }
119 |
120 | if user_id.unwrap() == bot_id {
121 | cx.reply_to("I am not gonna ban myself fella! Try using your brain next time!")
122 | .await?;
123 | return Ok(());
124 | }
125 | if user_id.unwrap() == *OWNER_ID || (*SUDO_USERS).contains(&user_id.unwrap()) {
126 | cx.reply_to("I am not gonna ban my owner or my sudo users")
127 | .await?;
128 | return Ok(());
129 | }
130 |
131 | if let Ok(mem) = cx
132 | .requester
133 | .get_chat_member(cx.chat_id(), user_id.unwrap())
134 | .await
135 | {
136 | if !mem.can_be_edited() {
137 | cx.reply_to("I am not gonna ban an admin here").await?;
138 | return Ok(());
139 | }
140 |
141 | if mem.is_banned() {
142 | cx.reply_to("This user is already banned").await?;
143 | return Ok(());
144 | }
145 |
146 | if sudo_or_owner_filter(user_id.unwrap()).await.is_ok() {
147 | cx.reply_to("This user is either my owner or my sudo user I am not gonna ban him")
148 | .await?;
149 | return Ok(());
150 | }
151 |
152 | if user_id.unwrap() == get_bot_id(cx).await {
153 | cx.reply_to("I am not gonna ban myself you idiot!").await?;
154 | return Ok(());
155 | }
156 | let u = text.unwrap().parse::();
157 | if u.is_err() {
158 | cx.reply_to("Please specify with proper unit: s,m,h,d")
159 | .await?;
160 | return Ok(());
161 | }
162 | let t = get_time(u.as_ref().unwrap());
163 | cx.requester
164 | .kick_chat_member(cx.chat_id(), user_id.unwrap())
165 | .until_date(
166 | DateTime::::from_utc(
167 | NaiveDateTime::from_timestamp(cx.update.date as i64, 0),
168 | Utc,
169 | ) + t,
170 | )
171 | .await?;
172 | cx.reply_to(format!("Banned for {} ", u.as_ref().unwrap()))
173 | .parse_mode(ParseMode::Html)
174 | .await?;
175 | if let Some(l) = get_log_channel(&db, cx.chat_id()).await? {
176 | let admin = cx
177 | .requester
178 | .get_chat_member(cx.chat_id(), cx.update.from().unwrap().id)
179 | .await?
180 | .user;
181 | let mem = cx
182 | .requester
183 | .get_chat_member(cx.chat_id(), user_id.unwrap())
184 | .await?;
185 | let logm = format!(
186 | "Chat title: {}\n#TEMP_BANNED\nAdmin: {}\nUser: {}\n Until: {}\n",
187 | html::code_inline(&get_chat_title(cx, cx.chat_id()).await.unwrap()),
188 | html::user_mention(admin.id, &admin.full_name()),
189 | html::user_mention(user_id.unwrap(), &mem.user.full_name()),
190 | html::code_inline(&mem.until_date().unwrap().to_string())
191 | );
192 | send_log(cx, &logm, l).await?;
193 | }
194 | } else {
195 | cx.reply_to("Can't get this user maybe he's not in the group or he deleted his account")
196 | .await?;
197 | }
198 |
199 | Ok(())
200 | }
201 |
202 | pub async fn unban(cx: &Cxt) -> TgErr<()> {
203 | tokio::try_join!(
204 | is_group(cx), //Should be a group
205 | user_should_restrict(cx, get_bot_id(cx).await), //Bot Should have restrict rights
206 | user_should_restrict(cx, cx.update.from().unwrap().id), //User should have restrict rights
207 | )?;
208 | let db = get_mdb().await;
209 | let (user_id, _text) = extract_text_id_from_reply(cx).await;
210 | if user_id.is_none() {
211 | cx.reply_to("No user was targeted").await?;
212 | return Ok(());
213 | }
214 |
215 | if let Ok(mem) = cx
216 | .requester
217 | .get_chat_member(cx.chat_id(), user_id.unwrap())
218 | .await
219 | {
220 | if !mem.is_banned() {
221 | cx.reply_to("This user is already unbanned!").await?;
222 | return Ok(());
223 | }
224 | } else {
225 | cx.reply_to("I can't seem to get the info of the user")
226 | .await?;
227 | return Ok(());
228 | }
229 |
230 | cx.requester
231 | .unban_chat_member(cx.chat_id(), user_id.unwrap())
232 | .await?;
233 | cx.reply_to("Unbanned! ")
234 | .parse_mode(ParseMode::Html)
235 | .await?;
236 |
237 | if let Some(l) = get_log_channel(&db, cx.chat_id()).await? {
238 | let admin = cx
239 | .requester
240 | .get_chat_member(cx.chat_id(), cx.update.from().unwrap().id)
241 | .await?
242 | .user;
243 | let user = cx
244 | .requester
245 | .get_chat_member(cx.chat_id(), user_id.unwrap())
246 | .await?
247 | .user;
248 | let logm = format!(
249 | "Chat title: {}\n#UNBANNED\nAdmin: {}\nUser: {}",
250 | html::code_inline(&get_chat_title(cx, cx.chat_id()).await.unwrap()),
251 | html::user_mention(admin.id, &admin.full_name()),
252 | html::user_mention(user_id.unwrap(), &user.full_name())
253 | );
254 | send_log(cx, &logm, l).await?;
255 | }
256 | Ok(())
257 | }
258 |
259 | pub async fn kick(cx: &Cxt) -> TgErr<()> {
260 | tokio::try_join!(
261 | is_group(cx), //Should be a group
262 | user_should_restrict(cx, get_bot_id(cx).await), //Bot Should have restrict rights
263 | user_should_restrict(cx, cx.update.from().unwrap().id), //User should have restrict rights
264 | )?;
265 | let db = get_mdb().await;
266 | let bot_id = get_bot_id(cx).await;
267 | let (user_id, text) = extract_text_id_from_reply(cx).await;
268 | if user_id.is_none() {
269 | cx.reply_to("No user was targeted").await?;
270 | return Ok(());
271 | }
272 | if user_id.unwrap() == bot_id {
273 | cx.reply_to("I am not gonna kick myself fella! Try using your brain next time!")
274 | .await?;
275 | return Ok(());
276 | }
277 |
278 | if user_id.unwrap() == *OWNER_ID || (*SUDO_USERS).contains(&user_id.unwrap()) {
279 | cx.reply_to("I am not gonna kick my owner or one of my sudo users")
280 | .await?;
281 | return Ok(());
282 | }
283 | if let Ok(mem) = cx
284 | .requester
285 | .get_chat_member(cx.chat_id(), user_id.unwrap())
286 | .await
287 | {
288 | if mem.is_banned() || mem.is_left() {
289 | cx.reply_to("This user is already gone mate!").await?;
290 | return Ok(());
291 | }
292 | if !mem.can_be_edited() {
293 | cx.reply_to("I am not gonna kick an Admin Here!").await?;
294 | return Ok(());
295 | }
296 | } else {
297 | cx.reply_to("I can't seem to get info for this user")
298 | .await?;
299 | return Ok(());
300 | };
301 | let user = cx
302 | .requester
303 | .get_chat_member(cx.chat_id(), user_id.unwrap())
304 | .await
305 | .unwrap()
306 | .user;
307 | let reason = text.unwrap_or_else(|| String::from("None"));
308 | let kick_text = format!(
309 | "Kicked \nUser: {}\n\nReason: {}",
310 | user_mention_or_link(&user),
311 | reason
312 | );
313 | cx.requester
314 | .kick_chat_member(cx.chat_id(), user_id.unwrap())
315 | .await?;
316 | cx.requester
317 | .unban_chat_member(cx.chat_id(), user_id.unwrap())
318 | .await?;
319 | cx.reply_to(kick_text).parse_mode(ParseMode::Html).await?;
320 | if let Some(l) = get_log_channel(&db, cx.chat_id()).await? {
321 | let admin = cx
322 | .requester
323 | .get_chat_member(cx.chat_id(), cx.update.from().unwrap().id)
324 | .await?
325 | .user;
326 | let user = cx
327 | .requester
328 | .get_chat_member(cx.chat_id(), user_id.unwrap())
329 | .await?
330 | .user;
331 | let logm = format!(
332 | "Chat title: {}\n#KICKED\nAdmin: {}\nUser: {}",
333 | html::code_inline(&get_chat_title(cx, cx.chat_id()).await.unwrap()),
334 | html::user_mention(admin.id, &admin.full_name()),
335 | html::user_mention(user_id.unwrap(), &user.full_name())
336 | );
337 | send_log(cx, &logm, l).await?;
338 | }
339 | Ok(())
340 | }
341 | pub async fn kickme(cx: &Cxt, cmd: &str) -> TgErr<()> {
342 | tokio::try_join!(
343 | is_group(cx),
344 | user_should_restrict(cx, get_bot_id(cx).await),
345 | check_command_disabled(cx, String::from(cmd))
346 | )?;
347 | let db = get_mdb().await;
348 | if let Some(user) = cx.update.from() {
349 | let user_id = user.id;
350 | if user_id == *OWNER_ID || (*SUDO_USERS).contains(&user_id) {
351 | cx.reply_to("You are my owner or one of my sudo users mate I can't kick you")
352 | .await?;
353 | return Ok(());
354 | }
355 | if let Ok(mem) = cx.requester.get_chat_member(cx.chat_id(), user_id).await {
356 | if !mem.can_be_edited() {
357 | cx.reply_to("I am not gonna kick an Admin Here!").await?;
358 | return Ok(());
359 | }
360 | } else {
361 | cx.reply_to("Can't kick the user").await?;
362 | return Ok(());
363 | }
364 | let kickme_text = format!("Piss off {} ", user_mention_or_link(user));
365 | cx.requester.kick_chat_member(cx.chat_id(), user_id).await?;
366 | cx.requester
367 | .unban_chat_member(cx.chat_id(), user_id)
368 | .await?;
369 | cx.reply_to(kickme_text).await?;
370 | if let Some(l) = get_log_channel(&db, cx.chat_id()).await? {
371 | let user = cx
372 | .requester
373 | .get_chat_member(cx.chat_id(), user_id)
374 | .await?
375 | .user;
376 | let logm = format!(
377 | "Chat id: {}\n#KICKME\nUser: {}",
378 | html::code_inline(&get_chat_title(cx, cx.chat_id()).await.unwrap()),
379 | html::user_mention(user_id, &user.full_name())
380 | );
381 | send_log(cx, &logm, l).await?;
382 | }
383 | } else {
384 | cx.reply_to("Can't get the info about the user").await?;
385 | }
386 | Ok(())
387 | }
388 |
--------------------------------------------------------------------------------
/src/modules/chat.rs:
--------------------------------------------------------------------------------
1 | use crate::{
2 | util::{can_change_info, consts, get_bot_id, get_filter_type, FilterType},
3 | Cxt, TgErr,
4 | };
5 | use teloxide::{
6 | net::Download,
7 | payloads::SendMessageSetters,
8 | prelude::{GetChatId, Requester},
9 | types::{ChatKind, InputFile, ParseMode},
10 | utils::command::parse_command,
11 | utils::html,
12 | };
13 | use tokio::{fs, try_join};
14 |
15 | pub async fn set_chatpic(cx: &Cxt) -> TgErr<()> {
16 | let bot_id = get_bot_id(cx).await;
17 | tokio::try_join!(
18 | can_change_info(cx, cx.update.from().unwrap().id),
19 | can_change_info(cx, bot_id)
20 | )?;
21 | if cx.update.reply_to_message().is_none() {
22 | cx.reply_to("Reply to a picture to set it as a chat picture")
23 | .await?;
24 | return Ok(());
25 | }
26 |
27 | let f = cx.update.reply_to_message().unwrap();
28 |
29 | //Get the message type
30 | let m_type = get_filter_type(f).await.parse::().unwrap();
31 | //Image path abs{chat_id}.png
32 | let path = format!("{}.png", cx.chat_id().abs());
33 | if let ChatKind::Public(c) = &cx.update.chat.kind {
34 | let title = c.title.as_ref().unwrap();
35 | match m_type {
36 | FilterType::Document => {
37 | if matches!(
38 | f.document().unwrap().mime_type.as_ref().unwrap().type_(),
39 | mime::IMAGE
40 | ) {
41 | let file_id = f.document().as_ref().unwrap().file_id.as_str();
42 | let file_path = cx.requester.get_file(file_id).await?.file_path;
43 | let mut file = fs::File::create(&path).await?;
44 | cx.requester.download_file(&file_path, &mut file).await?;
45 | let doc = InputFile::file(&path);
46 | cx.requester.set_chat_photo(cx.chat_id(), doc).await?;
47 | cx.reply_to(format!("Chat picture updated for chat {}", title))
48 | .await?;
49 | } else {
50 | cx.reply_to("This type is not supported").await?;
51 | }
52 | }
53 | FilterType::Photos => {
54 | //Last photo in the vector is the image with best quality
55 | let file_id = f.photo().as_ref().unwrap().last().unwrap().file_id.as_str();
56 | let file_path = cx.requester.get_file(file_id).await?.file_path;
57 | let mut file = fs::File::create(&path).await?;
58 | cx.requester.download_file(&file_path, &mut file).await?;
59 | let photo = InputFile::file(&path);
60 | cx.requester.set_chat_photo(cx.chat_id(), photo).await?;
61 | cx.reply_to(format!("Chat picture updated for chat {}", title))
62 | .await?;
63 | }
64 | _ => {
65 | cx.reply_to("Reply to an image to set it as chat picture")
66 | .await?;
67 | }
68 | }
69 | } else {
70 | cx.reply_to("This command can only be used in a group")
71 | .await?;
72 | }
73 | //If the downloaded chat pic still exists delet
74 | if fs::metadata(&path).await.is_ok() {
75 | fs::remove_file(&path).await?;
76 | }
77 |
78 | Ok(())
79 | }
80 |
81 | pub async fn set_chat_tile(cx: &Cxt) -> TgErr<()> {
82 | try_join!(
83 | can_change_info(cx, cx.update.from().unwrap().id),
84 | can_change_info(cx, get_bot_id(cx).await)
85 | )?;
86 | let (_, args) = parse_command(cx.update.text().unwrap(), consts::BOT_NAME).unwrap();
87 | let mut title;
88 | //If args is empty look for reply to message
89 | if args.is_empty() {
90 | if cx.update.reply_to_message().is_some() {
91 | //Check if the reply_to_message as a text if not check if the message has any captions
92 | title = cx
93 | .update
94 | .reply_to_message()
95 | .unwrap()
96 | .text()
97 | .unwrap_or_else(|| {
98 | cx.update
99 | .reply_to_message()
100 | .unwrap()
101 | .caption()
102 | .unwrap_or("")
103 | })
104 | .to_string();
105 | } else {
106 | cx.reply_to("Provide me a title to set").await?;
107 | return Ok(());
108 | }
109 | } else {
110 | title = args.join(" ");
111 | }
112 | //Telegram has 255 character limit on the chat title (https://core.telegram.org/bots/api#setchattitle)
113 | if title.len() > 255 {
114 | cx.reply_to("The text has more than 255 characters so truncating it to 255 characters")
115 | .await?;
116 | title.truncate(255);
117 | }
118 |
119 | //Check if the title is empty possible when the user replies to a non-text message without caption
120 | if title.is_empty() {
121 | cx.reply_to("Title can't be empty").await?;
122 | return Ok(());
123 | }
124 |
125 | cx.requester.set_chat_title(cx.chat_id(), &title).await?;
126 | cx.reply_to(format!(
127 | "Successfully set the chat title to '{}'",
128 | html::code_inline(&title)
129 | ))
130 | .parse_mode(ParseMode::Html)
131 | .await?;
132 | Ok(())
133 | }
134 |
--------------------------------------------------------------------------------
/src/modules/commands.rs:
--------------------------------------------------------------------------------
1 | use teloxide::utils::command::BotCommand;
2 | #[derive(BotCommand)]
3 | #[command(rename = "lowercase", description = "These commands are supported:")]
4 | pub enum Command {
5 | #[command(description = "Ban a user")]
6 | Ban,
7 | #[command(description = "Bans a user for sometime")]
8 | Tban,
9 | #[command(description = "Unbans a user")]
10 | Unban,
11 | #[command(description = "Mute a user")]
12 | Mute,
13 | #[command(description = "Mutes user for some time")]
14 | Tmute,
15 | #[command(description = "Unmute a user")]
16 | Unmute,
17 | #[command(description = "Greeting a user who sends /start")]
18 | Start,
19 | #[command(description = "Helps with available commands")]
20 | Help,
21 | #[command(description = "Kick a user from the group")]
22 | Kick,
23 | #[command(description = "Sends info about a user")]
24 | Info,
25 | #[command(description = "Send's user's or chat's ID")]
26 | Id,
27 | #[command(description = "Kick yourself from a group")]
28 | Kickme,
29 | #[command(description = "Pins a message")]
30 | Pin,
31 | #[command(description = "Unpins a mentioned message")]
32 | Unpin,
33 | #[command(description = "Promotes a user")]
34 | Promote,
35 | #[command(description = "Demotes a user")]
36 | Demote,
37 | #[command(description = "Get's the invite link of the chat")]
38 | Invitelink,
39 | #[command(description = "Get's list of admins in a group")]
40 | Adminlist,
41 | #[command(description = "Delete bulk of messages in a group")]
42 | Purge,
43 | #[command(description = "Deletes a message")]
44 | Del,
45 | #[command(description = "Leaves a chat (Owner use only)")]
46 | Leavechat,
47 | #[command(description = "Urban Dictionary")]
48 | Ud,
49 | #[command(description = "Pastes text to dogbin")]
50 | Paste,
51 | #[command(description = "Echoes same thing basically")]
52 | Echo,
53 | #[command(description = "Changes chat permissons")]
54 | Lock,
55 | #[command(description = "Unlocks locked permissions in a chat")]
56 | Unlock,
57 | #[command(description = "Available locktypes")]
58 | Locktypes,
59 | #[command(description = "Get's list of chats bot is in")]
60 | Chatlist,
61 | #[command(description = "Gban a user")]
62 | Gban,
63 | #[command(description = "Ungban a user")]
64 | Ungban,
65 | #[command(description = "Turns Gbans for a group on/off")]
66 | Gbanstat,
67 | #[command(description = "Warns a user")]
68 | Warn,
69 | #[command(description = "Sets warn limit")]
70 | Warnlimit,
71 | #[command(description = "Sets warn mode")]
72 | Warnmode,
73 | #[command(description = "Resets user's warnings")]
74 | Resetwarns,
75 | #[command(description = "Counts the number of warnings")]
76 | Warns,
77 | #[command(description = "Disables a command")]
78 | Disable,
79 | #[command(description = "Enables a command")]
80 | Enable,
81 | #[command(description = "Add filter for a keyword")]
82 | Filter,
83 | #[command(description = "list filters")]
84 | Filters,
85 | #[command(description = "Stop the use of a filter")]
86 | Stop,
87 | #[command(description = "Add a blacklist word")]
88 | Addblacklist,
89 | #[command(description = "Remove a blacklist word")]
90 | Rmblacklist,
91 | #[command(description = "List current blacklists in the group")]
92 | Blacklists,
93 | #[command(description = "Set a blacklist mode")]
94 | Blacklistmode,
95 | #[command(description = "Set chat picture")]
96 | Setchatpic,
97 | #[command(description = "Set chat title")]
98 | Setchattitle,
99 | #[command(description = "Set a log channel")]
100 | Setlog,
101 | #[command(description = "Unset a log channel")]
102 | Unsetlog,
103 | #[command(description = "Report a user")]
104 | Report,
105 | #[command(description = "Report setting of a group")]
106 | Reports,
107 | }
108 |
--------------------------------------------------------------------------------
/src/modules/disable.rs:
--------------------------------------------------------------------------------
1 | use teloxide::prelude::GetChatId;
2 | use teloxide::utils::command::parse_command;
3 |
4 | use crate::database::db_utils::{disable_command, get_disabled_command};
5 | use crate::database::DisableCommand;
6 | use crate::util::{consts, is_group, user_should_be_admin, DisableAble};
7 | use crate::{get_mdb, Cxt, TgErr};
8 |
9 | pub async fn disable(cx: &Cxt) -> TgErr<()> {
10 | tokio::try_join!(
11 | is_group(cx),
12 | user_should_be_admin(cx, cx.update.from().unwrap().id)
13 | )?;
14 | let db = get_mdb().await;
15 | let (_, args) = parse_command(cx.update.text().unwrap(), consts::BOT_NAME).unwrap();
16 |
17 | if args.is_empty() {
18 | cx.reply_to("What should I disable").await?;
19 | return Ok(());
20 | }
21 | let disable_val = args[0].to_lowercase();
22 | let dis_enu = disable_val.parse::().unwrap();
23 | let mut cmds = get_disabled_command(&db, cx.chat_id()).await?;
24 | if !matches!(dis_enu, DisableAble::Error) {
25 | cmds.push(disable_val.clone());
26 | let dc = &DisableCommand {
27 | chat_id: cx.chat_id(),
28 | disabled_commands: cmds,
29 | };
30 | disable_command(&db, dc).await?;
31 | cx.reply_to(format!("Command {} has been disabled", disable_val))
32 | .await?;
33 | } else {
34 | cx.reply_to("This command Can't be disabled!").await?;
35 | }
36 | Ok(())
37 | }
38 |
39 | pub async fn enable(cx: &Cxt) -> TgErr<()> {
40 | tokio::try_join!(
41 | is_group(cx),
42 | user_should_be_admin(cx, cx.update.from().unwrap().id)
43 | )?;
44 | let (_, args) = parse_command(cx.update.text().unwrap(), consts::BOT_NAME).unwrap();
45 | let db = get_mdb().await;
46 | if args.is_empty() {
47 | cx.reply_to("What should I disable").await?;
48 | return Ok(());
49 | }
50 | let cmd = args[0].to_lowercase();
51 | let mut disabled_cmds = get_disabled_command(&db, cx.chat_id()).await?;
52 | let ind = disabled_cmds.iter().position(|pos| pos.eq(&cmd));
53 | if ind.is_some() {
54 | disabled_cmds.remove(ind.unwrap());
55 | let dc = &DisableCommand {
56 | chat_id: cx.chat_id(),
57 | disabled_commands: disabled_cmds,
58 | };
59 | disable_command(&db, dc).await?;
60 | cx.reply_to("This command is enabled and ready to use here")
61 | .await?;
62 | } else {
63 | cx.reply_to("Try enabling something which was disabled")
64 | .await?;
65 | }
66 | Ok(())
67 | }
68 |
--------------------------------------------------------------------------------
/src/modules/filters.rs:
--------------------------------------------------------------------------------
1 | use regex::RegexBuilder;
2 | use teloxide::{
3 | payloads::{
4 | SendAnimationSetters, SendAudioSetters, SendDocumentSetters, SendMessageSetters,
5 | SendPhotoSetters, SendVideoSetters, SendVoiceSetters,
6 | },
7 | prelude::{GetChatId, Requester},
8 | types::InputFile,
9 | types::ParseMode,
10 | utils::{
11 | command::parse_command,
12 | html::{self, user_mention_or_link},
13 | },
14 | };
15 |
16 | use crate::{
17 | database::{
18 | db_utils::{
19 | add_blacklist, add_filter, get_blacklist, get_blacklist_mode, get_log_channel,
20 | get_reply_caption, get_reply_filter, get_reply_type_filter, list_filters, rm_blacklist,
21 | rm_filter, set_blacklist_mode,
22 | },
23 | BlacklistFilter, BlacklistKind, Filters,
24 | },
25 | get_mdb,
26 | modules::{send_log, warn_user},
27 | util::{
28 | can_delete_messages, consts, extract_filter_text, get_bot_id, get_chat_title,
29 | get_filter_type, is_group, is_user_admin, user_should_be_admin, user_should_restrict,
30 | BlacklistMode, FilterType,
31 | },
32 | };
33 | use crate::{Cxt, TgErr};
34 |
35 | pub async fn filter(cx: &Cxt) -> TgErr<()> {
36 | tokio::try_join!(
37 | is_group(cx),
38 | user_should_be_admin(cx, cx.update.from().unwrap().id)
39 | )?;
40 | let db = get_mdb().await;
41 | let (_, args) = parse_command(cx.update.text().unwrap(), consts::BOT_NAME).unwrap();
42 | if !args.is_empty() {
43 | let keyword = args[0].to_string();
44 | if args.get(1).is_none() {
45 | if cx.update.reply_to_message().is_some() {
46 | let rep_msg = cx.update.reply_to_message().unwrap();
47 | let fil_type = get_filter_type(rep_msg).await;
48 | let parsed_type = fil_type.parse::().unwrap();
49 | let reply;
50 | let cap = rep_msg.caption().map(String::from);
51 | match parsed_type {
52 | FilterType::Text => reply = rep_msg.text().unwrap().to_string(),
53 | FilterType::Animation => {
54 | reply = rep_msg.animation().unwrap().file_id.to_string();
55 | }
56 | FilterType::Audio => reply = rep_msg.audio().unwrap().file_id.to_string(),
57 | FilterType::Document => reply = rep_msg.document().unwrap().file_id.to_string(),
58 | FilterType::Photos => {
59 | reply = rep_msg.photo().unwrap().last().unwrap().file_id.to_string()
60 | }
61 | FilterType::Sticker => reply = rep_msg.sticker().unwrap().file_id.to_string(),
62 | FilterType::Video => reply = rep_msg.video().unwrap().file_id.to_string(),
63 | FilterType::Voice => reply = rep_msg.voice().unwrap().file_id.to_string(),
64 | FilterType::Error => {
65 | cx.reply_to("This filter type is not supported").await?;
66 | return Ok(());
67 | }
68 | }
69 | let fl = &Filters {
70 | chat_id: cx.chat_id(),
71 | filter: keyword.clone(),
72 | reply: reply.clone(),
73 | caption: cap,
74 | f_type: fil_type,
75 | };
76 | add_filter(&db, fl).await?;
77 | cx.reply_to(format!("Saved filter '{}'
", &keyword))
78 | .parse_mode(ParseMode::Html)
79 | .await?;
80 | } else {
81 | cx.reply_to("Give me something to reply the filter with")
82 | .await?;
83 | }
84 | } else {
85 | let rep = args[1..].join("");
86 | let fl = &Filters {
87 | chat_id: cx.chat_id(),
88 | filter: keyword.clone(),
89 | reply: rep,
90 | caption: None,
91 | f_type: "text".to_string(),
92 | };
93 | add_filter(&db, fl).await?;
94 | cx.reply_to(format!("Saved filter '{}'
", &keyword))
95 | .parse_mode(ParseMode::Html)
96 | .await?;
97 | if let Some(l) = get_log_channel(&db, cx.chat_id()).await? {
98 | let admin = cx
99 | .requester
100 | .get_chat_member(cx.chat_id(), cx.update.from().unwrap().id)
101 | .await?
102 | .user;
103 | let logm = format!(
104 | "Chat title: {}\n#FILTER\nAdmin: {}\nWord: {}",
105 | html::code_inline(&get_chat_title(cx, cx.chat_id()).await.unwrap()),
106 | html::user_mention(admin.id, &admin.full_name()),
107 | html::code_inline(&keyword)
108 | );
109 | send_log(cx, &logm, l).await?;
110 | }
111 | }
112 | } else {
113 | cx.reply_to("Give me some keyword to filter").await?;
114 | }
115 | Ok(())
116 | }
117 |
118 | pub async fn remove_filter(cx: &Cxt) -> TgErr<()> {
119 | tokio::try_join!(
120 | is_group(cx),
121 | user_should_be_admin(cx, cx.update.from().unwrap().id),
122 | )?;
123 | let db = get_mdb().await;
124 | let (_, args) = parse_command(cx.update.text().unwrap(), consts::BOT_NAME).unwrap();
125 | if args.is_empty() {
126 | cx.reply_to("Mention some filter keyword to stop").await?;
127 | return Ok(());
128 | }
129 | let keyword = args[0].to_owned();
130 | let filist = list_filters(&db, cx.chat_id()).await?;
131 | if !filist.contains(&keyword) {
132 | cx.reply_to("You haven't set any filter on that keyword")
133 | .await?;
134 | return Ok(());
135 | }
136 | rm_filter(&db, cx.chat_id(), &keyword).await?;
137 | cx.reply_to(format!(
138 | "Filter {}
has been stopped.",
139 | &keyword
140 | ))
141 | .parse_mode(ParseMode::Html)
142 | .await?;
143 | if let Some(l) = get_log_channel(&db, cx.chat_id()).await? {
144 | let admin = cx
145 | .requester
146 | .get_chat_member(cx.chat_id(), cx.update.from().unwrap().id)
147 | .await?
148 | .user;
149 | let logm = format!(
150 | "Chat title: {}\n#FILTER_STOPPED\nAdmin: {}\nWord: {}",
151 | html::code_inline(&get_chat_title(cx, cx.chat_id()).await.unwrap()),
152 | html::user_mention(admin.id, &admin.full_name()),
153 | html::code_inline(&keyword)
154 | );
155 | send_log(cx, &logm, l).await?;
156 | }
157 | Ok(())
158 | }
159 |
160 | pub async fn filter_reply(cx: &Cxt) -> TgErr<()> {
161 | let db = get_mdb().await;
162 | let text = extract_filter_text(&cx.update).await;
163 | if text.is_none() {
164 | return Ok(());
165 | }
166 | let to_match = text.unwrap();
167 | let filterlist = list_filters(&db, cx.chat_id()).await?;
168 | for pat in filterlist {
169 | let pattern = format!(r#"( |^|[^\w]){}( |$|[^\w])"#, regex::escape(&pat));
170 | let re = RegexBuilder::new(&pattern)
171 | .case_insensitive(true)
172 | .build()
173 | .unwrap();
174 | if re.is_match(&to_match) {
175 | let f_type = get_reply_type_filter(&db, cx.chat_id(), &pat)
176 | .await?
177 | .unwrap();
178 | let reply = get_reply_filter(&db, cx.chat_id(), &pat).await?.unwrap();
179 | let parsed_ftype = f_type.parse::().unwrap();
180 | let caption = get_reply_caption(&db, cx.chat_id(), &pat)
181 | .await?
182 | .unwrap_or_else(String::new);
183 | match parsed_ftype {
184 | FilterType::Audio => {
185 | let audio = InputFile::file_id(reply);
186 | cx.reply_audio(audio).caption(caption).await?;
187 | }
188 | FilterType::Animation => {
189 | let animation = InputFile::file_id(reply);
190 | cx.reply_animation(animation).caption(caption).await?;
191 | }
192 | FilterType::Document => {
193 | let document = InputFile::file_id(reply);
194 | cx.reply_document(document).caption(caption).await?;
195 | }
196 | FilterType::Photos => {
197 | let photo = InputFile::file_id(reply);
198 | cx.reply_photo(photo).caption(caption).await?;
199 | }
200 | FilterType::Sticker => {
201 | let sticker = InputFile::file_id(reply);
202 | cx.reply_sticker(sticker).await?;
203 | }
204 | FilterType::Text => {
205 | cx.reply_to(reply).await?;
206 | }
207 | FilterType::Video => {
208 | let video = InputFile::file_id(reply);
209 | cx.reply_video(video).caption(caption).await?;
210 | }
211 | FilterType::Voice => {
212 | let voice = InputFile::file_id(reply);
213 | cx.reply_voice(voice).caption(caption).await?;
214 | }
215 | _ => {}
216 | }
217 | }
218 | }
219 | Ok(())
220 | }
221 | pub async fn filter_list(cx: &Cxt) -> TgErr<()> {
222 | tokio::try_join!(
223 | is_group(cx),
224 | user_should_be_admin(cx, cx.update.from().unwrap().id),
225 | )?;
226 | let db = get_mdb().await;
227 | let filters = list_filters(&db, cx.chat_id()).await?;
228 | if filters.is_empty() {
229 | cx.reply_to(format!(
230 | "No filters in {}",
231 | get_chat_title(cx, cx.chat_id()).await.unwrap()
232 | ))
233 | .await?;
234 | return Ok(());
235 | }
236 | cx.reply_to(format!(
237 | "Filters in this group are
:\n- {}",
238 | filters.join("\n- ")
239 | ))
240 | .parse_mode(ParseMode::Html)
241 | .await?;
242 | Ok(())
243 | }
244 |
245 | pub async fn blacklist_filter(cx: &Cxt) -> TgErr<()> {
246 | tokio::try_join!(
247 | is_group(cx),
248 | user_should_restrict(cx, cx.update.from().unwrap().id),
249 | user_should_restrict(cx, get_bot_id(cx).await)
250 | )?;
251 | let db = get_mdb().await;
252 | let (_, args) = parse_command(cx.update.text().unwrap(), consts::BOT_NAME).unwrap();
253 | if args.is_empty() {
254 | cx.reply_to("What should I blacklist").await?;
255 | return Ok(());
256 | }
257 | let blacklist = args[0].to_owned();
258 | let bl = &BlacklistFilter {
259 | chat_id: cx.chat_id(),
260 | filter: blacklist.clone(),
261 | };
262 | add_blacklist(&db, bl).await?;
263 | let mode = get_blacklist_mode(&db, cx.chat_id()).await?;
264 |
265 | //Because the default mode is delete we need to check for the permissions for other modes bot will take care about the permissions while setting the modes
266 | if matches!(
267 | mode.parse::().unwrap(),
268 | BlacklistMode::Delete
269 | ) {
270 | can_delete_messages(cx, get_bot_id(cx).await).await?;
271 | }
272 |
273 | cx.reply_to(format!(
274 | "Added blacklist {}. The blacklist mode in the chat is {}
",
275 | &blacklist, &mode
276 | ))
277 | .parse_mode(ParseMode::Html)
278 | .await?;
279 | if let Some(l) = get_log_channel(&db, cx.chat_id()).await? {
280 | let admin = cx
281 | .requester
282 | .get_chat_member(cx.chat_id(), cx.update.from().unwrap().id)
283 | .await?
284 | .user;
285 | let logm = format!(
286 | "Chat title: {}\n#BLACKLIST\nAdmin: {}\nWord: {}",
287 | html::code_inline(&get_chat_title(cx, cx.chat_id()).await.unwrap()),
288 | html::user_mention(admin.id, &admin.full_name()),
289 | html::code_inline(&blacklist)
290 | );
291 | send_log(cx, &logm, l).await?;
292 | }
293 | Ok(())
294 | }
295 |
296 | pub async fn list_blacklist(cx: &Cxt) -> TgErr<()> {
297 | tokio::try_join!(
298 | is_group(cx),
299 | user_should_be_admin(cx, cx.update.from().unwrap().id)
300 | )?;
301 | let db = get_mdb().await;
302 | let blist = get_blacklist(&db, cx.chat_id()).await?;
303 | if blist.is_empty() {
304 | cx.reply_to("No blacklist set in this chat").await?;
305 | return Ok(());
306 | }
307 | cx.reply_to(format!(
308 | "The blacklist words in the chat are\n - {}
",
309 | blist.join("\n -")
310 | ))
311 | .parse_mode(ParseMode::Html)
312 | .await?;
313 | Ok(())
314 | }
315 |
316 | pub async fn remove_blacklist(cx: &Cxt) -> TgErr<()> {
317 | tokio::try_join!(
318 | is_group(cx),
319 | user_should_be_admin(cx, cx.update.from().unwrap().id)
320 | )?;
321 | let db = get_mdb().await;
322 | let (_, args) = parse_command(cx.update.text().unwrap(), "consts::BOT_NAME").unwrap();
323 | if args.is_empty() {
324 | cx.reply_to("Mention some blacklist to remove").await?;
325 | return Ok(());
326 | }
327 | let bk = args[0].to_string();
328 | let blist = get_blacklist(&db, cx.chat_id()).await?;
329 | if blist.contains(&bk) {
330 | let bl = &BlacklistFilter {
331 | chat_id: cx.chat_id(),
332 | filter: bk.clone(),
333 | };
334 | rm_blacklist(&db, bl).await?;
335 | cx.reply_to(format!("Blacklist {} has been removed", &bk))
336 | .await?;
337 | if let Some(l) = get_log_channel(&db, cx.chat_id()).await? {
338 | let admin = cx
339 | .requester
340 | .get_chat_member(cx.chat_id(), cx.update.from().unwrap().id)
341 | .await?
342 | .user;
343 | let logm = format!(
344 | "Chat title: {}\n#BLACKLIST_REMOVED\nAdmin: {}\nWord: {}",
345 | html::code_inline(&get_chat_title(cx, cx.chat_id()).await.unwrap()),
346 | html::user_mention(admin.id, &admin.full_name()),
347 | html::code_inline(&bk)
348 | );
349 | send_log(cx, &logm, l).await?;
350 | }
351 | } else {
352 | cx.reply_to("This word isn't blacklisted here!").await?;
353 | }
354 | Ok(())
355 | }
356 |
357 | pub async fn set_blacklist_kind(cx: &Cxt) -> TgErr<()> {
358 | tokio::try_join!(
359 | is_group(cx),
360 | user_should_be_admin(cx, cx.update.from().unwrap().id)
361 | )?;
362 | let db = get_mdb().await;
363 | let (_, args) = parse_command(cx.update.text().unwrap(), "consts::BOT_NAME").unwrap();
364 | let bot_id = get_bot_id(cx).await;
365 | if args.is_empty() {
366 | cx.reply_to("Mention a blacklist mode").await?;
367 | return Ok(());
368 | }
369 | let mode = args[0].parse::().unwrap();
370 | let chatmem = cx.requester.get_chat_member(cx.chat_id(), bot_id).await?;
371 | match mode {
372 | BlacklistMode::Warn => {
373 | if chatmem.kind.can_restrict_members() {
374 | let bm = &BlacklistKind {
375 | chat_id: cx.chat_id(),
376 | kind: String::from("warn"),
377 | };
378 | set_blacklist_mode(&db, bm).await?;
379 | cx.reply_to("The blacklist mode is set to warn that means if you use the blacklisted word you will be warned, when your warns exceed the warn limit you will be banned or kicked depending upon the warn mode").parse_mode(ParseMode::Html).await?;
380 | } else {
381 | cx.reply_to("I can't restrict people here please give me the permission to do so")
382 | .await?;
383 | }
384 | }
385 | BlacklistMode::Kick => {
386 | if chatmem.kind.can_restrict_members() {
387 | let bm = &BlacklistKind {
388 | chat_id: cx.chat_id(),
389 | kind: String::from("kick"),
390 | };
391 | set_blacklist_mode(&db, bm).await?;
392 | cx.reply_to("The blacklist mode is set to kick that means if you use the blacklisted word you will be kicked from the group").parse_mode(ParseMode::Html).await?;
393 | } else {
394 | cx.reply_to("I can't restrict people here please give me the permission to do so")
395 | .await?;
396 | }
397 | }
398 | BlacklistMode::Delete => {
399 | if chatmem.kind.can_delete_messages() {
400 | let bm = &BlacklistKind {
401 | chat_id: cx.chat_id(),
402 | kind: String::from("delete"),
403 | };
404 | set_blacklist_mode(&db, bm).await?;
405 | cx.reply_to("The blacklist mode is set to delete that means if you use the blacklisted word the message will be deleted").parse_mode(ParseMode::Html).await?;
406 | } else {
407 | cx.reply_to("I can't delete messages here please give me the permission to do so")
408 | .await?;
409 | }
410 | }
411 | BlacklistMode::Ban => {
412 | if chatmem.kind.can_restrict_members() {
413 | let bm = &BlacklistKind {
414 | chat_id: cx.chat_id(),
415 | kind: String::from("ban"),
416 | };
417 | set_blacklist_mode(&db, bm).await?;
418 | cx.reply_to("The blacklist mode is set to ban that means if you use the blacklisted word you will be banned from the group").parse_mode(ParseMode::Html).await?;
419 | } else {
420 | cx.reply_to("I can't restrict people here please give me the permission to do so")
421 | .await?;
422 | }
423 | }
424 | BlacklistMode::Error => {
425 | cx.reply_to("Invalid blacklist mode").await?;
426 | }
427 | }
428 | Ok(())
429 | }
430 |
431 | pub async fn action_blacklist(cx: &Cxt) -> TgErr<()> {
432 | tokio::try_join!(
433 | is_group(cx), //Should be a group
434 | )?;
435 | let text = extract_filter_text(&cx.update).await;
436 | let bot_id = get_bot_id(cx).await;
437 | let db = get_mdb().await;
438 |
439 | if cx.update.from().is_none() {
440 | return Ok(());
441 | }
442 | if text.is_none() {
443 | return Ok(());
444 | }
445 | let culprit_id = cx.update.from().unwrap().id;
446 | if culprit_id == bot_id {
447 | return Ok(());
448 | }
449 | if is_user_admin(cx, culprit_id).await {
450 | return Ok(());
451 | }
452 | let to_match = text.unwrap();
453 | let blacklist = get_blacklist(&db, cx.chat_id()).await?;
454 | let mode = get_blacklist_mode(&db, cx.chat_id()).await?;
455 | let parsed_mode = mode.parse::().unwrap();
456 | let botmem = cx.requester.get_chat_member(cx.chat_id(), bot_id).await?;
457 | let usmem = cx
458 | .requester
459 | .get_chat_member(cx.chat_id(), culprit_id)
460 | .await?;
461 | for pat in blacklist {
462 | let pattern = format!(r#"( |^|[^\w]){}( |$|[^\w])"#, regex::escape(&pat));
463 | let re = RegexBuilder::new(&pattern)
464 | .case_insensitive(true)
465 | .build()
466 | .unwrap();
467 | if re.is_match(&to_match) {
468 | match parsed_mode {
469 | BlacklistMode::Ban => {
470 | if botmem.kind.can_restrict_members() {
471 | cx.requester
472 | .kick_chat_member(cx.chat_id(), culprit_id)
473 | .await?;
474 | cx.reply_to(format!(
475 | "User{} has been banned for using blacklisted word {}
",
476 | user_mention_or_link(&usmem.user),
477 | &pat
478 | ))
479 | .parse_mode(ParseMode::Html)
480 | .await?;
481 | }
482 | }
483 | BlacklistMode::Delete => {
484 | if botmem.kind.can_delete_messages() {
485 | cx.requester
486 | .delete_message(cx.chat_id(), cx.update.id)
487 | .await?;
488 | }
489 | }
490 | BlacklistMode::Kick => {
491 | if botmem.kind.can_restrict_members() {
492 | cx.requester
493 | .kick_chat_member(cx.chat_id(), culprit_id)
494 | .await?;
495 | cx.requester
496 | .unban_chat_member(cx.chat_id(), culprit_id)
497 | .await?;
498 | cx.reply_to(format!(
499 | "User {} has been kicked for using the blacklisted word {}",
500 | user_mention_or_link(&usmem.user),
501 | &pat
502 | ))
503 | .await?;
504 | }
505 | }
506 | BlacklistMode::Warn => {
507 | if botmem.kind.can_restrict_members() {
508 | let reason = format!("Use of blacklisted word {}", &pat);
509 | warn_user(cx, culprit_id, reason).await?;
510 | }
511 | }
512 | _ => {}
513 | }
514 | }
515 | }
516 | Ok(())
517 | }
518 |
--------------------------------------------------------------------------------
/src/modules/log_channel.rs:
--------------------------------------------------------------------------------
1 | use teloxide::{
2 | payloads::SendMessageSetters,
3 | prelude::{GetChatId, Requester},
4 | types::ParseMode,
5 | utils::html,
6 | };
7 |
8 | use crate::{
9 | database::{
10 | db_utils::{add_log_channel, get_log_channel, rm_log_channel},
11 | Logging,
12 | },
13 | get_mdb,
14 | util::{get_bot_id, get_chat_title, is_group, user_should_be_creator},
15 | Cxt, TgErr,
16 | };
17 |
18 | pub async fn add_logc(cx: &Cxt) -> TgErr<()> {
19 | tokio::try_join!(
20 | is_group(cx),
21 | user_should_be_creator(cx, cx.update.from().unwrap().id)
22 | )?;
23 | let bot_id = get_bot_id(cx).await;
24 | let db = get_mdb().await;
25 | if cx.update.reply_to_message().is_none() {
26 | cx.reply_to("Add the bot to the channel send a message in the channel and forward that message to this chat and reply to the message with /setlog").await?;
27 | return Ok(());
28 | }
29 | let ch_msg = cx.update.reply_to_message().unwrap();
30 | if let Some(m) = ch_msg.forward_from_chat() {
31 | if let Ok(chatmem) = cx.requester.get_chat_member(m.id, bot_id).await {
32 | let c_id = m.id;
33 | if chatmem.can_post_messages() {
34 | let lg = Logging {
35 | chat_id: cx.chat_id(),
36 | channel: c_id,
37 | };
38 | add_log_channel(&db, &lg).await?;
39 | cx.reply_to(format!(
40 | "Added log channel for this chat\nChannel id:{}\nChannel Name:{}",
41 | html::code_inline(&c_id.to_string()),
42 | html::code_inline(&get_chat_title(cx, c_id).await.unwrap())
43 | ))
44 | .parse_mode(ParseMode::Html)
45 | .await?;
46 | } else {
47 | cx.reply_to("I can't post messages in the mentioned channel please give me permissions to do so").await?;
48 | }
49 | } else {
50 | cx.reply_to(
51 | "Seems like I am not in the channel where the message was forwardeed from!",
52 | )
53 | .await?;
54 | }
55 | } else {
56 | cx.reply_to("This message was not forwarded from a channel please read the instruction properly for setting a log channel").await?;
57 | }
58 | Ok(())
59 | }
60 |
61 | pub async fn remove_log(cx: &Cxt) -> TgErr<()> {
62 | tokio::try_join!(
63 | is_group(cx),
64 | user_should_be_creator(cx, cx.update.from().unwrap().id)
65 | )?;
66 | let db = get_mdb().await;
67 | if get_log_channel(&db, cx.chat_id()).await?.is_some() {
68 | rm_log_channel(&db, cx.chat_id()).await?;
69 | cx.reply_to("The log channel has been unset").await?;
70 | } else {
71 | cx.reply_to("You haven't set any log channel's here send /setlog to get instructions")
72 | .await?;
73 | }
74 | Ok(())
75 | }
76 |
77 | pub async fn send_log(cx: &Cxt, message: &str, channel_id: i64) -> TgErr<()> {
78 | if let Err(e) = cx
79 | .requester
80 | .send_message(channel_id, message)
81 | .parse_mode(ParseMode::Html)
82 | .await
83 | {
84 | let text = format!(
85 | "Can't send the message into the log channel because of\n{}",
86 | html::code_inline(&e.to_string())
87 | );
88 | cx.requester
89 | .send_message(cx.chat_id(), text)
90 | .parse_mode(ParseMode::Html)
91 | .await?;
92 | }
93 | Ok(())
94 | }
95 |
--------------------------------------------------------------------------------
/src/modules/misc.rs:
--------------------------------------------------------------------------------
1 | use crate::util::{check_command_disabled, consts, sudo_or_owner_filter};
2 | use crate::{Cxt, TgErr, BOT_TOKEN};
3 | use mime;
4 | use regex::Regex;
5 | use serde_json::json;
6 | use teloxide::prelude::*;
7 | use teloxide::types::{InlineKeyboardButton, InlineKeyboardMarkup, ParseMode};
8 | use teloxide::utils::command::parse_command;
9 | use teloxide::utils::html;
10 |
11 | pub async fn ud(cx: &Cxt, cmd: &str) -> TgErr<()> {
12 | tokio::try_join!(check_command_disabled(cx, String::from(cmd)))?;
13 | let (_, args) = parse_command(cx.update.text().unwrap(), "consts::BOT_NAME").unwrap();
14 | if args.is_empty() {
15 | cx.reply_to("Please enter a keyword to search").await?;
16 | return Ok(());
17 | }
18 | let text = args.join("");
19 | let resp = reqwest::get(format!(
20 | "http://api.urbandictionary.com/v0/define?term={}",
21 | text
22 | ))
23 | .await?;
24 | let data: serde_json::Value = resp.json().await?;
25 | let ubdata = data.get("list").unwrap().get(0);
26 | if ubdata.is_none() {
27 | cx.reply_to("No result found for the keyword").await?;
28 | return Ok(());
29 | }
30 | let ignore_char = Regex::new(r#"[\[\]]"#).unwrap();
31 | let txt = format!(
32 | "Word: {}\nDefinition: \n{}\n\nExample:\n{} ",
33 | text,
34 | ubdata.unwrap().get("definition").unwrap().as_str().unwrap(),
35 | ubdata.unwrap().get("example").unwrap().as_str().unwrap()
36 | );
37 | let button = InlineKeyboardButton::url(
38 | "Know More".to_string(),
39 | ubdata
40 | .unwrap()
41 | .get("permalink")
42 | .unwrap()
43 | .as_str()
44 | .unwrap()
45 | .to_owned(),
46 | );
47 | let mut reply_text = ignore_char.replace_all(&txt, "").into_owned();
48 | //Telegram's character limit
49 | reply_text.truncate(4096);
50 | cx.reply_to(reply_text)
51 | .parse_mode(ParseMode::Html)
52 | .reply_markup(InlineKeyboardMarkup::default().append_row(vec![button]))
53 | .await?;
54 | Ok(())
55 | }
56 |
57 | pub async fn katbin(cx: &Cxt, cmd: &str) -> TgErr<()> {
58 | tokio::try_join!(check_command_disabled(cx, String::from(cmd)))?;
59 | let message = &cx.update;
60 | let (_, args) = parse_command(cx.update.text().unwrap(), "consts::BOT_NAME").unwrap();
61 | let mut _data = String::new();
62 | if args.is_empty() {
63 | if let Some(m) = message.reply_to_message() {
64 | if let Some(txt) = m.text() {
65 | _data = txt.to_string();
66 | } else if let Some(doc) = m.document() {
67 | let file = doc.clone();
68 | let mime = file.mime_type.unwrap();
69 | let file_dw = cx.requester.get_file(&file.file_id).await?.file_path;
70 | if matches!(mime.type_(), mime::TEXT | mime::OCTET_STREAM) {
71 | let url = format!(
72 | "https://api.telegram.org/file/bot{}/{}",
73 | *BOT_TOKEN, file_dw
74 | );
75 | _data = reqwest::get(url).await?.text().await?;
76 | } else {
77 | cx.reply_to("Invalid file type").await?;
78 | return Ok(());
79 | }
80 | } else {
81 | cx.reply_to("This file format is not supported").await?;
82 | return Ok(());
83 | }
84 | } else {
85 | cx.reply_to("No data was provided to paste").await?;
86 | return Ok(());
87 | }
88 | } else {
89 | _data = args.join("");
90 | }
91 | let client = reqwest::Client::new();
92 | let post_json = json!({
93 | "content":_data,
94 | }
95 | );
96 | let resp = client
97 | .post("https://api.katb.in/api/paste")
98 | .json(&post_json)
99 | .send()
100 | .await?;
101 | let json: serde_json::Value = resp.json().await?;
102 | let resp_msg = json.get("msg").unwrap().as_str().unwrap();
103 | if resp_msg.ne("Successfully created paste") {
104 | cx.reply_to(resp_msg).await?;
105 | return Ok(());
106 | }
107 | let key = json.get("paste_id").unwrap().as_str().unwrap();
108 | let reply_text = format!(
109 | "I have pasted that for you {}",
110 | html::link(format!("https://katb.in/{}", &key).as_str(), "click here")
111 | );
112 | cx.reply_to(reply_text).parse_mode(ParseMode::Html).await?;
113 | Ok(())
114 | }
115 |
116 | pub async fn echo(cx: &Cxt, cmd: &str) -> TgErr<()> {
117 | tokio::try_join!(
118 | check_command_disabled(cx, cmd.to_string()),
119 | sudo_or_owner_filter(cx.update.from().unwrap().id)
120 | )?;
121 |
122 | if let Some(text) = cx.update.text() {
123 | let (_, echo_text) = parse_command(text, consts::BOT_NAME).unwrap();
124 |
125 | //Sudo is a dumbfuck demote needed immediately
126 | if echo_text.is_empty() {
127 | return Ok(());
128 | }
129 |
130 | cx.reply_to(echo_text.join(" ")).await?;
131 | //Try to delete the echo text sent by the user
132 | cx.requester
133 | .delete_message(cx.chat_id(), cx.update.id)
134 | .await
135 | .ok();
136 | }
137 | Ok(())
138 | }
139 |
--------------------------------------------------------------------------------
/src/modules/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod admin;
2 | pub mod bans;
3 | pub mod chat;
4 | pub mod commands;
5 | pub mod disable;
6 | pub mod filters;
7 | pub mod log_channel;
8 | pub mod misc;
9 | pub mod msg_delete;
10 | pub mod restrict;
11 | pub mod start;
12 | pub mod sudo;
13 | pub mod user;
14 | pub mod warning;
15 | pub use admin::*;
16 | pub use bans::*;
17 | pub use chat::*;
18 | pub use commands::Command;
19 | pub use disable::*;
20 | pub use filters::*;
21 | pub use log_channel::*;
22 | pub use misc::*;
23 | pub use msg_delete::*;
24 | pub use restrict::*;
25 | pub use start::*;
26 | pub use sudo::*;
27 | pub use user::*;
28 | pub use warning::*;
29 |
--------------------------------------------------------------------------------
/src/modules/msg_delete.rs:
--------------------------------------------------------------------------------
1 | use crate::database::db_utils::get_log_channel;
2 | use crate::modules::send_log;
3 | use crate::util::{can_delete_messages, get_bot_id, get_chat_title, is_group};
4 | use crate::{get_mdb, Cxt, TgErr};
5 | use teloxide::prelude::*;
6 | use teloxide::types::ParseMode;
7 | use teloxide::utils::html;
8 | use tokio::time::Duration;
9 | pub async fn delete(cx: &Cxt) -> TgErr<()> {
10 | tokio::try_join!(
11 | is_group(cx),
12 | can_delete_messages(cx, get_bot_id(cx).await),
13 | can_delete_messages(cx, cx.update.from().unwrap().id),
14 | )?;
15 | if let Some(msg) = cx.update.reply_to_message() {
16 | let msg_id = msg.id;
17 | if let Err(m) = cx.requester.delete_message(cx.chat_id(), msg_id).await {
18 | cx.reply_to(format!(
19 | "Can't delete the message for the following reason\n{}
",
20 | m
21 | ))
22 | .parse_mode(ParseMode::Html)
23 | .await?;
24 | return Ok(());
25 | }
26 | } else {
27 | cx.reply_to("Reply to some message to delete it").await?;
28 | return Ok(());
29 | }
30 | if let Err(m) = cx
31 | .requester
32 | .delete_message(cx.chat_id(), cx.update.id)
33 | .await
34 | {
35 | cx.reply_to(format!(
36 | "Can't delete the message for the following reason{}
",
37 | m
38 | ))
39 | .parse_mode(ParseMode::Html)
40 | .await?;
41 | }
42 | Ok(())
43 | }
44 | pub async fn purge(cx: &Cxt) -> TgErr<()> {
45 | tokio::try_join!(
46 | is_group(cx),
47 | can_delete_messages(cx, get_bot_id(cx).await),
48 | can_delete_messages(cx, cx.update.from().unwrap().id),
49 | )?;
50 | let db = get_mdb().await;
51 | let mut count: u32 = 0;
52 | if let Some(msg) = cx.update.reply_to_message() {
53 | let msg_id = msg.id;
54 | let delete_to = cx.update.id;
55 | for m_id in (msg_id..delete_to).rev() {
56 | if let Err(m) = cx.requester.delete_message(cx.chat_id(), m_id).await {
57 | cx.reply_to(format!("Error in purging some of the messages reason message might be too old or this is not a supergroup\n Error Message: {}
",
58 | m
59 | ))
60 | .parse_mode(ParseMode::Html)
61 | .await?;
62 | return Ok(());
63 | }
64 | count += 1;
65 | }
66 | if let Err(m) = cx
67 | .requester
68 | .delete_message(cx.chat_id(), cx.update.id)
69 | .await
70 | {
71 | cx.requester
72 | .send_message(
73 | cx.chat_id(),
74 | format!(
75 | "Error while deleting messages\n Error Message:{}
",
76 | m
77 | ),
78 | )
79 | .parse_mode(ParseMode::Html)
80 | .await?;
81 | return Ok(());
82 | }
83 | } else {
84 | cx.reply_to("Reply to some message to purge").await?;
85 | return Ok(());
86 | }
87 | let msg = cx
88 | .requester
89 | .send_message(cx.chat_id(), format!("Purged {} messages", count))
90 | .await?;
91 | if let Some(l) = get_log_channel(&db, cx.chat_id()).await? {
92 | let admin = cx
93 | .requester
94 | .get_chat_member(cx.chat_id(), cx.update.from().unwrap().id)
95 | .await?
96 | .user;
97 | let logm = format!(
98 | "Chat title: {}\n#PURGE\nAdmin: {}\nNo of messages: {}",
99 | html::code_inline(&get_chat_title(cx, cx.chat_id()).await.unwrap()),
100 | html::user_mention(admin.id, &admin.full_name()),
101 | html::code_inline(&count.to_string())
102 | );
103 | send_log(cx, &logm, l).await?;
104 | }
105 | tokio::time::sleep(Duration::from_secs(4)).await;
106 | cx.requester.delete_message(cx.chat_id(), msg.id).await?;
107 | Ok(())
108 | }
109 |
--------------------------------------------------------------------------------
/src/modules/restrict.rs:
--------------------------------------------------------------------------------
1 | use chrono::{DateTime, NaiveDateTime, Utc};
2 | use teloxide::{
3 | payloads::{RestrictChatMemberSetters, SendMessageSetters},
4 | prelude::{GetChatId, Requester},
5 | types::{ChatPermissions, ParseMode},
6 | utils::{
7 | command::parse_command,
8 | html::{self, user_mention_or_link},
9 | },
10 | };
11 |
12 | use crate::{
13 | database::db_utils::get_log_channel,
14 | get_mdb,
15 | modules::send_log,
16 | util::{
17 | can_send_text, extract_text_id_from_reply, get_bot_id, get_chat_title, get_time, is_group,
18 | is_user_restricted, sudo_or_owner_filter, user_should_restrict, LockType, TimeUnit,
19 | },
20 | Cxt, TgErr, OWNER_ID, SUDO_USERS,
21 | };
22 |
23 | pub async fn temp_mute(cx: &Cxt) -> TgErr<()> {
24 | tokio::try_join!(
25 | is_group(cx), //Should be a group
26 | user_should_restrict(cx, get_bot_id(cx).await), //Bot Should have restrict rights
27 | user_should_restrict(cx, cx.update.from().unwrap().id), //User should have restrict rights
28 | )?;
29 | let db = get_mdb().await;
30 | let (user_id, text) = extract_text_id_from_reply(cx).await;
31 | let bot_id = get_bot_id(cx).await;
32 | if user_id.is_none() {
33 | cx.reply_to("No user was targetted").await?;
34 | return Ok(());
35 | }
36 |
37 | if text.is_none() {
38 | cx.reply_to("Mention muting time in s,m,h,d").await?;
39 | return Ok(());
40 | }
41 |
42 | if user_id.unwrap() == bot_id {
43 | cx.reply_to("I am not gonna mute myself fella! Try using your brain next time!")
44 | .await?;
45 | return Ok(());
46 | }
47 |
48 | if user_id.unwrap() == *OWNER_ID || (*SUDO_USERS).contains(&user_id.unwrap()) {
49 | cx.reply_to("I am not gonna mute my owner or my sudo users")
50 | .await?;
51 | return Ok(());
52 | }
53 |
54 | if let Ok(mem) = cx
55 | .requester
56 | .get_chat_member(cx.chat_id(), user_id.unwrap())
57 | .await
58 | {
59 | if !mem.can_be_edited() {
60 | cx.reply_to("I am not gonna mute an admin here").await?;
61 | return Ok(());
62 | }
63 |
64 | if mem.is_banned() || mem.is_left() {
65 | cx.reply_to(
66 | "This user is either left of banned from here there's no point of muting him",
67 | )
68 | .await?;
69 | return Ok(());
70 | }
71 | if sudo_or_owner_filter(user_id.unwrap()).await.is_ok() {
72 | cx.reply_to("This user is either my owner or my sudo user I am not gonna mute him")
73 | .await?;
74 | return Ok(());
75 | }
76 |
77 | if user_id.unwrap() == get_bot_id(cx).await {
78 | cx.reply_to("I am not gonna mute myself you idiot!").await?;
79 | return Ok(());
80 | }
81 | let u = text.unwrap().parse::();
82 | if u.is_err() {
83 | cx.reply_to("Please specify with proper unit: s,m,h,d")
84 | .await?;
85 | return Ok(());
86 | }
87 | let t = get_time(u.as_ref().unwrap());
88 | cx.requester
89 | .restrict_chat_member(cx.chat_id(), user_id.unwrap(), ChatPermissions::default())
90 | .until_date(
91 | DateTime::::from_utc(
92 | NaiveDateTime::from_timestamp(cx.update.date as i64, 0),
93 | Utc,
94 | ) + t,
95 | )
96 | .await?;
97 | cx.reply_to(format!("Muted for {} ", u.as_ref().unwrap()))
98 | .parse_mode(ParseMode::Html)
99 | .await?;
100 | if let Some(l) = get_log_channel(&db, cx.chat_id()).await? {
101 | let admin = cx
102 | .requester
103 | .get_chat_member(cx.chat_id(), cx.update.from().unwrap().id)
104 | .await?
105 | .user;
106 | let mem = cx
107 | .requester
108 | .get_chat_member(cx.chat_id(), user_id.unwrap())
109 | .await?;
110 | let logm = format!(
111 | "Chat title: {}\n#TEMP_MUTED\nAdmin: {}\nUser: {}\nUntil: {}\n",
112 | html::code_inline(&get_chat_title(cx, cx.chat_id()).await.unwrap()),
113 | html::user_mention(admin.id, &admin.full_name()),
114 | html::user_mention(user_id.unwrap(), &mem.user.full_name()),
115 | html::code_inline(&mem.until_date().unwrap().to_string())
116 | );
117 | send_log(cx, &logm, l).await?;
118 | }
119 | } else {
120 | cx.reply_to("Can't get this user maybe he's not in the group or he deleted his account")
121 | .await?;
122 | }
123 |
124 | Ok(())
125 | }
126 |
127 | pub async fn mute(cx: &Cxt) -> TgErr<()> {
128 | tokio::try_join!(
129 | is_group(cx), //Should be a group
130 | user_should_restrict(cx, get_bot_id(cx).await), //Bot Should have restrict rights
131 | user_should_restrict(cx, cx.update.from().unwrap().id), //User should have restrict rights
132 | )?;
133 | let db = get_mdb().await;
134 | let bot_id = get_bot_id(cx).await;
135 | let (user_id, text) = extract_text_id_from_reply(cx).await;
136 | if user_id.is_none() {
137 | cx.reply_to("No user was targeted").await?;
138 | return Ok(());
139 | }
140 | if user_id.unwrap() == bot_id {
141 | cx.reply_to("I am not gonna mute myself fella! Try using your brain next time!")
142 | .await?;
143 | return Ok(());
144 | }
145 |
146 | if user_id.unwrap() == *OWNER_ID || (*SUDO_USERS).contains(&user_id.unwrap()) {
147 | cx.reply_to("I am not gonna mute my owner or one of my sudo users")
148 | .await?;
149 | return Ok(());
150 | }
151 | if let Ok(mem) = cx
152 | .requester
153 | .get_chat_member(cx.chat_id(), user_id.unwrap())
154 | .await
155 | {
156 | if !mem.can_be_edited() {
157 | cx.reply_to("I am not gonna mute an Admin Here!").await?;
158 | return Ok(());
159 | }
160 | } else {
161 | cx.reply_to("I can't seem to get info for this user")
162 | .await?;
163 | return Ok(());
164 | }
165 | let user = cx
166 | .requester
167 | .get_chat_member(cx.chat_id(), user_id.unwrap())
168 | .await
169 | .unwrap()
170 | .user;
171 | if can_send_text(cx, user_id.unwrap()).await? {
172 | cx.reply_to("User is already restricted").await?;
173 | return Ok(());
174 | }
175 | let reason = text.unwrap_or_else(|| String::from("None"));
176 | let mute_text = format!(
177 | "Muted \nUser: {}\n\nReason: {}",
178 | user_mention_or_link(&user),
179 | reason
180 | );
181 | cx.requester
182 | .restrict_chat_member(cx.chat_id(), user_id.unwrap(), ChatPermissions::default())
183 | .await?;
184 | cx.reply_to(mute_text).parse_mode(ParseMode::Html).await?;
185 | if let Some(l) = get_log_channel(&db, cx.chat_id()).await? {
186 | let admin = cx
187 | .requester
188 | .get_chat_member(cx.chat_id(), cx.update.from().unwrap().id)
189 | .await?
190 | .user;
191 | let user = cx
192 | .requester
193 | .get_chat_member(cx.chat_id(), user_id.unwrap())
194 | .await?
195 | .user;
196 | let logm = format!(
197 | "Chat title: {}\n#MUTED\nAdmin: {}\nUser: {}",
198 | html::code_inline(&get_chat_title(cx, cx.chat_id()).await.unwrap()),
199 | html::user_mention(admin.id, &admin.full_name()),
200 | html::user_mention(user_id.unwrap(), &user.full_name())
201 | );
202 | send_log(cx, &logm, l).await?;
203 | }
204 | Ok(())
205 | }
206 | pub async fn unmute(cx: &Cxt) -> TgErr<()> {
207 | tokio::try_join!(
208 | is_group(cx), //Should be a group
209 | user_should_restrict(cx, get_bot_id(cx).await), //Bot Should have restrict rights
210 | user_should_restrict(cx, cx.update.from().unwrap().id), //User should have restrict rights
211 | )?;
212 | let perm: ChatPermissions = ChatPermissions::new()
213 | .can_send_messages(true)
214 | .can_send_media_messages(true)
215 | .can_send_other_messages(true)
216 | .can_send_polls(true)
217 | .can_add_web_page_previews(true);
218 | let (user_id, _text) = extract_text_id_from_reply(cx).await;
219 | if user_id.is_none() {
220 | cx.reply_to("No user was targeted").await?;
221 | return Ok(());
222 | }
223 | let member = cx
224 | .requester
225 | .get_chat_member(cx.chat_id(), user_id.unwrap())
226 | .await?;
227 |
228 | if member.is_banned() || member.is_left() {
229 | cx.reply_to("This user already banned/left from the group")
230 | .await?;
231 | return Ok(());
232 | }
233 | if !is_user_restricted(cx, user_id.unwrap()).await? {
234 | cx.reply_to("This user can already talk!").await?;
235 | return Ok(());
236 | }
237 | cx.requester
238 | .restrict_chat_member(cx.chat_id(), user_id.unwrap(), perm)
239 | .await?;
240 | cx.reply_to("Unmuted ")
241 | .parse_mode(ParseMode::Html)
242 | .await?;
243 | Ok(())
244 | }
245 |
246 | pub async fn lock(cx: &Cxt) -> TgErr<()> {
247 | tokio::try_join!(
248 | is_group(cx), //Should be a group
249 | user_should_restrict(cx, get_bot_id(cx).await), //Bot Should have restrict rights
250 | user_should_restrict(cx, cx.update.from().unwrap().id), //User should have restrict rights
251 | )?;
252 | let (_, args) = parse_command(cx.update.text().unwrap(), "consts::BOT_NAME").unwrap();
253 | if args.is_empty() {
254 | cx.reply_to("What should I lock?").await?;
255 | return Ok(());
256 | }
257 | let locktype = args[0].to_lowercase().parse::().unwrap();
258 | if let Ok(chat) = cx.requester.get_chat(cx.chat_id()).await {
259 | match locktype {
260 | LockType::Text(_) => {
261 | cx.requester
262 | .set_chat_permissions(cx.chat_id(), ChatPermissions::default())
263 | .await?;
264 | cx.reply_to(format!("{}", LockType::Text("Lock".to_string())))
265 | .parse_mode(ParseMode::Html)
266 | .await?;
267 | }
268 | LockType::Other(_) => {
269 | let perm = chat.permissions().unwrap().can_send_other_messages(false);
270 | cx.requester
271 | .set_chat_permissions(cx.chat_id(), perm)
272 | .await?;
273 | cx.reply_to(format!("{}", LockType::Other("Lock".to_string())))
274 | .parse_mode(ParseMode::Html)
275 | .await?;
276 | }
277 | LockType::Media(_) => {
278 | let perm = chat
279 | .permissions()
280 | .unwrap()
281 | .can_send_media_messages(false)
282 | .can_send_other_messages(false)
283 | .can_add_web_page_previews(false);
284 | cx.requester
285 | .set_chat_permissions(cx.chat_id(), perm)
286 | .await?;
287 | cx.reply_to(format!("{}", LockType::Media("Lock".to_string())))
288 | .parse_mode(ParseMode::Html)
289 | .await?;
290 | }
291 | LockType::Poll(_) => {
292 | let perm = chat.permissions().unwrap().can_send_polls(false);
293 | cx.requester
294 | .set_chat_permissions(cx.chat_id(), perm)
295 | .await?;
296 | cx.reply_to(format!("{}", LockType::Poll("Lock".to_string())))
297 | .parse_mode(ParseMode::Html)
298 | .await?;
299 | }
300 | LockType::Web(_) => {
301 | let perm = chat.permissions().unwrap().can_add_web_page_previews(false);
302 | cx.requester
303 | .set_chat_permissions(cx.chat_id(), perm)
304 | .await?;
305 | cx.reply_to(format!("{}", LockType::Web("Lock".to_string())))
306 | .parse_mode(ParseMode::Html)
307 | .await?;
308 | }
309 | LockType::Error(_) => {
310 | cx.reply_to(format!("{}", locktype)).await?;
311 | }
312 | }
313 | } else {
314 | cx.reply_to("Can't get info about the chat").await?;
315 | }
316 | Ok(())
317 | }
318 |
319 | pub async fn unlock(cx: &Cxt) -> TgErr<()> {
320 | tokio::try_join!(
321 | is_group(cx), //Should be a group
322 | user_should_restrict(cx, get_bot_id(cx).await), //Bot Should have restrict rights
323 | user_should_restrict(cx, cx.update.from().unwrap().id), //User should have restrict rights
324 | )?;
325 | let (_, args) = parse_command(cx.update.text().unwrap(), "consts::BOT_NAME").unwrap();
326 | if args.is_empty() {
327 | cx.reply_to("What should I unlock?").await?;
328 | return Ok(());
329 | }
330 | let locktype = args[0].to_lowercase().parse::().unwrap();
331 | if let Ok(chat) = cx.requester.get_chat(cx.chat_id()).await {
332 | match locktype {
333 | LockType::Text(_) => {
334 | let perm = chat
335 | .permissions()
336 | .unwrap()
337 | .can_send_messages(true)
338 | .can_add_web_page_previews(true)
339 | .can_send_media_messages(true)
340 | .can_send_other_messages(true)
341 | .can_send_polls(true);
342 | cx.requester
343 | .set_chat_permissions(cx.chat_id(), perm)
344 | .await?;
345 | cx.reply_to(format!("{}", LockType::Text("Unlock".to_string())))
346 | .parse_mode(ParseMode::Html)
347 | .await?;
348 | }
349 | LockType::Other(_) => {
350 | let perm = chat.permissions().unwrap().can_send_other_messages(true);
351 | cx.requester
352 | .set_chat_permissions(cx.chat_id(), perm)
353 | .await?;
354 | cx.reply_to(format!("{}", LockType::Other("Unlock".to_string())))
355 | .parse_mode(ParseMode::Html)
356 | .await?;
357 | }
358 | LockType::Media(_) => {
359 | let perm = chat.permissions().unwrap().can_send_media_messages(true);
360 | cx.requester
361 | .set_chat_permissions(cx.chat_id(), perm)
362 | .await?;
363 | cx.reply_to(format!("{}", LockType::Media("Unlock".to_string())))
364 | .parse_mode(ParseMode::Html)
365 | .await?;
366 | }
367 | LockType::Poll(_) => {
368 | let perm = chat.permissions().unwrap().can_send_polls(true);
369 | cx.requester
370 | .set_chat_permissions(cx.chat_id(), perm)
371 | .await?;
372 | cx.reply_to(format!("{}", LockType::Poll("Unlock".to_string())))
373 | .parse_mode(ParseMode::Html)
374 | .await?;
375 | }
376 | LockType::Web(_) => {
377 | let perm = chat.permissions().unwrap().can_add_web_page_previews(true);
378 | cx.requester
379 | .set_chat_permissions(cx.chat_id(), perm)
380 | .await?;
381 | cx.reply_to(format!("{}", LockType::Web("Unlock".to_string())))
382 | .parse_mode(ParseMode::Html)
383 | .await?;
384 | }
385 | LockType::Error(_) => {
386 | cx.reply_to(format!("{}", locktype)).await?;
387 | }
388 | }
389 | } else {
390 | cx.reply_to("Can't get info about the chat").await?;
391 | }
392 | Ok(())
393 | }
394 |
395 | pub async fn locktypes(cx: &Cxt) -> TgErr<()> {
396 | tokio::try_join!(is_group(cx),)?;
397 | cx.reply_to("Following Locktypes are available: \nall\ntext\nsticker\ngif\nurl\nweb\nmedia\npoll\n
").parse_mode(ParseMode::Html).await?;
398 | Ok(())
399 | }
400 |
--------------------------------------------------------------------------------
/src/modules/start.rs:
--------------------------------------------------------------------------------
1 | use super::commands::Command;
2 | use crate::teloxide::utils::command::BotCommand;
3 | use crate::util::check_command_disabled;
4 | use crate::{Cxt, TgErr};
5 | use teloxide::utils::html::user_mention_or_link;
6 |
7 | pub async fn start_handler(cx: &Cxt, cmd: &str) -> TgErr<()> {
8 | tokio::try_join!(check_command_disabled(cx, String::from(cmd)))?;
9 | let start_message_priv = format!(
10 | "Hello {}! Hope you are doing well\n Send /help to know about available commands",
11 | user_mention_or_link(cx.update.from().unwrap())
12 | );
13 | let start_message_pub = "I am alive boss!".to_owned();
14 |
15 | if cx.update.chat.is_private() {
16 | cx.reply_to(start_message_priv).await?;
17 | return Ok(());
18 | }
19 | cx.reply_to(start_message_pub).await?;
20 | Ok(())
21 | }
22 |
23 | pub async fn help_handler(cx: &Cxt) -> TgErr<()> {
24 | let descriptions = Command::descriptions();
25 | if cx.update.chat.is_group() || cx.update.chat.is_supergroup() {
26 | cx.reply_to("This command is meant to be used in private")
27 | .await?;
28 | return Ok(());
29 | }
30 | cx.reply_to(descriptions).await?;
31 | Ok(())
32 | }
33 |
--------------------------------------------------------------------------------
/src/modules/sudo.rs:
--------------------------------------------------------------------------------
1 | use crate::database::{
2 | db_utils::{gban_user, get_all_chats, is_gbanned, set_gbanstat, ungban_user},
3 | Gban, GbanStat,
4 | };
5 | use crate::util::{
6 | extract_text_id_from_reply, get_bot_id, is_group, owner_filter, sudo_or_owner_filter,
7 | user_should_be_admin, GbanStats,
8 | };
9 | use crate::{get_mdb, Cxt, TgErr, OWNER_ID, SUDO_USERS};
10 | use teloxide::payloads::SendMessageSetters;
11 | use teloxide::prelude::*;
12 | use teloxide::types::{ChatKind, ParseMode};
13 | use teloxide::utils::command::parse_command;
14 | use teloxide::utils::html;
15 |
16 | pub async fn leavechat(cx: &Cxt) -> TgErr<()> {
17 | tokio::try_join!(owner_filter(cx.update.from().unwrap().id),)?;
18 | let (_, txt) = parse_command(cx.update.text().unwrap(), "consts::BOT_NAME").unwrap();
19 | let args = txt.get(0);
20 | if args.is_none() {
21 | cx.reply_to("Mention a chat id to leave").await?;
22 | return Ok(());
23 | }
24 | let chat_id = args.unwrap().parse::().unwrap_or(0);
25 | if let Ok(chat) = cx.requester.get_chat(chat_id).await {
26 | match chat.kind {
27 | ChatKind::Public(pu) => {
28 | cx.requester.leave_chat(chat_id).await?;
29 | cx.requester
30 | .send_message(
31 | *OWNER_ID,
32 | format!(
33 | "I have left {}
boss",
34 | html::escape(&pu.title.unwrap())
35 | ),
36 | )
37 | .parse_mode(ParseMode::Html)
38 | .await?;
39 | return Ok(());
40 | }
41 | ChatKind::Private(_) => {
42 | cx.reply_to(
43 | "The chat id you provided belongs to some user I can only leave groups",
44 | )
45 | .await?;
46 | return Ok(());
47 | }
48 | }
49 | } else {
50 | cx.reply_to("Either you gave me a non-valid chat id or I have been kicked from that group")
51 | .await?;
52 | }
53 | Ok(())
54 | }
55 |
56 | pub async fn chatlist(cx: &Cxt) -> TgErr<()> {
57 | tokio::try_join!(owner_filter(cx.update.from().unwrap().id))?;
58 | let db = get_mdb().await;
59 | let chatlist = get_all_chats(&db).await?;
60 | let mut chat_string = String::new();
61 | for c in chatlist {
62 | if let Ok(chat) = cx.requester.get_chat(c).await {
63 | if let ChatKind::Public(pu) = chat.kind {
64 | let s = format!("- {} : {}
\n", pu.title.unwrap(), &c);
65 | chat_string.push_str(&s);
66 | }
67 | }
68 | }
69 | cx.reply_to(format!(
70 | "The chat id's of the chats I am in \n {}
",
71 | chat_string
72 | ))
73 | .parse_mode(ParseMode::Html)
74 | .await?;
75 | Ok(())
76 | }
77 |
78 | pub async fn gban(cx: &Cxt) -> TgErr<()> {
79 | tokio::try_join!(sudo_or_owner_filter(cx.update.from().unwrap().id))?;
80 | let (user_id, text) = extract_text_id_from_reply(cx).await;
81 | let db = get_mdb().await;
82 | if user_id.is_none() {
83 | cx.reply_to("Specify someone to gban").await?;
84 | return Ok(());
85 | }
86 | let reason = text.unwrap_or_else(String::new);
87 | let gb = &Gban {
88 | user_id: user_id.unwrap(),
89 | reason: reason.clone(),
90 | };
91 | if (*SUDO_USERS).contains(&user_id.unwrap()) {
92 | cx.reply_to("I am not gonna ban a sudo user").await?;
93 | return Ok(());
94 | }
95 | if user_id.unwrap() == *OWNER_ID {
96 | cx.reply_to("I am not gonna gban my owner of all people")
97 | .await?;
98 | return Ok(());
99 | }
100 | if user_id.unwrap() == get_bot_id(cx).await {
101 | cx.reply_to("Haha I am not gonna ban myself fuck off!")
102 | .await?;
103 | return Ok(());
104 | }
105 | if is_gbanned(&db, &user_id.unwrap()).await? {
106 | if reason.is_empty() {
107 | cx.reply_to("This user is already gbanned I would have loved to change the reason for his gban but you haven't given me one").await?;
108 | return Ok(());
109 | }
110 | gban_user(&db, gb).await?;
111 | return Ok(());
112 | }
113 | let msg = cx.reply_to("Gbanning the user...").await?;
114 | gban_user(&db, gb).await?;
115 | let chats = get_all_chats(&db).await?;
116 | for c in chats {
117 | if let Ok(chatmem) = cx.requester.get_chat_member(c, user_id.unwrap()).await {
118 | if chatmem.is_privileged() || chatmem.is_banned() {
119 | continue;
120 | }
121 | if cx
122 | .requester
123 | .kick_chat_member(c, user_id.unwrap())
124 | .await
125 | .is_err()
126 | {
127 | continue;
128 | }
129 | }
130 | }
131 | cx.requester
132 | .edit_message_text(cx.chat_id(), msg.id, "Gbanned the fucker")
133 | .await?;
134 | Ok(())
135 | }
136 |
137 | pub async fn ungban(cx: &Cxt) -> TgErr<()> {
138 | let (user_id, _) = extract_text_id_from_reply(cx).await;
139 | if user_id.is_none() {
140 | cx.reply_to("Refer someone to gban").await?;
141 | return Ok(());
142 | }
143 | let db = get_mdb().await;
144 | if (*SUDO_USERS).contains(&user_id.unwrap()) {
145 | cx.reply_to("Pretty sure this user isn't gbanned because he's my sudo user")
146 | .await?;
147 | return Ok(());
148 | }
149 | if user_id.unwrap() == *OWNER_ID {
150 | cx.reply_to("This user is not gbanned because he's my owner")
151 | .await?;
152 | return Ok(());
153 | }
154 | if user_id.unwrap() == get_bot_id(cx).await {
155 | cx.reply_to("The day I gban myself is the release date of Halflife 3")
156 | .await?;
157 | return Ok(());
158 | }
159 | if is_gbanned(&db, &user_id.unwrap()).await? {
160 | ungban_user(&db, &user_id.unwrap()).await?;
161 | let chats = get_all_chats(&db).await?;
162 | let msg = cx.reply_to("Ungbanning the poor fucker").await?;
163 | for c in chats {
164 | if let Ok(mem) = cx.requester.get_chat_member(c, user_id.unwrap()).await {
165 | if mem.is_banned()
166 | && cx
167 | .requester
168 | .unban_chat_member(c, user_id.unwrap())
169 | .await
170 | .is_err()
171 | {
172 | continue;
173 | }
174 | }
175 | }
176 | cx.requester
177 | .edit_message_text(cx.chat_id(), msg.id, "Ungban Completed")
178 | .await?;
179 | } else {
180 | cx.reply_to("Why are you trying to ungban the user who's not even gbanned")
181 | .await?;
182 | }
183 | Ok(())
184 | }
185 |
186 | pub async fn gbanstat(cx: &Cxt) -> TgErr<()> {
187 | tokio::try_join!(
188 | is_group(cx),
189 | user_should_be_admin(cx, cx.update.from().unwrap().id),
190 | )?;
191 | let (_, args) = parse_command(cx.update.text().unwrap(), "consts::BOT_NAME").unwrap();
192 | let db = get_mdb().await;
193 | if args.is_empty() {
194 | cx.reply_to("What should I do with this?").await?;
195 | return Ok(());
196 | }
197 | let gstat = args[0].to_lowercase().parse::().unwrap();
198 | match gstat {
199 | GbanStats::On => {
200 | let gs = &GbanStat {
201 | chat_id: cx.chat_id(),
202 | is_on: true,
203 | };
204 | set_gbanstat(&db, gs).await?;
205 | cx.reply_to(
206 | "I have enabled Gbans for this chat you will be more protected from trolls now",
207 | )
208 | .await?;
209 | }
210 | GbanStats::Off => {
211 | let gs = &GbanStat {
212 | chat_id: cx.chat_id(),
213 | is_on: false,
214 | };
215 | set_gbanstat(&db, gs).await?;
216 | cx.reply_to(
217 | "I have disabled Gbans for this chat you will be less protected from trolls though",
218 | )
219 | .await?;
220 | }
221 | GbanStats::Error => {
222 | cx.reply_to("That's an invalid gbanstat input valid one's are (yes/on),(no,off)")
223 | .await?;
224 | }
225 | }
226 | Ok(())
227 | }
228 |
--------------------------------------------------------------------------------
/src/modules/user.rs:
--------------------------------------------------------------------------------
1 | use crate::database::db_utils::{get_gban_reason, is_gbanned};
2 | use crate::util::{check_command_disabled, extract_text_id_from_reply};
3 | use crate::{get_mdb, Cxt, TgErr, OWNER_ID, SUDO_USERS};
4 | use teloxide::prelude::*;
5 | use teloxide::types::{ChatKind, ForwardedFrom, ParseMode};
6 | use teloxide::utils::command::parse_command;
7 | use teloxide::utils::html::user_mention;
8 |
9 | pub async fn info(cx: &Cxt, cmd: &str) -> TgErr<()> {
10 | tokio::try_join!(check_command_disabled(cx, String::from(cmd)))?;
11 | let (user_id, _) = extract_text_id_from_reply(cx).await;
12 | let db = get_mdb().await;
13 | let (_, args) = parse_command(cx.update.text().unwrap(), "consts::BOT_NAME").unwrap();
14 | let chat = cx.update.chat.clone();
15 | let mut user = None;
16 | if user_id.is_some() && (chat.is_group() || chat.is_supergroup()) {
17 | user = match cx
18 | .requester
19 | .get_chat_member(cx.chat_id(), user_id.unwrap())
20 | .await
21 | {
22 | Ok(chatmem) => Some(chatmem.user),
23 | Err(_) => None,
24 | };
25 | } else if (chat.is_private()) || (cx.update.reply_to_message().is_none() && args.is_empty()) {
26 | user = Some(cx.update.from().unwrap().to_owned());
27 | } else if user_id.is_none() {
28 | cx.reply_to("This user is either dead or not in my database!")
29 | .await?;
30 | return Ok(());
31 | }
32 | if user.is_none() {
33 | cx.reply_to("Can't seem to get info about the user").await?;
34 | return Ok(());
35 | }
36 |
37 | let us_inf = user.unwrap();
38 | let is_rekt = is_gbanned(&db, &us_inf.id).await?;
39 | let mut info_text = format!(
40 | "User info :\nID:{}
\nFirst Name: {}",
41 | &us_inf.id, &us_inf.first_name
42 | );
43 |
44 | if let Some(ln) = us_inf.clone().last_name {
45 | info_text = format!("{}\nLast Name: {}", info_text, ln);
46 | }
47 |
48 | if let Some(un) = us_inf.clone().username {
49 | info_text = format!("{}\nUsername: @{}", info_text, un);
50 | }
51 |
52 | info_text = format!(
53 | "{}\nPermanent Link: {}",
54 | info_text,
55 | user_mention(us_inf.id, "link")
56 | );
57 |
58 | if is_rekt {
59 | info_text = format!(
60 | "{}\n\nThis is a gbanned user \nReason: {} ",
61 | info_text,
62 | &get_gban_reason(&db, &us_inf.id).await?
63 | );
64 | }
65 | if us_inf.id == *OWNER_ID {
66 | info_text = format!(
67 | "{}\n\nNote:-This user is my owner I will always be loyal to him ",
68 | info_text
69 | );
70 | } else if (*SUDO_USERS).contains(&us_inf.id) {
71 | info_text = format!(
72 | "{}\n\nNote:-This is one of my sudo users as powerful as my owner beware ",
73 | info_text
74 | );
75 | }
76 | cx.reply_to(info_text).parse_mode(ParseMode::Html).await?;
77 | Ok(())
78 | }
79 |
80 | pub async fn get_id(cx: &Cxt) -> TgErr<()> {
81 | let (user_id, _) = extract_text_id_from_reply(cx).await;
82 | if user_id.is_some() {
83 | if let Some(msg) = cx.update.reply_to_message() {
84 | let user = msg.from();
85 | if let Some(frwd) = msg.forward_from() {
86 | let us1 = user.unwrap();
87 | if let ForwardedFrom::User(us) = frwd {
88 | cx.reply_to(format!(
89 | "The sender {} has ID {}
and the forwarder {} has ID {}
",
90 | user_mention(us.id,&us.first_name),
91 | us.id,
92 | user_mention(us1.id,&us.first_name),
93 | us1.id))
94 | .parse_mode(ParseMode::Html)
95 | .await?;
96 | } else if let ForwardedFrom::SenderName(_) = frwd {
97 | cx.reply_to(format!(
98 | "{}'s ID is {}
",
99 | user_mention(us1.id, &us1.first_name),
100 | us1.id
101 | ))
102 | .parse_mode(ParseMode::Html)
103 | .await?;
104 | }
105 | } else if let Some(u) = user {
106 | cx.reply_to(format!(
107 | "{}'s ID is {}
",
108 | user_mention(u.id, &u.first_name),
109 | u.id
110 | ))
111 | .parse_mode(ParseMode::Html)
112 | .await?;
113 | } else {
114 | cx.reply_to("This user's dead I can't get his ID").await?;
115 | }
116 | } else if let ChatKind::Private(u) = cx.requester.get_chat(user_id.unwrap()).await?.kind {
117 | cx.reply_to(format!(
118 | "{}'s ID is {}
",
119 | user_mention(
120 | user_id.unwrap(),
121 | &u.first_name.unwrap_or_else(|| "".to_string())
122 | ),
123 | user_id.unwrap()
124 | ))
125 | .parse_mode(ParseMode::Html)
126 | .await?;
127 | }
128 | } else {
129 | let c = &cx.update.chat;
130 | cx.reply_to(format!("This chat has ID of {}
", c.id))
131 | .parse_mode(ParseMode::Html)
132 | .await?;
133 | }
134 | Ok(())
135 | }
136 |
--------------------------------------------------------------------------------
/src/modules/warning.rs:
--------------------------------------------------------------------------------
1 | use regex::Regex;
2 | use teloxide::payloads::SendMessageSetters;
3 | use teloxide::prelude::{GetChatId, Requester};
4 | use teloxide::types::{ChatKind, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode};
5 | use teloxide::utils::command::parse_command;
6 | use teloxide::utils::html::{user_mention, user_mention_or_link};
7 |
8 | use crate::database::db_utils::{
9 | get_softwarn, get_warn_count, get_warn_limit, insert_warn, reset_warn, rm_single_warn,
10 | set_softwarn, set_warn_limit,
11 | };
12 | use crate::database::{Warn, WarnKind, Warnlimit};
13 | use crate::util::{
14 | extract_text_id_from_reply, get_bot_id, is_group, is_user_admin, user_should_be_admin,
15 | user_should_restrict, WarnMode,
16 | };
17 | use crate::{get_mdb, Ctx, Cxt, TgErr};
18 | pub async fn warn(cx: &Cxt) -> TgErr<()> {
19 | tokio::try_join!(
20 | is_group(cx), //Should be a group
21 | user_should_restrict(cx, get_bot_id(cx).await), //Bot Should have restrict rights
22 | user_should_restrict(cx, cx.update.from().unwrap().id), //User should have restrict rights
23 | )?;
24 | let (user_id, text) = extract_text_id_from_reply(cx).await;
25 | if user_id.is_none() {
26 | cx.reply_to("No user was targeted").await?;
27 | return Ok(());
28 | }
29 | let reason = text.unwrap_or_else(String::new);
30 | warn_user(cx, user_id.unwrap(), reason).await?;
31 | Ok(())
32 | }
33 |
34 | pub async fn warn_user(cx: &Cxt, id: i64, reason: String) -> TgErr<()> {
35 | let bot_id = get_bot_id(cx).await;
36 | let db = get_mdb().await;
37 | if id == bot_id {
38 | cx.reply_to("I am not gonna warn myself fella! Try using your brain next time!")
39 | .await?;
40 | return Ok(());
41 | }
42 |
43 | if is_user_admin(cx, id).await {
44 | cx.reply_to("I am not gonna warn an admin here!").await?;
45 | return Ok(());
46 | }
47 | let w_count = get_warn_count(&db, cx.chat_id(), id).await?;
48 | let lim = get_warn_limit(&db, cx.chat_id()).await?;
49 | let mode = get_softwarn(&db, cx.chat_id()).await?;
50 | let warn = &Warn {
51 | chat_id: cx.chat_id(),
52 | user_id: id,
53 | reason: reason.clone(),
54 | count: (w_count + 1) as u64,
55 | };
56 | if let Ok(mem) = cx.requester.get_chat_member(cx.chat_id(), id).await {
57 | if (w_count + 1) >= lim {
58 | cx.requester.kick_chat_member(cx.chat_id(), id).await?;
59 | if mode {
60 | cx.requester.unban_chat_member(cx.chat_id(), id).await?;
61 | cx.reply_to(format!(
62 | "That's it get out ({}\\{}) warns, User has been kicked!",
63 | &w_count + 1,
64 | &lim
65 | ))
66 | .await?;
67 | } else {
68 | cx.reply_to(format!(
69 | "That's it get out ({}\\{}) warns, User has been banned!",
70 | &w_count + 1,
71 | &lim
72 | ))
73 | .await?;
74 | }
75 | reset_warn(&db, cx.chat_id(), id).await?;
76 | return Ok(());
77 | }
78 | let rm_warn_data = format!("rm_warn({},{})", cx.chat_id(), id);
79 | let warn_button = InlineKeyboardButton::callback("Remove Warn".to_string(), rm_warn_data);
80 | insert_warn(&db, warn).await?;
81 | cx.reply_to(format!(
82 | "Warned {}({}\\{})\nReason:{}",
83 | user_mention_or_link(&mem.user),
84 | &w_count + 1,
85 | &lim,
86 | &reason
87 | ))
88 | .reply_markup(InlineKeyboardMarkup::default().append_row(vec![warn_button]))
89 | .await?;
90 | } else {
91 | cx.reply_to("Can't get info about the user").await?;
92 | }
93 | Ok(())
94 | }
95 | pub async fn handle_unwarn_button(cx: &Ctx) -> TgErr<()> {
96 | let db = get_mdb().await;
97 | let data = &cx.update.data;
98 | if let Some(d) = data {
99 | let re = Regex::new(r#"rm_warn\((.+?),(.+?)\)"#).unwrap();
100 | let caps = re.captures(d).unwrap();
101 | let chat_id = caps
102 | .get(1)
103 | .map_or(0_i64, |s| s.as_str().parse::().unwrap());
104 | let user_id = cx.update.from.id;
105 | let warned_user = caps
106 | .get(2)
107 | .map_or(0_i64, |s| s.as_str().parse::().unwrap());
108 | let chatmem = cx.requester.get_chat_member(chat_id, user_id).await?;
109 | let count = get_warn_count(&db, chat_id, warned_user).await?;
110 | if chatmem.is_privileged() {
111 | if count == 0 || count.is_negative() {
112 | cx.requester
113 | .edit_message_text(
114 | chat_id,
115 | cx.update.message.clone().unwrap().id,
116 | "Warn is alredy removed",
117 | )
118 | .await?;
119 | return Ok(());
120 | }
121 | rm_single_warn(&db, chat_id, warned_user).await?;
122 | cx.requester
123 | .edit_message_text(
124 | chat_id,
125 | cx.update.message.clone().unwrap().id,
126 | format!("Warn Removed by {}", user_mention_or_link(&cx.update.from)),
127 | )
128 | .await?;
129 | } else {
130 | return Ok(());
131 | }
132 | }
133 | Ok(())
134 | }
135 | pub async fn warn_limit(cx: &Cxt) -> TgErr<()> {
136 | tokio::try_join!(
137 | is_group(cx), //Should be a group
138 | user_should_restrict(cx, get_bot_id(cx).await), //Bot Should have restrict rights
139 | user_should_restrict(cx, cx.update.from().unwrap().id), //User should have restrict rights
140 | )?;
141 | let db = get_mdb().await;
142 | let (_, args) = parse_command(cx.update.text().unwrap(), "consts::BOT_NAME").unwrap();
143 | if args.is_empty() {
144 | cx.reply_to("Send proper warn limit").await?;
145 | return Ok(());
146 | }
147 | let lim = match args[0].parse::() {
148 | Ok(val) => val,
149 | Err(_) => {
150 | cx.reply_to("Send a proper warn limit you idiot!").await?;
151 | return Ok(());
152 | }
153 | };
154 | let wl = &Warnlimit {
155 | chat_id: cx.chat_id(),
156 | limit: lim,
157 | };
158 | set_warn_limit(&db, wl).await?;
159 | cx.reply_to(format!("Warn limit set to {}", lim)).await?;
160 | Ok(())
161 | }
162 |
163 | pub async fn warnmode(cx: &Cxt) -> TgErr<()> {
164 | tokio::try_join!(
165 | is_group(cx),
166 | user_should_be_admin(cx, cx.update.from().unwrap().id),
167 | )?;
168 | let db = get_mdb().await;
169 | let (_, args) = parse_command(cx.update.text().unwrap(), "consts::BOT_NAME").unwrap();
170 | if args.is_empty() {
171 | cx.reply_to("Mention any option! Available one's are (soft/smooth),(hard/strong)")
172 | .await?;
173 | return Ok(());
174 | }
175 | let mode = args[0].to_lowercase().parse::().unwrap();
176 | match mode {
177 | WarnMode::Soft => {
178 | let wk = &WarnKind {
179 | chat_id: cx.chat_id(),
180 | softwarn: true,
181 | };
182 | set_softwarn(&db, wk).await?;
183 | cx.reply_to("Warnmode is set to soft. Now I will just kick the chat members when their warn exceeds the limit").await?;
184 | }
185 | WarnMode::Hard => {
186 | let wk = &WarnKind {
187 | chat_id: cx.chat_id(),
188 | softwarn: false,
189 | };
190 | set_softwarn(&db, wk).await?;
191 | cx.reply_to("Warnmode is set to hard. I will ban the chat members when their warn exceeds the limit").await?;
192 | }
193 | WarnMode::Error => {
194 | cx.reply_to("Invalid warnmode available one's are (soft/strong),(strong/hard)")
195 | .await?;
196 | }
197 | }
198 | Ok(())
199 | }
200 |
201 | pub async fn reset_warns(cx: &Cxt) -> TgErr<()> {
202 | tokio::try_join!(
203 | is_group(cx),
204 | user_should_be_admin(cx, cx.update.from().unwrap().id),
205 | )?;
206 | let db = get_mdb().await;
207 | let (user_id, _) = extract_text_id_from_reply(cx).await;
208 | let count = get_warn_count(&db, cx.chat_id(), user_id.unwrap()).await?;
209 | if let Ok(member) = cx
210 | .requester
211 | .get_chat_member(cx.chat_id(), user_id.unwrap())
212 | .await
213 | {
214 | if count > 0 {
215 | reset_warn(&db, cx.chat_id(), user_id.unwrap()).await?;
216 | cx.reply_to(format!(
217 | "Warns has been reset for the user {}",
218 | user_mention_or_link(&member.user)
219 | ))
220 | .await?;
221 | } else {
222 | cx.reply_to("User was not warned even once").await?;
223 | }
224 | } else {
225 | cx.reply_to("This user is not in the chat I can't unwarn him ")
226 | .await?;
227 | }
228 | Ok(())
229 | }
230 |
231 | pub async fn warns(cx: &Cxt) -> TgErr<()> {
232 | tokio::try_join!(
233 | is_group(cx),
234 | user_should_be_admin(cx, cx.update.from().unwrap().id),
235 | )?;
236 | let db = get_mdb().await;
237 | let limit = get_warn_limit(&db, cx.chat_id()).await?;
238 | let (user_id, _) = extract_text_id_from_reply(cx).await;
239 | if user_id.is_none() {
240 | if let Ok(chat) = cx.requester.get_chat(cx.chat_id()).await {
241 | if let ChatKind::Public(c) = chat.kind {
242 | cx.reply_to(format!("The chat {} has warn limit of {} when the warns exceed the limit the user will be banned from the group",c.title.clone().unwrap(),limit)).await?;
243 | return Ok(());
244 | }
245 | }
246 | }
247 | if let Ok(chatmem) = cx
248 | .requester
249 | .get_chat_member(cx.chat_id(), user_id.unwrap())
250 | .await
251 | {
252 | let count = get_warn_count(&db, cx.chat_id(), user_id.unwrap()).await?;
253 | if count <= 0 {
254 | cx.reply_to("This user got no warnings").await?;
255 | return Ok(());
256 | }
257 | cx.reply_to(format!(
258 | "User {} got {}/{} warnings",
259 | user_mention(user_id.unwrap(), &chatmem.user.full_name()),
260 | count,
261 | limit
262 | ))
263 | .parse_mode(ParseMode::Html)
264 | .await?;
265 | }
266 | Ok(())
267 | }
268 |
--------------------------------------------------------------------------------
/src/util/consts.rs:
--------------------------------------------------------------------------------
1 | pub const BOT_NAME: &str = "grpmr_bot";
2 |
--------------------------------------------------------------------------------
/src/util/custom_types.rs:
--------------------------------------------------------------------------------
1 | use std::{fmt::Display, str::FromStr};
2 |
3 | pub enum PinMode {
4 | Loud,
5 | Silent,
6 | Error,
7 | }
8 |
9 | impl FromStr for PinMode {
10 | type Err = &'static str;
11 | fn from_str(s: &str) -> Result::Err> {
12 | let ret = match s {
13 | "loud" | "hard" | "violent" => PinMode::Loud,
14 | "silent" => PinMode::Silent,
15 | _ => PinMode::Error,
16 | };
17 | Ok(ret)
18 | }
19 | }
20 |
21 | pub enum TimeUnit {
22 | Seconds(u64),
23 | Minutes(u64),
24 | Hours(u64),
25 | Days(u64),
26 | }
27 |
28 | impl FromStr for TimeUnit {
29 | type Err = &'static str;
30 | fn from_str(s: &str) -> Result::Err> {
31 | let split: Vec<_> = s.splitn(2, char::is_whitespace).collect();
32 | let num;
33 | let unit;
34 |
35 | if split.len() == 1 && split[0].ends_with(&['h', 'm', 's', 'd'][..]) && split[0].len() >= 2
36 | {
37 | let mut t = split[0].to_owned();
38 | let u = t.pop().unwrap().to_string();
39 | t = t.to_string();
40 |
41 | num = match t.parse::() {
42 | Ok(n) => n,
43 | Err(_) => {
44 | return Err("Invalid time unit use the following units: h, m, s, d");
45 | }
46 | };
47 | unit = u;
48 | } else if split.len() == 2 {
49 | num = match split[0].parse::() {
50 | Ok(n) => n,
51 | Err(_) => {
52 | return Err("Invalid time unit use the following units: h, m, s, d");
53 | }
54 | };
55 |
56 | unit = split[1].to_owned()
57 | } else {
58 | return Err("Invalid time unit use the following units: h, m, s, d");
59 | }
60 |
61 | match &unit as &str {
62 | "h" | "hours" => Ok(TimeUnit::Hours(num)),
63 | "m" | "minutes" => Ok(TimeUnit::Minutes(num)),
64 | "s" | "seconds" => Ok(TimeUnit::Seconds(num)),
65 | "d" | "days" => Ok(TimeUnit::Days(num)),
66 | _ => Err("Invalid time unit use the following units: h, m, s, d"),
67 | }
68 | }
69 | }
70 |
71 | impl Display for TimeUnit {
72 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73 | match self {
74 | TimeUnit::Seconds(t) => write!(f, "{} second(s)", t),
75 | TimeUnit::Minutes(t) => write!(f, "{} minute(s)", t),
76 | TimeUnit::Hours(t) => write!(f, "{} hour(s)", t),
77 | TimeUnit::Days(t) => write!(f, "{} day(s)", t),
78 | }
79 | }
80 | }
81 |
82 | pub enum LockType {
83 | Text(String),
84 | Other(String),
85 | Media(String),
86 | Poll(String),
87 | Web(String),
88 | Error(String),
89 | }
90 |
91 | impl FromStr for LockType {
92 | type Err = &'static str;
93 | fn from_str(s: &str) -> Result::Err> {
94 | let kind = String::new();
95 | let ret = match s {
96 | "all" | "text" => LockType::Text(kind),
97 | "sticker" | "gif" => LockType::Other(kind),
98 | "url" | "web" => LockType::Web(kind),
99 | "media" => LockType::Media(kind),
100 | "poll" => LockType::Poll(kind),
101 | _ => LockType::Error(kind),
102 | };
103 | Ok(ret)
104 | }
105 | }
106 |
107 | impl Display for LockType {
108 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 | match &self {
110 | LockType::Text(kind) => write!(f, "{}ed all for Non-admins", kind),
111 | LockType::Other(kind) => write!(f, "{}ed sticker,gif,game for Non-Admins", kind),
112 | LockType::Media(kind) => write!(
113 | f,
114 | "{}ed Media(photos,animations,documents,stickers/gif,video) for Non-Admins",
115 | kind
116 | ),
117 | LockType::Web(kind) => write!(f, "{}ed URL previewing for Non-Admins", kind),
118 | LockType::Poll(kind) => write!(f, "{}ed Polls for Non-Admins", kind),
119 | LockType::Error(_) => write!(
120 | f,
121 | "Invalid locktype please run /locktypes to check available locktypes"
122 | ),
123 | }
124 | }
125 | }
126 |
127 | pub enum GbanStats {
128 | On,
129 | Off,
130 | Error,
131 | }
132 |
133 | impl FromStr for GbanStats {
134 | type Err = &'static str;
135 | fn from_str(s: &str) -> Result::Err> {
136 | match s {
137 | "yes" | "on" => Ok(GbanStats::On),
138 | "no" | "off" => Ok(GbanStats::Off),
139 | _ => Ok(GbanStats::Error),
140 | }
141 | }
142 | }
143 |
144 | pub enum WarnMode {
145 | Soft,
146 | Hard,
147 | Error,
148 | }
149 |
150 | impl FromStr for WarnMode {
151 | type Err = &'static str;
152 | fn from_str(s: &str) -> Result::Err> {
153 | match s {
154 | "soft" | "smooth" => Ok(WarnMode::Soft),
155 | "hard" | "strong" => Ok(WarnMode::Hard),
156 | _ => Ok(WarnMode::Error),
157 | }
158 | }
159 | }
160 |
161 | pub enum DisableAble {
162 | Ud,
163 | Info,
164 | Start,
165 | Paste,
166 | Kickme,
167 | Adminlist,
168 | Error,
169 | }
170 |
171 | impl FromStr for DisableAble {
172 | type Err = &'static str;
173 | fn from_str(s: &str) -> Result::Err> {
174 | match s {
175 | "ud" => Ok(DisableAble::Ud),
176 | "info" => Ok(DisableAble::Info),
177 | "start" => Ok(DisableAble::Start),
178 | "paste" => Ok(DisableAble::Paste),
179 | "kickme" => Ok(DisableAble::Kickme),
180 | "adminlist" => Ok(DisableAble::Adminlist),
181 | _ => Ok(DisableAble::Error),
182 | }
183 | }
184 | }
185 |
186 | pub enum FilterType {
187 | Animation,
188 | Audio,
189 | Sticker,
190 | Photos,
191 | Document,
192 | Text,
193 | Voice,
194 | Video,
195 | Error,
196 | }
197 |
198 | impl FromStr for FilterType {
199 | type Err = &'static str;
200 | fn from_str(s: &str) -> Result::Err> {
201 | match s {
202 | "animation" => Ok(FilterType::Animation),
203 | "audio" => Ok(FilterType::Audio),
204 | "sticker" => Ok(FilterType::Sticker),
205 | "photo" => Ok(FilterType::Photos),
206 | "document" => Ok(FilterType::Document),
207 | "text" => Ok(FilterType::Text),
208 | "voice" => Ok(FilterType::Voice),
209 | "video" => Ok(FilterType::Video),
210 | _ => Ok(FilterType::Error),
211 | }
212 | }
213 | }
214 |
215 | pub enum BlacklistMode {
216 | Delete,
217 | Warn,
218 | Ban,
219 | Kick,
220 | Error,
221 | }
222 |
223 | impl FromStr for BlacklistMode {
224 | type Err = &'static str;
225 | fn from_str(s: &str) -> Result::Err> {
226 | match s {
227 | "delete" => Ok(BlacklistMode::Delete),
228 | "warn" => Ok(BlacklistMode::Warn),
229 | "ban" | "hard" => Ok(BlacklistMode::Ban),
230 | "kick" | "soft" => Ok(BlacklistMode::Kick),
231 | _ => Ok(BlacklistMode::Error),
232 | }
233 | }
234 | }
235 |
236 | pub enum ReportStatus {
237 | On,
238 | Off,
239 | Error,
240 | }
241 |
242 | impl FromStr for ReportStatus {
243 | type Err = &'static str;
244 | fn from_str(s: &str) -> Result::Err> {
245 | match s {
246 | "on" | "yes" => Ok(ReportStatus::On),
247 | "off" | "no" => Ok(ReportStatus::Off),
248 | _ => Ok(ReportStatus::Error),
249 | }
250 | }
251 | }
252 |
--------------------------------------------------------------------------------
/src/util/mod.rs:
--------------------------------------------------------------------------------
1 | pub mod consts;
2 | pub mod custom_types;
3 | pub mod utils;
4 | pub use consts::*;
5 | pub use custom_types::*;
6 | pub use utils::*;
7 |
--------------------------------------------------------------------------------
/src/util/utils.rs:
--------------------------------------------------------------------------------
1 | use chrono::Duration;
2 |
3 | use super::custom_types::*;
4 | use crate::database::db_utils::{
5 | get_disabled_command, get_gbanstat, get_userid_from_name, is_gbanned,
6 | };
7 | use crate::{get_mdb, Cxt, TgErr, OWNER_ID, SUDO_USERS};
8 | use anyhow::anyhow;
9 | use teloxide::prelude::*;
10 | use teloxide::types::{ChatKind, ChatMemberKind, MessageEntity, MessageEntityKind};
11 |
12 | pub async fn get_bot_id(cx: &Cxt) -> i64 {
13 | return cx.requester.get_me().await.unwrap().user.id;
14 | }
15 |
16 | pub async fn can_user_restrict(cx: &Cxt, user_id: i64) -> bool {
17 | let ret = cx
18 | .requester
19 | .get_chat_member(cx.chat_id(), user_id)
20 | .await
21 | .ok();
22 | if user_id == *OWNER_ID || (*SUDO_USERS).contains(&user_id) {
23 | return true;
24 | }
25 | if ret.is_none() {
26 | return false;
27 | }
28 | let mem = ret.unwrap();
29 | if mem.is_owner() {
30 | return true;
31 | }
32 | if let ChatMemberKind::Administrator(a) = mem.kind {
33 | if a.can_restrict_members {
34 | return true;
35 | }
36 | }
37 | false
38 | }
39 | pub async fn user_should_restrict(cx: &Cxt, user_id: i64) -> TgErr<()> {
40 | if can_user_restrict(cx, user_id).await {
41 | return Ok(());
42 | }
43 | if user_id == get_bot_id(cx).await {
44 | cx.reply_to("I can't restrict people here make sure you gave me proper rights to do so!!")
45 | .await?;
46 | } else {
47 | cx.reply_to("You can't restrict people here!!").await?;
48 | }
49 | Err(anyhow!("User don't have the permission to restrict"))
50 | }
51 | pub async fn is_user_admin(cx: &Cxt, user_id: i64) -> bool {
52 | let ret = cx
53 | .requester
54 | .get_chat_member(cx.chat_id(), user_id)
55 | .await
56 | .ok();
57 |
58 | if user_id == *OWNER_ID || (*SUDO_USERS).contains(&user_id) {
59 | return true;
60 | }
61 | if ret.is_none() {
62 | return false;
63 | }
64 | let mem = ret.unwrap();
65 | if mem.is_privileged() {
66 | return true;
67 | }
68 | false
69 | }
70 | pub async fn user_should_be_admin(cx: &Cxt, user_id: i64) -> TgErr<()> {
71 | if is_user_admin(cx, user_id).await {
72 | return Ok(());
73 | }
74 | if user_id == get_bot_id(cx).await {
75 | cx.reply_to("I am not admin here!").await?;
76 | } else {
77 | cx.reply_to("You are not an admin here!").await?;
78 | }
79 | Err(anyhow!("User isnt admin"))
80 | }
81 | pub fn extract_id_from_reply(cx: &Cxt) -> Option {
82 | cx.update.reply_to_message()?.from().map(|u| u.id)
83 | }
84 | pub async fn extract_text_id_from_reply(cx: &Cxt) -> (Option, Option) {
85 | if let Some(msg_text) = cx.update.text() {
86 | let split_text: Vec<_> = msg_text.splitn(2, char::is_whitespace).collect();
87 |
88 | if split_text.len() < 2 {
89 | return (extract_id_from_reply(cx), None);
90 | }
91 |
92 | let text_to_parse = split_text[1];
93 | let args: Vec<_> = text_to_parse.split_whitespace().collect();
94 |
95 | let mut user_id: Option = None;
96 | let mut text: Option = None;
97 | let mut ent: Option<&MessageEntity> = None;
98 |
99 | if let Some(entities) = cx.update.entities() {
100 | if entities
101 | .iter()
102 | .any(|entity| matches!(entity.kind, MessageEntityKind::TextMention { user: _ }))
103 | {
104 | ent = Some(&entities[0]);
105 | }
106 |
107 | if !entities.is_empty() && ent.is_some() {
108 | if ent.unwrap().offset == msg_text.len() - text_to_parse.len() {
109 | ent = Some(&entities[0]);
110 | user_id = match &ent.unwrap().kind {
111 | MessageEntityKind::TextMention { user } => Some(user.id),
112 | _ => None,
113 | };
114 | text = Some(msg_text[ent.unwrap().offset + ent.unwrap().length..].to_owned());
115 | }
116 | } else if !args.is_empty() && args[0].starts_with('@') {
117 | let user_name = args[0];
118 | let db = get_mdb().await;
119 | let res = get_userid_from_name(
120 | &db,
121 | user_name.to_string().replace("@", "").to_lowercase(),
122 | )
123 | .await;
124 | if res.is_ok() {
125 | user_id = res.unwrap();
126 | let split: Vec<_> = msg_text.splitn(3, char::is_whitespace).collect();
127 | if split.len() >= 3 {
128 | text = Some(split[2].to_owned());
129 | }
130 | } else {
131 | cx.reply_to(
132 | "Could not find a user by this name; are you sure I've seen them before?",
133 | )
134 | .await
135 | .ok();
136 | return (None, None);
137 | }
138 | } else if !args.is_empty() {
139 | if let Ok(id) = args[0].parse::() {
140 | user_id = Some(id);
141 | let res: Vec<_> = msg_text.splitn(3, char::is_whitespace).collect();
142 | if res.len() >= 3 {
143 | text = Some(res[2].to_owned());
144 | }
145 | } else if cx.update.reply_to_message().is_some() {
146 | if let Some(u) = cx.update.reply_to_message().unwrap().from() {
147 | user_id = Some(u.id);
148 | }
149 | let res: Vec<_> = msg_text.splitn(2, char::is_whitespace).collect();
150 | if res.len() >= 2 {
151 | text = Some(res[1].to_owned());
152 | }
153 | }
154 | } else if cx.update.reply_to_message().is_some() {
155 | user_id = extract_id_from_reply(cx);
156 | } else {
157 | return (None, None);
158 | }
159 |
160 | if let Some(id) = user_id {
161 | match cx.requester.get_chat(id).await {
162 | Ok(_) => {}
163 | Err(_) => {
164 | cx.reply_to("I don't seem to have interacted with this user before - please forward a message from them to give me control! (like a voodoo doll, I need a piece of them to be able to execute certain commands...)").await.ok();
165 | return (None, None);
166 | }
167 | }
168 | }
169 | }
170 | return (user_id, text);
171 | }
172 | (None, None)
173 | }
174 |
175 | pub async fn is_group(cx: &Cxt) -> TgErr<()> {
176 | let c = &cx.update.chat;
177 | if c.is_group() || c.is_supergroup() {
178 | return Ok(());
179 | }
180 | cx.reply_to("This command can't be used in private").await?;
181 | Err(anyhow!("This isnt a group"))
182 | }
183 |
184 | pub async fn can_send_text(cx: &Cxt, id: i64) -> TgErr {
185 | if cx.update.chat.is_private() {
186 | return Ok(false);
187 | }
188 | let mem = cx.requester.get_chat_member(cx.chat_id(), id).await?;
189 | let restricted = mem.kind.can_send_messages();
190 | Ok(!restricted)
191 | }
192 |
193 | pub async fn is_user_restricted(cx: &Cxt, id: i64) -> anyhow::Result {
194 | if cx.update.chat.is_private() {
195 | return Ok(false);
196 | }
197 | let mem = cx.requester.get_chat_member(cx.chat_id(), id).await?;
198 | let restricted = mem.kind.can_send_messages()
199 | && mem.kind.can_send_media_messages()
200 | && mem.kind.can_send_other_messages()
201 | && mem.kind.can_add_web_page_previews();
202 | Ok(!restricted)
203 | }
204 |
205 | pub async fn can_pin_messages(cx: &Cxt, id: i64) -> TgErr<()> {
206 | let mem = cx.requester.get_chat_member(cx.chat_id(), id).await?;
207 | if id == *OWNER_ID || (*SUDO_USERS).contains(&id) {
208 | return Ok(());
209 | }
210 | match mem.kind {
211 | ChatMemberKind::Owner(_) => {
212 | return Ok(());
213 | }
214 | ChatMemberKind::Administrator(_) => {
215 | if mem.kind.can_pin_messages() {
216 | return Ok(());
217 | }
218 | }
219 | _ => {}
220 | }
221 | if id == get_bot_id(cx).await {
222 | cx.reply_to("I can't pin messages here! Missing can_pin_messages permission")
223 | .await?;
224 | } else {
225 | cx.reply_to("You can't pin messages here! Missing can_pin_messages permissions")
226 | .await?;
227 | }
228 | Err(anyhow!(
229 | "Can't pin messages because missing can_pin_messages permissions"
230 | ))
231 | }
232 |
233 | pub async fn user_should_be_creator(cx: &Cxt, id: i64) -> TgErr<()> {
234 | let mem = cx.requester.get_chat_member(cx.chat_id(), id).await?;
235 | if mem.is_owner() {
236 | return Ok(());
237 | }
238 | Err(anyhow!("User is not a creator"))
239 | }
240 |
241 | pub async fn can_delete_messages(cx: &Cxt, id: i64) -> TgErr<()> {
242 | let mem = cx.requester.get_chat_member(cx.chat_id(), id).await?;
243 | if id == *OWNER_ID || (*SUDO_USERS).contains(&id) {
244 | return Ok(());
245 | }
246 | match mem.kind {
247 | ChatMemberKind::Owner(_) => {
248 | return Ok(());
249 | }
250 | ChatMemberKind::Administrator(_) => {
251 | if mem.kind.can_delete_messages() {
252 | return Ok(());
253 | }
254 | }
255 | _ => {}
256 | };
257 | if id == get_bot_id(cx).await {
258 | cx.reply_to("I can't delete messages here! Missing can_delete_messages permission")
259 | .await?;
260 | } else {
261 | cx.reply_to("You can't delete messages here! Missing can_delete_messages permission")
262 | .await?;
263 | }
264 | Err(anyhow!(
265 | "Can't delete messages missing can_delete_messages permission"
266 | ))
267 | }
268 | pub async fn can_promote_members(cx: &Cxt, id: i64) -> TgErr<()> {
269 | let mem = cx.requester.get_chat_member(cx.chat_id(), id).await?;
270 | if id == *OWNER_ID || (*SUDO_USERS).contains(&id) {
271 | return Ok(());
272 | }
273 | match mem.kind {
274 | ChatMemberKind::Owner(_) => {
275 | return Ok(());
276 | }
277 | ChatMemberKind::Administrator(_) => {
278 | if mem.kind.can_promote_members() {
279 | return Ok(());
280 | }
281 | }
282 | _ => {}
283 | }
284 | if id == get_bot_id(cx).await {
285 | cx.reply_to("I can't promote members here! Missing can_promote_members permission")
286 | .await?;
287 | } else {
288 | cx.reply_to("You can't promote members here! Missing can_promote_members permission")
289 | .await?;
290 | }
291 | Err(anyhow!(
292 | "Can't promote members because user is missing can_promote_members permissions"
293 | ))
294 | }
295 |
296 | pub async fn can_change_info(cx: &Cxt, id: i64) -> TgErr<()> {
297 | let mem = cx.requester.get_chat_member(cx.chat_id(), id).await?;
298 | if id == *OWNER_ID || (*SUDO_USERS).contains(&id) {
299 | return Ok(());
300 | }
301 | match mem.kind {
302 | ChatMemberKind::Owner(_) => {
303 | return Ok(());
304 | }
305 | ChatMemberKind::Administrator(_) => {
306 | if mem.can_change_info() {
307 | return Ok(());
308 | }
309 | }
310 | _ => {}
311 | }
312 | if id == get_bot_id(cx).await {
313 | cx.reply_to("I can't change group info here! Missing can_change_info permission")
314 | .await?;
315 | } else {
316 | cx.reply_to("You can't change group info here! Missing can_change_info permission")
317 | .await?;
318 | }
319 | Err(anyhow!(
320 | "Can't change group info because user is missing can_change_info permissions"
321 | ))
322 | }
323 |
324 | pub async fn owner_filter(uid: i64) -> TgErr<()> {
325 | if uid == *OWNER_ID {
326 | return Ok(());
327 | }
328 | Err(anyhow!("This command only works for owner"))
329 | }
330 |
331 | pub async fn sudo_or_owner_filter(uid: i64) -> TgErr<()> {
332 | if (*SUDO_USERS).contains(&uid) || *OWNER_ID == uid {
333 | return Ok(());
334 | }
335 | Err(anyhow!(
336 | "This command only works for either owner or sudo users"
337 | ))
338 | }
339 |
340 | pub async fn check_and_gban(cx: &Cxt, user_id: i64) -> TgErr<()> {
341 | let db = get_mdb().await;
342 | if is_gbanned(&db, &user_id).await? && get_gbanstat(&db, cx.chat_id()).await? {
343 | if cx
344 | .requester
345 | .kick_chat_member(cx.chat_id(), user_id)
346 | .await
347 | .is_err()
348 | {
349 | return Ok(());
350 | }
351 | cx.requester.send_message(cx.chat_id(),"This is a Gbanned user trying to sneak inside in my presence. I am banning him right away!").await?;
352 | }
353 | Ok(())
354 | }
355 |
356 | pub async fn enforce_gban(cx: &Cxt) -> TgErr<()> {
357 | if let Some(u) = cx.update.from() {
358 | check_and_gban(cx, u.id).await?;
359 | } else if let Some(new) = cx.update.new_chat_members() {
360 | for u in new {
361 | check_and_gban(cx, u.id).await?;
362 | }
363 | }
364 | Ok(())
365 | }
366 |
367 | pub fn get_time(unit: &TimeUnit) -> Duration {
368 | match unit {
369 | TimeUnit::Hours(t) => Duration::hours(*t as i64),
370 | TimeUnit::Minutes(t) => Duration::minutes(*t as i64),
371 | TimeUnit::Seconds(t) => Duration::seconds(*t as i64),
372 | TimeUnit::Days(t) => Duration::days(*t as i64),
373 | }
374 | }
375 |
376 | pub async fn is_command_disabled(chat_id: i64, cmd: String) -> bool {
377 | if !matches!(cmd.parse::().unwrap(), DisableAble::Error) {
378 | let db = get_mdb().await;
379 | let dis_cmds = get_disabled_command(&db, chat_id).await.unwrap();
380 | let ind = dis_cmds.iter().position(|p| p.eq(&cmd.to_lowercase()));
381 | return ind.is_some();
382 | }
383 | false
384 | }
385 |
386 | pub async fn check_command_disabled(cx: &Cxt, cmd: String) -> TgErr<()> {
387 | if cx.update.chat.is_group() || cx.update.chat.is_supergroup() {
388 | if !is_command_disabled(cx.chat_id(), cmd).await {
389 | return Ok(());
390 | } else {
391 | return Err(anyhow!("This command is disabled"));
392 | }
393 | }
394 | Ok(())
395 | }
396 |
397 | pub async fn get_filter_type(msg: &Message) -> String {
398 | if msg.audio().is_some() {
399 | return "audio".to_string();
400 | } else if msg.text().is_some() {
401 | return "text".to_string();
402 | } else if msg.document().is_some() {
403 | return "document".to_string();
404 | } else if msg.photo().is_some() {
405 | return "photo".to_string();
406 | } else if msg.video().is_some() {
407 | return "video".to_string();
408 | } else if msg.animation().is_some() {
409 | return "animation".to_string();
410 | } else if msg.voice().is_some() {
411 | return "voice".to_string();
412 | } else if msg.sticker().is_some() {
413 | return "sticker".to_string();
414 | }
415 | String::new()
416 | }
417 |
418 | pub async fn extract_filter_text(msg: &Message) -> Option {
419 | if msg.caption().is_some() {
420 | return msg.caption().map(|s| s.to_string());
421 | } else if msg.text().is_some() {
422 | return msg.text().map(|s| s.to_string());
423 | } else if msg.sticker().is_some() {
424 | return msg.sticker().map(|s| s.clone().emoji.unwrap());
425 | }
426 | None
427 | }
428 |
429 | pub async fn get_chat_title(cx: &Cxt, chat_id: i64) -> Option {
430 | if let Ok(chat) = cx.requester.get_chat(chat_id).await {
431 | if let ChatKind::Public(c) = chat.kind {
432 | return c.title;
433 | }
434 | }
435 | None
436 | }
437 |
--------------------------------------------------------------------------------