src/commands/say.rs

1aebd1afe96d6b9a2f26ca598c88d5aae0ba5008
weechat-matrix-rs/src/commands/say.rs history · blame · raw

68 lines · 1545 bytes

7 symbols in this file
 1use std::borrow::Cow;
 2
 3use weechat::{
 4    buffer::Buffer,
 5    hooks::{CommandRun, CommandRunCallback},
 6    ReturnCode, Weechat,
 7};
 8
 9use crate::Servers;
10
11pub struct SayCommand {
12    servers: Servers,
13}
14
15fn say_body(command: &str) -> Option<&str> {
16    command.strip_prefix("/say ").map(str::trim_start)
17}
18
19impl SayCommand {
20    pub fn create(servers: &Servers) -> Result<CommandRun, ()> {
21        CommandRun::new(
22            "/say *",
23            SayCommand {
24                servers: servers.clone(),
25            },
26        )
27    }
28}
29
30impl CommandRunCallback for SayCommand {
31    fn callback(
32        &mut self,
33        _: &Weechat,
34        buffer: &Buffer,
35        command: Cow<str>,
36    ) -> ReturnCode {
37        let Some(room) = self.servers.find_room(buffer) else {
38            return ReturnCode::Ok;
39        };
40
41        let Some(body) = say_body(&command) else {
42            return ReturnCode::Ok;
43        };
44
45        let content = room.text_message_content(buffer, body.to_owned());
46        Weechat::spawn(async move { room.send_message(content).await })
47            .detach();
48
49        ReturnCode::OkEat
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::say_body;
56
57    #[test]
58    fn say_body_preserves_message_text() {
59        assert_eq!(say_body("/say hello Matrix"), Some("hello Matrix"));
60        assert_eq!(say_body("/say   leading spaces"), Some("leading spaces"));
61    }
62
63    #[test]
64    fn say_body_excludes_other_commands() {
65        assert_eq!(say_body("/msg hello"), None);
66        assert_eq!(say_body("hello"), None);
67    }
68}