1use std::{future::Future, str::FromStr};
2
3use chrono::{DateTime, Duration, Utc};
4use teloxide::{
5 prelude::*,
6 types::{ChatMember, ChatPermissions, UserId},
7 utils::command::BotCommands,
8};
9
10#[derive(BotCommands, Clone)]
22#[command(rename_rule = "lowercase", parse_with = "split")]
23enum Command {
24 Kick,
26 Ban {
28 time: u64,
29 unit: UnitOfTime,
30 },
31 Mute {
33 time: u64,
34 unit: UnitOfTime,
35 },
36 Help,
37}
38
39#[derive(Clone)]
40enum UnitOfTime {
41 Seconds,
42 Minutes,
43 Hours,
44}
45
46impl FromStr for UnitOfTime {
47 type Err = &'static str;
48 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
49 match s {
50 "h" | "hours" => Ok(UnitOfTime::Hours),
51 "m" | "minutes" => Ok(UnitOfTime::Minutes),
52 "s" | "seconds" => Ok(UnitOfTime::Seconds),
53 _ => Err("Allowed units: h, m, s"),
54 }
55 }
56}
57
58#[tokio::main]
59async fn main() {
60 pretty_env_logger::init();
61 log::info!("Starting admin bot...");
62
63 let bot = teloxide::Bot::from_env();
64
65 Command::repl(bot, action).await;
66}
67
68async fn action(bot: Bot, msg: Message, cmd: Command) -> ResponseResult<()> {
69 if !matches!(&cmd, Command::Help)
70 && !sender_can_restrict(&msg, |chat, user| {
71 let bot = ⊥
72 async move { bot.get_chat_member(chat, user).await }
73 })
74 .await
75 {
76 bot.send_message(
77 "Only chat admins with permission to restrict members can use this command.",
78 )
79 .chat_id(msg.chat.id)
80 .await?;
81 return Ok(());
82 }
83
84 let is_ban = matches!(&cmd, Command::Ban { .. });
85 match cmd {
86 Command::Help => {
87 bot.send_message(Command::descriptions().to_string()).chat_id(msg.chat.id).await?;
88 }
89 Command::Kick => {
90 if let Some(target) = moderation_target(&bot, &msg).await? {
91 bot.unban_chat_member(msg.chat.id, target).await?;
93 }
94 }
95 Command::Ban { time, unit } | Command::Mute { time, unit } => {
96 let Some(target) = moderation_target(&bot, &msg).await? else {
97 return Ok(());
98 };
99 let Some(until) = restriction_end(msg.date, time, unit) else {
100 bot.send_message("Restriction duration is too large.").chat_id(msg.chat.id).await?;
101 return Ok(());
102 };
103 if is_ban {
104 bot.kick_chat_member(msg.chat.id, target).until_date(until).await?;
105 } else {
106 bot.restrict_chat_member(msg.chat.id, target, ChatPermissions::empty())
107 .until_date(until)
108 .await?;
109 }
110 }
111 };
112
113 Ok(())
114}
115
116async fn sender_can_restrict<E, F>(
117 msg: &Message,
118 get_member: impl FnOnce(ChatId, UserId) -> F,
119) -> bool
120where
121 F: Future<Output = Result<ChatMember, E>>,
122 E: std::fmt::Display,
123{
124 let Some(sender) = msg.from.as_ref().filter(|_| msg.sender_chat.is_none()) else {
126 return false;
127 };
128 match get_member(msg.chat.id, sender.id).await {
129 Ok(member) => member.kind.can_restrict_members(),
130 Err(err) => {
131 log::warn!("Could not verify moderation permissions in {}: {err}", msg.chat.id);
132 false
133 }
134 }
135}
136
137async fn moderation_target(bot: &Bot, msg: &Message) -> ResponseResult<Option<UserId>> {
138 match reply_user(msg) {
139 Ok(user) => Ok(Some(user)),
140 Err(reason) => {
141 bot.send_message(reason).chat_id(msg.chat.id).await?;
142 Ok(None)
143 }
144 }
145}
146
147fn reply_user(msg: &Message) -> Result<UserId, &'static str> {
148 let reply = msg.reply_to_message().ok_or("Use this command in reply to another message.")?;
149 reply
150 .from
151 .as_ref()
152 .filter(|_| reply.sender_chat.is_none())
153 .map(|user| user.id)
154 .ok_or("The replied-to message has no identifiable user.")
155}
156
157fn restriction_end(date: DateTime<Utc>, time: u64, unit: UnitOfTime) -> Option<DateTime<Utc>> {
158 let time = i64::try_from(time).ok()?;
159 let duration = match unit {
160 UnitOfTime::Hours => Duration::try_hours(time),
161 UnitOfTime::Minutes => Duration::try_minutes(time),
162 UnitOfTime::Seconds => Duration::try_seconds(time),
163 }?;
164 if duration > Duration::days(366) {
166 return None;
167 }
168 date.checked_add_signed(duration)
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174 use serde_json::json;
175
176 #[test]
177 fn reply_requires_an_identifiable_user() {
178 let msg: Message = serde_json::from_value(json!({
179 "message_id": 1, "date": 0, "text": "/kick",
180 "chat": {"id": -123, "type": "group", "title": "Group"},
181 "reply_to_message": {
182 "message_id": 2, "date": 0, "text": "message",
183 "chat": {"id": -123, "type": "group", "title": "Group"}
184 }
185 }))
186 .unwrap();
187 assert_eq!(reply_user(&msg), Err("The replied-to message has no identifiable user."));
188 }
189
190 #[test]
191 fn rejects_overflowing_restriction_durations() {
192 let start = DateTime::UNIX_EPOCH;
193 assert_eq!(restriction_end(start, 2, UnitOfTime::Minutes).unwrap().timestamp(), 120);
194 assert!(restriction_end(start, 366 * 24, UnitOfTime::Hours).is_some());
195 assert_eq!(restriction_end(start, 366 * 24 + 1, UnitOfTime::Hours), None);
196 assert_eq!(restriction_end(start, u64::MAX, UnitOfTime::Seconds), None);
197 assert_eq!(restriction_end(start, i64::MAX as u64, UnitOfTime::Hours), None);
198 assert_eq!(restriction_end(DateTime::<Utc>::MAX_UTC, 1, UnitOfTime::Seconds), None);
199 }
200
201 #[tokio::test]
202 async fn moderation_checks_sender_in_the_current_chat_and_fails_closed() {
203 let sender = json!({"id": 42, "is_bot": false, "first_name": "Sender"});
204 let mut msg: Message = serde_json::from_value(json!({
205 "message_id": 1, "date": 0, "text": "/kick", "from": sender,
206 "chat": {"id": -123, "type": "group", "title": "Group"},
207 "reply_to_message": {
208 "message_id": 2, "date": 0, "text": "message",
209 "chat": {"id": -123, "type": "group", "title": "Group"},
210 "from": {"id": 43, "is_bot": false, "first_name": "Target"}
211 }
212 }))
213 .unwrap();
214
215 let owner = serde_json::from_value(json!({
216 "user": sender, "status": "creator", "is_anonymous": false
217 }))
218 .unwrap();
219 let member = serde_json::from_value(json!({"user": sender, "status": "member"})).unwrap();
220 assert!(
221 sender_can_restrict(&msg, |chat, user| async move {
222 assert_eq!((chat, user), (ChatId(-123), UserId(42)));
223 Ok::<_, &str>(owner)
224 })
225 .await
226 );
227 assert!(!sender_can_restrict(&msg, |_, _| async { Ok::<_, &str>(member) }).await);
228 for allowed in [false, true] {
229 let admin = serde_json::from_value(json!({
230 "user": sender,
231 "status": "administrator",
232 "is_anonymous": false,
233 "can_be_edited": false,
234 "can_manage_chat": true,
235 "can_change_info": false,
236 "can_delete_messages": false,
237 "can_manage_video_chats": false,
238 "can_invite_users": false,
239 "can_restrict_members": allowed,
240 "can_promote_members": false
241 }))
242 .unwrap();
243 assert_eq!(
244 sender_can_restrict(&msg, |_, _| async { Ok::<_, &str>(admin) }).await,
245 allowed
246 );
247 }
248 assert!(!sender_can_restrict(&msg, |_, _| async { Err("lookup failed") }).await);
249
250 msg.sender_chat = Some(msg.chat.clone());
251 assert!(
252 !sender_can_restrict(&msg, |_, _| -> std::future::Ready<Result<ChatMember, &str>> {
253 panic!("must not check an anonymous sender")
254 })
255 .await
256 );
257 msg.sender_chat = None;
258 msg.from = None;
259 assert!(
260 !sender_can_restrict(&msg, |_, _| -> std::future::Ready<Result<ChatMember, &str>> {
261 panic!("must not check an unknown sender")
262 })
263 .await
264 );
265 }
266}