Skip to main content

clickup_cli/commands/
chat.rs

1use crate::client::ClickUpClient;
2use crate::commands::auth::resolve_token;
3use crate::commands::workspace::resolve_workspace;
4use crate::error::CliError;
5use crate::output::OutputConfig;
6use crate::Cli;
7use clap::Subcommand;
8
9#[derive(Subcommand)]
10pub enum ChatCommands {
11    /// List channels in the workspace
12    #[command(name = "channel-list")]
13    ChannelList {
14        /// Include closed channels
15        #[arg(long)]
16        include_closed: bool,
17    },
18    /// Create a channel
19    #[command(name = "channel-create")]
20    ChannelCreate {
21        /// Channel name
22        #[arg(long)]
23        name: String,
24        /// Visibility: PUBLIC or PRIVATE
25        #[arg(long)]
26        visibility: Option<String>,
27    },
28    /// Get a channel by ID
29    #[command(name = "channel-get")]
30    ChannelGet {
31        /// Channel ID
32        id: String,
33    },
34    /// Update a channel
35    #[command(name = "channel-update")]
36    ChannelUpdate {
37        /// Channel ID
38        id: String,
39        /// New name
40        #[arg(long)]
41        name: Option<String>,
42        /// New topic
43        #[arg(long)]
44        topic: Option<String>,
45    },
46    /// Delete a channel
47    #[command(name = "channel-delete")]
48    ChannelDelete {
49        /// Channel ID
50        id: String,
51    },
52    /// List followers of a channel
53    #[command(name = "channel-followers")]
54    ChannelFollowers {
55        /// Channel ID
56        id: String,
57    },
58    /// List members of a channel
59    #[command(name = "channel-members")]
60    ChannelMembers {
61        /// Channel ID
62        id: String,
63    },
64    /// Create or get a direct message channel
65    Dm {
66        /// User ID(s) to send a DM to
67        user_ids: Vec<String>,
68    },
69    /// List messages in a channel
70    #[command(name = "message-list")]
71    MessageList {
72        /// Channel ID
73        #[arg(long)]
74        channel: String,
75    },
76    /// Send a message to a channel
77    #[command(name = "message-send")]
78    MessageSend {
79        /// Channel ID
80        #[arg(long)]
81        channel: String,
82        /// Message text
83        #[arg(long)]
84        text: String,
85        /// Message type: message or post
86        #[arg(long, default_value = "message")]
87        r#type: String,
88    },
89    /// Update a message
90    #[command(name = "message-update")]
91    MessageUpdate {
92        /// Message ID
93        id: String,
94        /// New message text
95        #[arg(long)]
96        text: String,
97    },
98    /// Delete a message
99    #[command(name = "message-delete")]
100    MessageDelete {
101        /// Message ID
102        id: String,
103    },
104    /// List reactions on a message
105    #[command(name = "reaction-list")]
106    ReactionList {
107        /// Message ID
108        msg_id: String,
109    },
110    /// Add a reaction to a message
111    #[command(name = "reaction-add")]
112    ReactionAdd {
113        /// Message ID
114        msg_id: String,
115        /// Emoji name
116        #[arg(long)]
117        emoji: String,
118    },
119    /// Remove a reaction from a message
120    #[command(name = "reaction-remove")]
121    ReactionRemove {
122        /// Message ID
123        msg_id: String,
124        /// Emoji name
125        emoji: String,
126    },
127    /// List replies to a message
128    #[command(name = "reply-list")]
129    ReplyList {
130        /// Message ID
131        msg_id: String,
132    },
133    /// Send a reply to a message
134    #[command(name = "reply-send")]
135    ReplySend {
136        /// Message ID
137        msg_id: String,
138        /// Reply text
139        #[arg(long)]
140        text: String,
141    },
142    /// Get users tagged in a message
143    #[command(name = "tagged-users")]
144    TaggedUsers {
145        /// Message ID
146        msg_id: String,
147    },
148}
149
150const CHANNEL_FIELDS: &[&str] = &["id", "name", "visibility", "type"];
151const MESSAGE_FIELDS: &[&str] = &["id", "content", "type", "date"];
152
153pub async fn execute(command: ChatCommands, cli: &Cli) -> Result<(), CliError> {
154    let token = resolve_token(cli)?;
155    let client = ClickUpClient::new(&token, cli.timeout)?;
156    let ws_id = resolve_workspace(cli)?;
157    let output = OutputConfig::from_cli(&cli.output, &cli.fields, cli.no_header, cli.quiet);
158    let base = format!("/v3/workspaces/{}/chat", ws_id);
159
160    match command {
161        ChatCommands::ChannelList { include_closed } => {
162            let query = if include_closed {
163                "?include_closed=true"
164            } else {
165                ""
166            };
167            let resp = client.get(&format!("{}/channels{}", base, query)).await?;
168            let mut channels = resp
169                .get("channels")
170                .and_then(|v| v.as_array())
171                .cloned()
172                .unwrap_or_default();
173            if let Some(limit) = cli.limit {
174                channels.truncate(limit);
175            }
176            output.print_items(&channels, CHANNEL_FIELDS, "id");
177            Ok(())
178        }
179        ChatCommands::ChannelCreate { name, visibility } => {
180            let mut body = serde_json::json!({ "name": name });
181            if let Some(v) = visibility {
182                body["visibility"] = serde_json::Value::String(v);
183            }
184            let resp = client.post(&format!("{}/channels", base), &body).await?;
185            output.print_single(&resp, CHANNEL_FIELDS, "id");
186            Ok(())
187        }
188        ChatCommands::ChannelGet { id } => {
189            let resp = client.get(&format!("{}/channels/{}", base, id)).await?;
190            output.print_single(&resp, CHANNEL_FIELDS, "id");
191            Ok(())
192        }
193        ChatCommands::ChannelUpdate { id, name, topic } => {
194            let mut body = serde_json::Map::new();
195            if let Some(n) = name {
196                body.insert("name".into(), serde_json::Value::String(n));
197            }
198            if let Some(t) = topic {
199                body.insert("topic".into(), serde_json::Value::String(t));
200            }
201            let resp = client
202                .patch(
203                    &format!("{}/channels/{}", base, id),
204                    &serde_json::Value::Object(body),
205                )
206                .await?;
207            output.print_single(&resp, CHANNEL_FIELDS, "id");
208            Ok(())
209        }
210        ChatCommands::ChannelDelete { id } => {
211            client.delete(&format!("{}/channels/{}", base, id)).await?;
212            output.print_message(&format!("Channel {} deleted", id));
213            Ok(())
214        }
215        ChatCommands::ChannelFollowers { id } => {
216            let resp = client
217                .get(&format!("{}/channels/{}/followers", base, id))
218                .await?;
219            println!("{}", serde_json::to_string_pretty(&resp).unwrap());
220            Ok(())
221        }
222        ChatCommands::ChannelMembers { id } => {
223            let resp = client
224                .get(&format!("{}/channels/{}/members", base, id))
225                .await?;
226            println!("{}", serde_json::to_string_pretty(&resp).unwrap());
227            Ok(())
228        }
229        ChatCommands::Dm { user_ids } => {
230            let body = serde_json::json!({ "user_ids": user_ids });
231            let resp = client
232                .post(&format!("{}/channels/direct_message", base), &body)
233                .await?;
234            output.print_single(&resp, CHANNEL_FIELDS, "id");
235            Ok(())
236        }
237        ChatCommands::MessageList { channel } => {
238            let resp = client
239                .get(&format!("{}/channels/{}/messages", base, channel))
240                .await?;
241            let mut messages = resp
242                .get("messages")
243                .and_then(|v| v.as_array())
244                .cloned()
245                .unwrap_or_else(|| {
246                    // Response may be an array directly
247                    resp.as_array().cloned().unwrap_or_default()
248                });
249            if let Some(limit) = cli.limit {
250                messages.truncate(limit);
251            }
252            output.print_items(&messages, MESSAGE_FIELDS, "id");
253            Ok(())
254        }
255        ChatCommands::MessageSend {
256            channel,
257            text,
258            r#type,
259        } => {
260            let body = serde_json::json!({ "content": text, "type": r#type });
261            let resp = client
262                .post(&format!("{}/channels/{}/messages", base, channel), &body)
263                .await?;
264            output.print_single(&resp, MESSAGE_FIELDS, "id");
265            Ok(())
266        }
267        ChatCommands::MessageUpdate { id, text } => {
268            let body = serde_json::json!({ "content": text });
269            let resp = client
270                .patch(&format!("{}/messages/{}", base, id), &body)
271                .await?;
272            output.print_single(&resp, MESSAGE_FIELDS, "id");
273            Ok(())
274        }
275        ChatCommands::MessageDelete { id } => {
276            client.delete(&format!("{}/messages/{}", base, id)).await?;
277            output.print_message(&format!("Message {} deleted", id));
278            Ok(())
279        }
280        ChatCommands::ReactionList { msg_id } => {
281            let resp = client
282                .get(&format!("{}/messages/{}/reactions", base, msg_id))
283                .await?;
284            println!("{}", serde_json::to_string_pretty(&resp).unwrap());
285            Ok(())
286        }
287        ChatCommands::ReactionAdd { msg_id, emoji } => {
288            let body = serde_json::json!({ "emoji": emoji });
289            let resp = client
290                .post(&format!("{}/messages/{}/reactions", base, msg_id), &body)
291                .await?;
292            println!("{}", serde_json::to_string_pretty(&resp).unwrap());
293            Ok(())
294        }
295        ChatCommands::ReactionRemove { msg_id, emoji } => {
296            client
297                .delete(&format!("{}/messages/{}/reactions/{}", base, msg_id, emoji))
298                .await?;
299            output.print_message(&format!(
300                "Reaction '{}' removed from message {}",
301                emoji, msg_id
302            ));
303            Ok(())
304        }
305        ChatCommands::ReplyList { msg_id } => {
306            let resp = client
307                .get(&format!("{}/messages/{}/replies", base, msg_id))
308                .await?;
309            let mut replies = resp
310                .get("replies")
311                .and_then(|v| v.as_array())
312                .cloned()
313                .unwrap_or_else(|| resp.as_array().cloned().unwrap_or_default());
314            if let Some(limit) = cli.limit {
315                replies.truncate(limit);
316            }
317            output.print_items(&replies, MESSAGE_FIELDS, "id");
318            Ok(())
319        }
320        ChatCommands::ReplySend { msg_id, text } => {
321            let body = serde_json::json!({ "content": text });
322            let resp = client
323                .post(&format!("{}/messages/{}/replies", base, msg_id), &body)
324                .await?;
325            output.print_single(&resp, MESSAGE_FIELDS, "id");
326            Ok(())
327        }
328        ChatCommands::TaggedUsers { msg_id } => {
329            let resp = client
330                .get(&format!("{}/messages/{}/tagged_users", base, msg_id))
331                .await?;
332            println!("{}", serde_json::to_string_pretty(&resp).unwrap());
333            Ok(())
334        }
335    }
336}