Skip to main content

zaun_client/bots/
community.rs

1//! Bots and commands on a community: the cached lists, the owner's management, and a bot's
2//! own command list.
3
4use zaun_community_protocol::bits::Permissions;
5use zaun_community_protocol::command::app;
6use zaun_community_protocol::command::bot::{
7    self, Bots, Disable, Enable, GrantChoice, Install, Register, Remove, Target,
8};
9use zaun_community_protocol::command::object::{ApplicationCommand, BotCard, Capabilities};
10use zaun_community_protocol::ids::{AttachmentId, BotId};
11
12use crate::error::Result;
13use crate::objects::{Community, Member, Role};
14
15impl Community {
16    /// Every bot command in the community, as last heard (each with its `bot_id`).
17    #[must_use]
18    pub fn commands(&self) -> Vec<ApplicationCommand> {
19        self.read(|c| c.commands.values().cloned().collect())
20            .unwrap_or_default()
21    }
22
23    /// The installed bots' public cards, as last heard.
24    #[must_use]
25    pub fn bots(&self) -> Vec<BotCard> {
26        self.read(|c| c.bots.values().cloned().collect())
27            .unwrap_or_default()
28    }
29
30    /// Asks the host for every bot's card (owners also get each bot's full request).
31    ///
32    /// # Errors
33    /// The host refused or did not answer.
34    pub fn fetch_bots(&self) -> Result<Vec<BotCard>> {
35        let page: Bots = self.client.command(self.id, None, bot::List {})?;
36        Ok(page.bots)
37    }
38
39    /// Asks the host for one bot's card.
40    ///
41    /// # Errors
42    /// The host refused (`NOT_FOUND`) or did not answer.
43    pub fn bot(&self, bot: BotId) -> Result<BotCard> {
44        self.client.command(self.id, None, Target { bot_id: bot })
45    }
46
47    /// Owner only: installs the `.zbot` package uploaded as `package` (an attachment not on
48    /// a message). `grants` absent: everything the manifest asks for, within the host's ceiling.
49    ///
50    /// # Errors
51    /// The host refused (not the owner, a bad package, over the ceiling) or did not answer.
52    pub fn install_bot(
53        &self,
54        package: AttachmentId,
55        grants: Option<GrantChoice>,
56        role_position: Option<u32>,
57    ) -> Result<BotCard> {
58        let body = Install {
59            package,
60            grants,
61            role_position,
62            source: None,
63        };
64        self.client.command(self.id, None, body)
65    }
66
67    /// Owner only: updates a bot to a newer package of the same publisher.
68    ///
69    /// # Errors
70    /// As [`install_bot`](Self::install_bot).
71    pub fn update_bot(&self, bot: BotId, package: AttachmentId) -> Result<BotCard> {
72        self.client.command(
73            self.id,
74            None,
75            bot::Update {
76                bot_id: bot,
77                package,
78                source: None,
79            },
80        )
81    }
82
83    /// Owner only: replaces a bot's grants (approves a waiting update when it covers it).
84    ///
85    /// # Errors
86    /// The host refused or did not answer.
87    pub fn grant_bot(
88        &self,
89        bot: BotId,
90        permissions: Option<Permissions>,
91        capabilities: Option<Capabilities>,
92    ) -> Result<BotCard> {
93        let body = bot::Grant {
94            bot_id: bot,
95            permissions,
96            capabilities,
97        };
98        self.client.command(self.id, None, body)
99    }
100
101    /// Owner only: starts a disabled bot.
102    ///
103    /// # Errors
104    /// The host refused or did not answer.
105    pub fn enable_bot(&self, bot: BotId) -> Result<BotCard> {
106        self.client.command(self.id, None, Enable { bot_id: bot })
107    }
108
109    /// Owner only: stops a bot and hides its commands.
110    ///
111    /// # Errors
112    /// The host refused or did not answer.
113    pub fn disable_bot(&self, bot: BotId) -> Result<BotCard> {
114        self.client.command(self.id, None, Disable { bot_id: bot })
115    }
116
117    /// Owner only: removes a bot, its role and commands (and its data unless `keep_data`).
118    ///
119    /// # Errors
120    /// The host refused or did not answer.
121    pub fn remove_bot(&self, bot: BotId, keep_data: bool) -> Result<()> {
122        let body = Remove {
123            bot_id: bot,
124            delete_data: Some(!keep_data),
125        };
126        self.client.command(self.id, None, body).map(|_| ())
127    }
128
129    /// Owner only: marks `member` (a client connected over SimpleX) as an external bot.
130    ///
131    /// # Errors
132    /// The host refused or did not answer.
133    pub fn register_bot(&self, member: &Member, name: Option<&str>) -> Result<BotCard> {
134        let body = Register {
135            member_id: member.id,
136            name: name.map(str::to_owned),
137        };
138        self.client.command(self.id, None, body)
139    }
140
141    /// As a bot: replaces this bot's whole command list; answers it with the host's ids.
142    ///
143    /// # Errors
144    /// The host refused (this member is not a bot, a command breaks the rules).
145    pub fn set_commands(
146        &self,
147        commands: Vec<ApplicationCommand>,
148    ) -> Result<Vec<ApplicationCommand>> {
149        let set: app::Commands = self.client.command(self.id, None, app::Set { commands })?;
150        Ok(set.commands)
151    }
152}
153
154impl Member {
155    /// The bot this member is, if it is one.
156    #[must_use]
157    pub fn bot_id(&self) -> Option<BotId> {
158        self.community
159            .read(|c| c.members.get(&self.id).and_then(|m| m.bot_id))
160            .flatten()
161    }
162
163    /// Whether this member is a bot.
164    #[must_use]
165    pub fn is_bot(&self) -> bool {
166        self.bot_id().is_some()
167    }
168}
169
170impl Role {
171    /// The bot whose managed role this is: only that bot holds it, and only the owner's
172    /// grants change it.
173    #[must_use]
174    pub fn managed_by(&self) -> Option<BotId> {
175        self.community
176            .read(|c| c.roles.get(&self.id).and_then(|r| r.managed_by))
177            .flatten()
178    }
179}
180
181impl Member {
182    /// Whether this member may use `command` in `channel` (a local view; the host decides).
183    #[must_use]
184    pub fn can_use(&self, command: &ApplicationCommand, channel: &crate::Channel) -> bool {
185        let now = self.community.client.now_ms();
186        self.community
187            .read(|c| c.can_use(&self.id, &channel.id, command, now))
188            .unwrap_or(false)
189    }
190}