Skip to main content

zaun_client/bots/
config.rs

1//! A bot's settings (`bot.configure`, zaun:bot 0.2.0 `[config]`): the card declares them
2//! (`BotCard::config`), the owner sets their values, and secret values are never shown again.
3
4use std::collections::BTreeMap;
5
6use zaun_community_protocol::command::bot::{Configure, Configured};
7use zaun_community_protocol::ids::BotId;
8
9use crate::error::Result;
10use crate::objects::Community;
11
12/// The `bot.configure` body: `Some` sets a key's value, `None` clears it back to its default.
13fn body<K, V>(bot: BotId, values: impl IntoIterator<Item = (K, Option<V>)>) -> Configure
14where
15    K: Into<String>,
16    V: Into<String>,
17{
18    let mut out = Configure {
19        bot_id: bot,
20        set: BTreeMap::new(),
21        unset: Vec::new(),
22    };
23    for (key, value) in values {
24        let key = key.into();
25        match value {
26            Some(v) => {
27                out.unset.retain(|k| *k != key);
28                out.set.insert(key, v.into());
29            }
30            None => {
31                out.set.remove(&key);
32                if !out.unset.contains(&key) {
33                    out.unset.push(key);
34                }
35            }
36        }
37    }
38    out
39}
40
41impl Community {
42    /// Owner only: sets (`Some`) or clears (`None`, back to the default) the values of the
43    /// settings `bot`'s manifest declares (its card's `config`), and answers every value the
44    /// owner has set, a secret one as `"••••"` ([`MASKED`](crate::protocol::command::bot::MASKED)).
45    /// The bot gets them at once. Keys are `[a-z][a-z0-9_]{0,63}`, values ≤ 4 KiB, ≤ 32 of
46    /// each.
47    ///
48    /// # Errors
49    /// A malformed key or value ([`Error::Protocol`](crate::Error::Protocol)), or the host
50    /// refused: `FORBIDDEN` (not the owner), `NOT_FOUND` (no such bot), `BAD_REQUEST` with
51    /// field `config.<key>` (a key the manifest does not declare). Needs zaun-host 0.4.0.
52    pub fn configure_bot<K, V>(
53        &self,
54        bot: BotId,
55        values: impl IntoIterator<Item = (K, Option<V>)>,
56    ) -> Result<BTreeMap<String, String>>
57    where
58        K: Into<String>,
59        V: Into<String>,
60    {
61        let done: Configured = self.client.command(self.id, None, body(bot, values))?;
62        Ok(done.values)
63    }
64
65    /// Owner only: the values set for `bot`'s settings, a secret one as `"••••"`; a key
66    /// not here uses its card's `default`.
67    ///
68    /// # Errors
69    /// As [`configure_bot`](Self::configure_bot).
70    pub fn bot_config(&self, bot: BotId) -> Result<BTreeMap<String, String>> {
71        self.configure_bot(bot, std::iter::empty::<(String, Option<String>)>())
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use serde_json::json;
78    use zaun_community_protocol::command::Validate;
79
80    use super::*;
81
82    const BOT: BotId = BotId::from_bytes([4; 16]);
83
84    #[test]
85    fn a_value_sets_a_key_none_clears_it_and_the_last_word_wins() {
86        let b = body(
87            BOT,
88            [
89                ("token", Some("s3cret")),
90                ("greeting", None),
91                ("media", Some("a")),
92                ("media", None),
93                ("greeting", Some("hi")),
94            ],
95        );
96        b.validate().unwrap();
97        assert_eq!(
98            serde_json::to_value(&b).unwrap(),
99            json!({ "bot_id": BOT, "set": { "greeting": "hi", "token": "s3cret" },
100                    "unset": ["media"] })
101        );
102    }
103
104    #[test]
105    fn reading_the_settings_sends_neither_set_nor_unset() {
106        let read = body(BOT, std::iter::empty::<(String, Option<String>)>());
107        assert_eq!(
108            serde_json::to_value(&read).unwrap(),
109            json!({ "bot_id": BOT })
110        );
111        let bad = body(BOT, [("Not-a-key", Some("x"))]);
112        assert!(bad.validate().is_err());
113    }
114}