zaun_client/bots/
config.rs1use 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
12fn 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 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 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}