teloxide-fork 0.20.0

An elegant Telegram bots framework for Rust
Documentation
use std::{future::Future, str::FromStr};

use chrono::{DateTime, Duration, Utc};
use teloxide::{
    prelude::*,
    types::{ChatMember, ChatPermissions, UserId},
    utils::command::BotCommands,
};

// Derive BotCommands to parse text with a command into this enumeration.
//
// 1. `rename_rule = "lowercase"` turns all the commands into lowercase letters.
// 2. `description = "..."` specifies a text before all the commands.
//
// That is, you can just call Command::descriptions() to get a description of
// your commands in this format:
// %GENERAL-DESCRIPTION%
// %PREFIX%%COMMAND% - %DESCRIPTION%

/// Use commands in format /%command% %num% %unit%
#[derive(BotCommands, Clone)]
#[command(rename_rule = "lowercase", parse_with = "split")]
enum Command {
    /// Kick user from chat.
    Kick,
    /// Ban user in chat.
    Ban {
        time: u64,
        unit: UnitOfTime,
    },
    /// Mute user in chat.
    Mute {
        time: u64,
        unit: UnitOfTime,
    },
    Help,
}

#[derive(Clone)]
enum UnitOfTime {
    Seconds,
    Minutes,
    Hours,
}

impl FromStr for UnitOfTime {
    type Err = &'static str;
    fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
        match s {
            "h" | "hours" => Ok(UnitOfTime::Hours),
            "m" | "minutes" => Ok(UnitOfTime::Minutes),
            "s" | "seconds" => Ok(UnitOfTime::Seconds),
            _ => Err("Allowed units: h, m, s"),
        }
    }
}

#[tokio::main]
async fn main() {
    pretty_env_logger::init();
    log::info!("Starting admin bot...");

    let bot = teloxide::Bot::from_env();

    Command::repl(bot, action).await;
}

async fn action(bot: Bot, msg: Message, cmd: Command) -> ResponseResult<()> {
    if !matches!(&cmd, Command::Help)
        && !sender_can_restrict(&msg, |chat, user| {
            let bot = &bot;
            async move { bot.get_chat_member(chat, user).await }
        })
        .await
    {
        bot.send_message(
            "Only chat admins with permission to restrict members can use this command.",
        )
        .chat_id(msg.chat.id)
        .await?;
        return Ok(());
    }

    let is_ban = matches!(&cmd, Command::Ban { .. });
    match cmd {
        Command::Help => {
            bot.send_message(Command::descriptions().to_string()).chat_id(msg.chat.id).await?;
        }
        Command::Kick => {
            if let Some(target) = moderation_target(&bot, &msg).await? {
                // unban_chat_member also removes a current member from a group.
                bot.unban_chat_member(msg.chat.id, target).await?;
            }
        }
        Command::Ban { time, unit } | Command::Mute { time, unit } => {
            let Some(target) = moderation_target(&bot, &msg).await? else {
                return Ok(());
            };
            let Some(until) = restriction_end(msg.date, time, unit) else {
                bot.send_message("Restriction duration is too large.").chat_id(msg.chat.id).await?;
                return Ok(());
            };
            if is_ban {
                bot.kick_chat_member(msg.chat.id, target).until_date(until).await?;
            } else {
                bot.restrict_chat_member(msg.chat.id, target, ChatPermissions::empty())
                    .until_date(until)
                    .await?;
            }
        }
    };

    Ok(())
}

async fn sender_can_restrict<E, F>(
    msg: &Message,
    get_member: impl FnOnce(ChatId, UserId) -> F,
) -> bool
where
    F: Future<Output = Result<ChatMember, E>>,
    E: std::fmt::Display,
{
    // Messages sent on behalf of chats can include a synthetic `from` user.
    let Some(sender) = msg.from.as_ref().filter(|_| msg.sender_chat.is_none()) else {
        return false;
    };
    match get_member(msg.chat.id, sender.id).await {
        Ok(member) => member.kind.can_restrict_members(),
        Err(err) => {
            log::warn!("Could not verify moderation permissions in {}: {err}", msg.chat.id);
            false
        }
    }
}

async fn moderation_target(bot: &Bot, msg: &Message) -> ResponseResult<Option<UserId>> {
    match reply_user(msg) {
        Ok(user) => Ok(Some(user)),
        Err(reason) => {
            bot.send_message(reason).chat_id(msg.chat.id).await?;
            Ok(None)
        }
    }
}

fn reply_user(msg: &Message) -> Result<UserId, &'static str> {
    let reply = msg.reply_to_message().ok_or("Use this command in reply to another message.")?;
    reply
        .from
        .as_ref()
        .filter(|_| reply.sender_chat.is_none())
        .map(|user| user.id)
        .ok_or("The replied-to message has no identifiable user.")
}

fn restriction_end(date: DateTime<Utc>, time: u64, unit: UnitOfTime) -> Option<DateTime<Utc>> {
    let time = i64::try_from(time).ok()?;
    let duration = match unit {
        UnitOfTime::Hours => Duration::try_hours(time),
        UnitOfTime::Minutes => Duration::try_minutes(time),
        UnitOfTime::Seconds => Duration::try_seconds(time),
    }?;
    // Telegram treats a restriction lasting more than 366 days as permanent.
    if duration > Duration::days(366) {
        return None;
    }
    date.checked_add_signed(duration)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn reply_requires_an_identifiable_user() {
        let msg: Message = serde_json::from_value(json!({
            "message_id": 1, "date": 0, "text": "/kick",
            "chat": {"id": -123, "type": "group", "title": "Group"},
            "reply_to_message": {
                "message_id": 2, "date": 0, "text": "message",
                "chat": {"id": -123, "type": "group", "title": "Group"}
            }
        }))
        .unwrap();
        assert_eq!(reply_user(&msg), Err("The replied-to message has no identifiable user."));
    }

    #[test]
    fn rejects_overflowing_restriction_durations() {
        let start = DateTime::UNIX_EPOCH;
        assert_eq!(restriction_end(start, 2, UnitOfTime::Minutes).unwrap().timestamp(), 120);
        assert!(restriction_end(start, 366 * 24, UnitOfTime::Hours).is_some());
        assert_eq!(restriction_end(start, 366 * 24 + 1, UnitOfTime::Hours), None);
        assert_eq!(restriction_end(start, u64::MAX, UnitOfTime::Seconds), None);
        assert_eq!(restriction_end(start, i64::MAX as u64, UnitOfTime::Hours), None);
        assert_eq!(restriction_end(DateTime::<Utc>::MAX_UTC, 1, UnitOfTime::Seconds), None);
    }

    #[tokio::test]
    async fn moderation_checks_sender_in_the_current_chat_and_fails_closed() {
        let sender = json!({"id": 42, "is_bot": false, "first_name": "Sender"});
        let mut msg: Message = serde_json::from_value(json!({
            "message_id": 1, "date": 0, "text": "/kick", "from": sender,
            "chat": {"id": -123, "type": "group", "title": "Group"},
            "reply_to_message": {
                "message_id": 2, "date": 0, "text": "message",
                "chat": {"id": -123, "type": "group", "title": "Group"},
                "from": {"id": 43, "is_bot": false, "first_name": "Target"}
            }
        }))
        .unwrap();

        let owner = serde_json::from_value(json!({
            "user": sender, "status": "creator", "is_anonymous": false
        }))
        .unwrap();
        let member = serde_json::from_value(json!({"user": sender, "status": "member"})).unwrap();
        assert!(
            sender_can_restrict(&msg, |chat, user| async move {
                assert_eq!((chat, user), (ChatId(-123), UserId(42)));
                Ok::<_, &str>(owner)
            })
            .await
        );
        assert!(!sender_can_restrict(&msg, |_, _| async { Ok::<_, &str>(member) }).await);
        for allowed in [false, true] {
            let admin = serde_json::from_value(json!({
                "user": sender,
                "status": "administrator",
                "is_anonymous": false,
                "can_be_edited": false,
                "can_manage_chat": true,
                "can_change_info": false,
                "can_delete_messages": false,
                "can_manage_video_chats": false,
                "can_invite_users": false,
                "can_restrict_members": allowed,
                "can_promote_members": false
            }))
            .unwrap();
            assert_eq!(
                sender_can_restrict(&msg, |_, _| async { Ok::<_, &str>(admin) }).await,
                allowed
            );
        }
        assert!(!sender_can_restrict(&msg, |_, _| async { Err("lookup failed") }).await);

        msg.sender_chat = Some(msg.chat.clone());
        assert!(
            !sender_can_restrict(&msg, |_, _| -> std::future::Ready<Result<ChatMember, &str>> {
                panic!("must not check an anonymous sender")
            })
            .await
        );
        msg.sender_chat = None;
        msg.from = None;
        assert!(
            !sender_can_restrict(&msg, |_, _| -> std::future::Ready<Result<ChatMember, &str>> {
                panic!("must not check an unknown sender")
            })
            .await
        );
    }
}