opencrabs 0.3.57

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! Discord Send Tool
//!
//! Agent-callable tool for full Discord control: send, reply, react, edit, delete,
//! pin/unpin, threads, embeds, message history, channel listing, and moderation.
//! Always prefer this tool over http_request — credentials are handled securely.

use super::error::Result;
use super::r#trait::{Tool, ToolCapability, ToolExecutionContext, ToolResult};
use crate::channels::discord::DiscordState;
use async_trait::async_trait;
use serde_json::Value;
use std::sync::Arc;

/// Tool for comprehensive Discord bot control (16 actions).
pub struct DiscordSendTool {
    discord_state: Arc<DiscordState>,
}

impl DiscordSendTool {
    pub fn new(discord_state: Arc<DiscordState>) -> Self {
        Self { discord_state }
    }
}

/// Extract a required non-empty string param, returning ToolResult::error on failure.
#[allow(clippy::result_large_err)]
fn get_str<'a>(input: &'a Value, key: &str) -> std::result::Result<&'a str, ToolResult> {
    match input.get(key).and_then(|v| v.as_str()) {
        Some(s) if !s.is_empty() => Ok(s),
        _ => Err(ToolResult::error(format!(
            "Missing required parameter '{key}'."
        ))),
    }
}

/// Parse a required numeric-string param as u64.
#[allow(clippy::result_large_err)]
fn get_id(input: &Value, key: &str) -> std::result::Result<u64, ToolResult> {
    match input.get(key).and_then(|v| v.as_str()) {
        Some(s) => s.parse::<u64>().map_err(|_| {
            ToolResult::error(format!("Invalid {key} '{s}': must be a numeric string."))
        }),
        None => Err(ToolResult::error(format!(
            "Missing required parameter '{key}'."
        ))),
    }
}

/// Unwrap channel id or return error ToolResult.
#[allow(clippy::result_large_err)]
fn channel_or_err(id: Option<u64>) -> std::result::Result<u64, ToolResult> {
    id.ok_or_else(|| {
        ToolResult::error(
            "No channel_id provided and no owner channel available. \
             The owner must send a message first, or pass channel_id explicitly."
                .to_string(),
        )
    })
}

/// Unwrap guild id or return error ToolResult.
#[allow(clippy::result_large_err)]
fn guild_or_err(id: Option<u64>) -> std::result::Result<u64, ToolResult> {
    id.ok_or_else(|| {
        ToolResult::error(
            "No guild ID available. The bot must receive at least one guild message first."
                .to_string(),
        )
    })
}

// Macro to early-return Ok(err_result) when a param helper returns Err.
macro_rules! pget {
    ($expr:expr) => {
        match $expr {
            Ok(v) => v,
            Err(e) => return Ok(e),
        }
    };
}

#[async_trait]
impl Tool for DiscordSendTool {
    fn name(&self) -> &str {
        "discord_send"
    }

    fn description(&self) -> &str {
        "Full Discord control: send messages, reply, react, edit, delete, pin/unpin, create \
         threads, send embeds, fetch message history, list channels, manage roles, kick and ban \
         members. Always use discord_send instead of http_request — credentials handled securely."
    }

    fn input_schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": [
                        "send", "reply", "react", "unreact", "edit", "delete",
                        "pin", "unpin", "create_thread", "send_embed", "get_messages",
                        "list_channels", "add_role", "remove_role", "kick", "ban",
                        "send_file"
                    ],
                    "description": "The Discord action to perform"
                },
                "message": {
                    "type": "string",
                    "description": "Message text (send, reply, edit) or embed description (send_embed)"
                },
                "channel_id": {
                    "type": "string",
                    "description": "Discord channel ID (numeric string). Omit to use owner's last channel."
                },
                "message_id": {
                    "type": "string",
                    "description": "Target message ID for reply/react/unreact/edit/delete/pin/unpin/create_thread"
                },
                "emoji": {
                    "type": "string",
                    "description": "Unicode emoji for react/unreact (e.g. \"👍\")"
                },
                "embed_title": {
                    "type": "string",
                    "description": "Title for send_embed"
                },
                "embed_description": {
                    "type": "string",
                    "description": "Body text for send_embed"
                },
                "embed_color": {
                    "type": "integer",
                    "description": "RGB color integer for send_embed (e.g. 0x00FF00 = 65280)"
                },
                "thread_name": {
                    "type": "string",
                    "description": "Thread name for create_thread"
                },
                "user_id": {
                    "type": "string",
                    "description": "Target user ID (numeric string) for add_role/remove_role/kick/ban"
                },
                "role_id": {
                    "type": "string",
                    "description": "Role ID (numeric string) for add_role/remove_role"
                },
                "limit": {
                    "type": "integer",
                    "description": "Number of messages to fetch for get_messages (1-100, default 10)"
                },
                "file_path": {
                    "type": "string",
                    "description": "Local file path to upload (required for send_file)"
                },
                "caption": {
                    "type": "string",
                    "description": "Optional caption text for send_file"
                }
            },
            "required": ["action"]
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::Network]
    }

    async fn execute(&self, input: Value, _context: &ToolExecutionContext) -> Result<ToolResult> {
        let action = match input.get("action").and_then(|v| v.as_str()) {
            Some(a) if !a.is_empty() => a.to_string(),
            _ => {
                return Ok(ToolResult::error(
                    "Missing required 'action' parameter.".to_string(),
                ));
            }
        };

        let http = match self.discord_state.http().await {
            Some(h) => h,
            None => {
                return Ok(ToolResult::error(
                    "Discord is not connected. Run discord_connect first.".to_string(),
                ));
            }
        };

        // Resolve target channel (owner's last channel if not specified)
        let channel_id_opt = if let Some(id_str) = input.get("channel_id").and_then(|v| v.as_str())
        {
            match id_str.parse::<u64>() {
                Ok(id) => Some(id),
                Err(_) => {
                    return Ok(ToolResult::error(format!(
                        "Invalid channel_id '{id_str}': must be a numeric string"
                    )));
                }
            }
        } else {
            self.discord_state.owner_channel_id().await
        };

        let guild_id_opt = self.discord_state.guild_id().await;

        use serenity::model::id::{ChannelId, GuildId, MessageId, RoleId, UserId};

        match action.as_str() {
            // ── send ─────────────────────────────────────────────────────────
            "send" => {
                let text = pget!(get_str(&input, "message")).to_string();
                let channel_id = pget!(channel_or_err(channel_id_opt));
                let channel = ChannelId::new(channel_id);
                let chunks = crate::channels::discord::handler::split_message(&text, 2000);
                for chunk in chunks {
                    if let Err(e) = channel.say(&http, chunk).await {
                        return Ok(ToolResult::error(format!("Failed to send: {e}")));
                    }
                }
                Ok(ToolResult::success(format!(
                    "Message sent to channel {channel_id}."
                )))
            }

            // ── reply ────────────────────────────────────────────────────────
            "reply" => {
                use serenity::builder::CreateMessage;
                use serenity::model::channel::MessageReference;
                let text = pget!(get_str(&input, "message")).to_string();
                let channel_id = pget!(channel_or_err(channel_id_opt));
                let message_id = pget!(get_id(&input, "message_id"));
                let channel = ChannelId::new(channel_id);
                let reference = MessageReference::from((channel, MessageId::new(message_id)));
                let builder = CreateMessage::new()
                    .content(text.as_str())
                    .reference_message(reference);
                match channel.send_message(&http, builder).await {
                    Ok(_) => Ok(ToolResult::success(format!(
                        "Reply sent to message {message_id}."
                    ))),
                    Err(e) => Ok(ToolResult::error(format!("Failed to reply: {e}"))),
                }
            }

            // ── react ────────────────────────────────────────────────────────
            "react" => {
                use serenity::model::channel::ReactionType;
                let channel_id = pget!(channel_or_err(channel_id_opt));
                let message_id = pget!(get_id(&input, "message_id"));
                let emoji = pget!(get_str(&input, "emoji")).to_string();
                let reaction = ReactionType::Unicode(emoji.clone());
                match http
                    .create_reaction(
                        ChannelId::new(channel_id),
                        MessageId::new(message_id),
                        &reaction,
                    )
                    .await
                {
                    Ok(()) => Ok(ToolResult::success(format!(
                        "Reacted with {emoji} on message {message_id}."
                    ))),
                    Err(e) => Ok(ToolResult::error(format!("Failed to react: {e}"))),
                }
            }

            // ── unreact ──────────────────────────────────────────────────────
            "unreact" => {
                use serenity::model::channel::ReactionType;
                let channel_id = pget!(channel_or_err(channel_id_opt));
                let message_id = pget!(get_id(&input, "message_id"));
                let emoji = pget!(get_str(&input, "emoji")).to_string();
                let reaction = ReactionType::Unicode(emoji.clone());
                match http
                    .delete_reaction_me(
                        ChannelId::new(channel_id),
                        MessageId::new(message_id),
                        &reaction,
                    )
                    .await
                {
                    Ok(()) => Ok(ToolResult::success(format!(
                        "Removed reaction {emoji} from message {message_id}."
                    ))),
                    Err(e) => Ok(ToolResult::error(format!("Failed to remove reaction: {e}"))),
                }
            }

            // ── edit ─────────────────────────────────────────────────────────
            "edit" => {
                use serenity::builder::EditMessage;
                let channel_id = pget!(channel_or_err(channel_id_opt));
                let message_id = pget!(get_id(&input, "message_id"));
                let text = pget!(get_str(&input, "message")).to_string();
                let edit = EditMessage::new().content(text.as_str());
                match http
                    .edit_message(
                        ChannelId::new(channel_id),
                        MessageId::new(message_id),
                        &edit,
                        vec![],
                    )
                    .await
                {
                    Ok(_) => Ok(ToolResult::success(format!("Message {message_id} edited."))),
                    Err(e) => Ok(ToolResult::error(format!("Failed to edit message: {e}"))),
                }
            }

            // ── delete ───────────────────────────────────────────────────────
            "delete" => {
                let channel_id = pget!(channel_or_err(channel_id_opt));
                let message_id = pget!(get_id(&input, "message_id"));
                match http
                    .delete_message(ChannelId::new(channel_id), MessageId::new(message_id), None)
                    .await
                {
                    Ok(()) => Ok(ToolResult::success(format!(
                        "Message {message_id} deleted."
                    ))),
                    Err(e) => Ok(ToolResult::error(format!("Failed to delete message: {e}"))),
                }
            }

            // ── pin ──────────────────────────────────────────────────────────
            "pin" => {
                let channel_id = pget!(channel_or_err(channel_id_opt));
                let message_id = pget!(get_id(&input, "message_id"));
                match http
                    .pin_message(ChannelId::new(channel_id), MessageId::new(message_id), None)
                    .await
                {
                    Ok(()) => Ok(ToolResult::success(format!("Message {message_id} pinned."))),
                    Err(e) => Ok(ToolResult::error(format!("Failed to pin message: {e}"))),
                }
            }

            // ── unpin ────────────────────────────────────────────────────────
            "unpin" => {
                let channel_id = pget!(channel_or_err(channel_id_opt));
                let message_id = pget!(get_id(&input, "message_id"));
                match http
                    .unpin_message(ChannelId::new(channel_id), MessageId::new(message_id), None)
                    .await
                {
                    Ok(()) => Ok(ToolResult::success(format!(
                        "Message {message_id} unpinned."
                    ))),
                    Err(e) => Ok(ToolResult::error(format!("Failed to unpin message: {e}"))),
                }
            }

            // ── create_thread ────────────────────────────────────────────────
            "create_thread" => {
                let channel_id = pget!(channel_or_err(channel_id_opt));
                let message_id = pget!(get_id(&input, "message_id"));
                let thread_name = pget!(get_str(&input, "thread_name")).to_string();
                let body = serde_json::json!({ "name": thread_name });
                match http
                    .create_thread_from_message(
                        ChannelId::new(channel_id),
                        MessageId::new(message_id),
                        &body,
                        None,
                    )
                    .await
                {
                    Ok(ch) => Ok(ToolResult::success(format!(
                        "Thread '{}' created (id={}).",
                        ch.name, ch.id
                    ))),
                    Err(e) => Ok(ToolResult::error(format!("Failed to create thread: {e}"))),
                }
            }

            // ── send_embed ───────────────────────────────────────────────────
            "send_embed" => {
                use serenity::builder::{CreateEmbed, CreateMessage};
                let channel_id = pget!(channel_or_err(channel_id_opt));
                let title = input
                    .get("embed_title")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let description = input
                    .get("embed_description")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let color = input
                    .get("embed_color")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0x5865F2) as u32; // Discord blurple default
                let embed = CreateEmbed::new()
                    .title(title.as_str())
                    .description(description.as_str())
                    .color(color);
                let builder = CreateMessage::new().embed(embed);
                match ChannelId::new(channel_id)
                    .send_message(&http, builder)
                    .await
                {
                    Ok(_) => Ok(ToolResult::success(format!(
                        "Embed sent to channel {channel_id}."
                    ))),
                    Err(e) => Ok(ToolResult::error(format!("Failed to send embed: {e}"))),
                }
            }

            // ── get_messages ─────────────────────────────────────────────────
            "get_messages" => {
                let channel_id = pget!(channel_or_err(channel_id_opt));
                let limit = input
                    .get("limit")
                    .and_then(|v| v.as_u64())
                    .map(|n| n.min(100) as u8)
                    .unwrap_or(10);
                match http
                    .get_messages(ChannelId::new(channel_id), None, Some(limit))
                    .await
                {
                    Ok(messages) => {
                        let summary = messages
                            .iter()
                            .map(|m| {
                                format!(
                                    "[{}] {}: {}",
                                    m.id,
                                    m.author.name,
                                    &m.content[..m.content.floor_char_boundary(80)]
                                )
                            })
                            .collect::<Vec<_>>()
                            .join("\n");
                        Ok(ToolResult::success(format!(
                            "Last {} messages in channel {channel_id}:\n{summary}",
                            messages.len()
                        )))
                    }
                    Err(e) => Ok(ToolResult::error(format!("Failed to fetch messages: {e}"))),
                }
            }

            // ── list_channels ────────────────────────────────────────────────
            "list_channels" => {
                let gid = pget!(guild_or_err(guild_id_opt));
                match http.get_channels(GuildId::new(gid)).await {
                    Ok(channels) => {
                        let list = channels
                            .iter()
                            .map(|c| format!("{}: {} ({})", c.id, c.name, c.kind.name()))
                            .collect::<Vec<_>>()
                            .join("\n");
                        Ok(ToolResult::success(format!(
                            "Channels in guild {gid}:\n{list}"
                        )))
                    }
                    Err(e) => Ok(ToolResult::error(format!("Failed to list channels: {e}"))),
                }
            }

            // ── add_role ─────────────────────────────────────────────────────
            "add_role" => {
                let gid = pget!(guild_or_err(guild_id_opt));
                let user_id = pget!(get_id(&input, "user_id"));
                let role_id = pget!(get_id(&input, "role_id"));
                match http
                    .add_member_role(
                        GuildId::new(gid),
                        UserId::new(user_id),
                        RoleId::new(role_id),
                        None,
                    )
                    .await
                {
                    Ok(()) => Ok(ToolResult::success(format!(
                        "Role {role_id} added to user {user_id}."
                    ))),
                    Err(e) => Ok(ToolResult::error(format!("Failed to add role: {e}"))),
                }
            }

            // ── remove_role ──────────────────────────────────────────────────
            "remove_role" => {
                let gid = pget!(guild_or_err(guild_id_opt));
                let user_id = pget!(get_id(&input, "user_id"));
                let role_id = pget!(get_id(&input, "role_id"));
                match http
                    .remove_member_role(
                        GuildId::new(gid),
                        UserId::new(user_id),
                        RoleId::new(role_id),
                        None,
                    )
                    .await
                {
                    Ok(()) => Ok(ToolResult::success(format!(
                        "Role {role_id} removed from user {user_id}."
                    ))),
                    Err(e) => Ok(ToolResult::error(format!("Failed to remove role: {e}"))),
                }
            }

            // ── kick ─────────────────────────────────────────────────────────
            "kick" => {
                let gid = pget!(guild_or_err(guild_id_opt));
                let user_id = pget!(get_id(&input, "user_id"));
                match http
                    .kick_member(GuildId::new(gid), UserId::new(user_id), None)
                    .await
                {
                    Ok(()) => Ok(ToolResult::success(format!("User {user_id} kicked."))),
                    Err(e) => Ok(ToolResult::error(format!("Failed to kick user: {e}"))),
                }
            }

            // ── ban ──────────────────────────────────────────────────────────
            "ban" => {
                let gid = pget!(guild_or_err(guild_id_opt));
                let user_id = pget!(get_id(&input, "user_id"));
                match http
                    .ban_user(GuildId::new(gid), UserId::new(user_id), 0, None)
                    .await
                {
                    Ok(()) => Ok(ToolResult::success(format!("User {user_id} banned."))),
                    Err(e) => Ok(ToolResult::error(format!("Failed to ban user: {e}"))),
                }
            }

            "send_file" => {
                use serenity::builder::{CreateAttachment, CreateMessage};
                use serenity::model::id::ChannelId;
                let channel_id = pget!(channel_or_err(channel_id_opt));
                let file_path = match input.get("file_path").and_then(|v| v.as_str()) {
                    Some(p) => p.to_string(),
                    None => {
                        return Ok(ToolResult::error(
                            "send_file requires 'file_path'.".to_string(),
                        ));
                    }
                };
                let caption = input
                    .get("caption")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let channel = ChannelId::new(channel_id);
                match tokio::fs::read(&file_path).await {
                    Ok(bytes) => {
                        let fname = std::path::Path::new(&file_path)
                            .file_name()
                            .and_then(|n| n.to_str())
                            .unwrap_or("file.png")
                            .to_string();
                        let attachment = CreateAttachment::bytes(bytes.as_slice(), fname);
                        let mut msg = CreateMessage::new().add_file(attachment);
                        if !caption.is_empty() {
                            msg = msg.content(caption);
                        }
                        match channel.send_message(&http, msg).await {
                            Ok(_) => Ok(ToolResult::success("File sent.".to_string())),
                            Err(e) => Ok(ToolResult::error(format!("Failed to send file: {e}"))),
                        }
                    }
                    Err(e) => Ok(ToolResult::error(format!(
                        "Failed to read file '{}': {e}",
                        file_path
                    ))),
                }
            }

            unknown => Ok(ToolResult::error(format!(
                "Unknown action '{unknown}'. Valid: send, reply, react, unreact, edit, delete, \
                 pin, unpin, create_thread, send_embed, get_messages, list_channels, \
                 add_role, remove_role, kick, ban, send_file"
            ))),
        }
    }
}