kovi-plugin-cmd 0.3.0

Kovi 的管理插件,通过消息命令配置 Kovi
Documentation
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
use cmd::{AccControlCmd, CmdSetAccessControlList, HelpItem, KoviArgs, KoviCmd, PluginCmd};
use kovi::{
    PluginBuilder as P, RuntimeBot,
    bot::{AccessControlMode, runtimebot::kovi_api::SetAccessControlList},
    error::BotError,
    event::AdminMsgEvent,
    log, serde_json,
};
use std::{
    sync::{Arc, Mutex},
    time::{SystemTime, UNIX_EPOCH},
};
use sysinfo::{Pid, ProcessesToUpdate, System};

mod cmd;

#[derive(Debug, Clone, Copy, serde::Deserialize, serde::Serialize, Default)]
struct Info {
    start_time: u64,
    accept_msg: u64,
    send_msg: u64,
}
impl Info {
    fn accept(&mut self) {
        self.accept_msg += 1;
    }
    fn send(&mut self) {
        self.send_msg += 1;
    }
}

#[kovi::plugin]
async fn main() {
    let start = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    let info = Arc::new(Mutex::new(Info {
        start_time: start,
        accept_msg: 0,
        send_msg: 0,
    }));

    let info_clone = info.clone();
    P::on_msg(move |_| {
        let info_clone = info_clone.clone();
        async move {
            let mut info = info_clone.lock().unwrap();
            info.accept();
        }
    });

    let info_clone = info.clone();
    P::on(move |_: Arc<kovi::event::MsgSendFromKoviEvent>| {
        let info_clone = info_clone.clone();
        async move {
            let mut info = info_clone.lock().unwrap();
            info.send();
        }
    });

    let bot = P::get_runtime_bot();
    // let data_path = bot.get_data_path();
    // let cmd = CMDInfo {
    //     cmd_start_with: ".kovi".to_string(),
    // };
    // let cmd: CMDInfo = load_json_data(cmd, data_path.join("cmd.json")).unwrap();
    // let cmd = Arc::new(cmd);
    P::on_admin_msg(move |e| {
        let bot = bot.clone();
        // let cmd = cmd.clone();
        let info = info.clone();
        async move {
            let text = if let Some(v) = e.borrow_text() {
                v
            } else {
                return;
            };
            // if !text.starts_with(cmd.cmd_start_with.as_str()) {
            //     return;
            // }

            if !text.starts_with(".kovi") {
                return;
            }

            let vec_text: Vec<&str> = text.split_whitespace().collect();

            let cmd = KoviArgs::parse(vec_text.iter().map(|v| v.to_string()).collect());

            match cmd.command {
                KoviCmd::Help(item) => {
                    help(&e, item);
                }
                KoviCmd::Plugin(plugin_cmd) => match plugin_cmd {
                    PluginCmd::Status => plugin_status(&e, &bot),
                    PluginCmd::Start { name } => {
                        plugin_start(&e, &bot, &name);
                    }
                    PluginCmd::Stop { name } => {
                        plugin_stop(&e, &bot, &name);
                    }
                    PluginCmd::ReStart { name } => {
                        plugin_restart(&e, &bot, &name).await;
                    }
                },
                KoviCmd::Status => status(&e, &bot, info).await,
                KoviCmd::Acc { name, acc_cmd } => acc(&e, &bot, &name, acc_cmd),
            }
        }
    });
}

static HELP_MSG: &str = r#"┄ 📜 帮助列表 ┄
.kovi plugin <T>: 插件管理
.kovi acc <name> <T>: 访问控制
.kovi status: 状态信息
部分命令可缩写为第一个字母"#;

static HELP_PLUGIN: &str = r#"┄ 📜 插件管理 ┄:
.kovi plugin <T>

<T>:
list: 列出所有插件
start <name>: 启动插件
stop <name>: 停止插件
restart <name>: 重载插件"#;

static ACC_CONTROL_PLUGIN: &str = r#"┄ 📜 访问控制 ┄:
.kovi acc <name> <T>

<T>:
status: 列出插件访问控制信息
enable: 启用插件访问控制
disable: 禁用插件访问控制
mode <white | black>: 插件访问控制模式
on: 添加本群到列表
off: 移除本群到列表
add <friend | group> [id]: 添加多个
remove <friend | group> [id]: 移除多个"#;

fn help(e: &AdminMsgEvent, item: HelpItem) {
    match item {
        HelpItem::Plugin => {
            e.reply(HELP_PLUGIN);
        }
        HelpItem::Acc => {
            e.reply(ACC_CONTROL_PLUGIN);
        }
        HelpItem::None => {
            e.reply(HELP_MSG);
        }
    }
}

async fn status(e: &AdminMsgEvent, bot: &RuntimeBot, info: Arc<Mutex<Info>>) {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    let info = { *info.lock().unwrap() };

    let duration = now - info.start_time;

    // 计算运行时间
    let days = duration / (24 * 3600);
    let hours = (duration % (24 * 3600)) / 3600;
    let minutes = (duration % 3600) / 60;
    let seconds = duration % 60;

    // 获取内存使用情况
    let mut sys = System::new();

    let pid = Pid::from_u32(std::process::id());
    sys.refresh_processes(ProcessesToUpdate::Some(&[pid]), true);
    sys.refresh_memory();

    let self_memory_usage = sys
        .process(pid)
        .map(|process| process.memory() as f64 / 1024.0 / 1024.0)
        .unwrap_or(0.0);

    let total_memory = sys.total_memory() as f64 / 1024.0 / 1024.0 / 1024.0;
    let used_memory = sys.used_memory() as f64 / 1024.0 / 1024.0 / 1024.0;
    let memory_usage_percent = (used_memory / total_memory) * 100.0;

    let time_str = if days > 0 {
        format!("{}d{}h{}m{}s", days, hours, minutes, seconds)
    } else if hours > 0 {
        format!("{}h{}m{}s", hours, minutes, seconds)
    } else if minutes > 0 {
        format!("{}m{}s", minutes, seconds)
    } else {
        format!("{}s", seconds)
    };

    let plugin_info = bot.get_plugin_info().unwrap();

    let plugin_start_len = plugin_info.iter().filter(|v| v.enabled).count();

    #[derive(Debug, serde::Deserialize, serde::Serialize)]
    struct OnebotInfo {
        app_name: Option<String>,
        app_version: Option<String>,
    }

    let onebot_info: Option<OnebotInfo> = match bot.get_version_info().await {
        Ok(v) => match serde_json::from_value::<OnebotInfo>(v.data) {
            Ok(v) => Some(v),
            Err(_) => None,
        },
        Err(_) => None,
    };

    let onebot_info_str = match onebot_info {
        Some(v) => {
            let mut msg = "".to_string();

            if let Some(app_name) = v.app_name {
                msg.push_str(&app_name);
            }
            if let Some(app_version) = v.app_version {
                msg.push_str(&format!("({})", app_version));
            }

            msg
        }
        None => "信息获取失败".to_string(),
    };

    let plugin_info_len = plugin_info.len();

    let accept_msg = info.accept_msg;
    let send_msg = info.send_msg;

    let reply = format!(
        "┄ 📑 状态 ┄\n\
        🕑 运行时间: {time_str}\n\
        ✉️ 消息状况: 收发{accept_msg}/{send_msg}\n\
        📦 插件数量: {plugin_info_len} 启用 {plugin_start_len}\n\
        🔋 内存使用: {self_memory_usage:.2}MB\n\
        💻 系统内存:\n  {:.2}GB/{:.2}GB({:.0}%)\n\
        🔗 服务端:\n  {}",
        used_memory, total_memory, memory_usage_percent, onebot_info_str
    );

    e.reply(reply);
}

fn acc(e: &AdminMsgEvent, bot: &RuntimeBot, plugin_name: &str, acc_cmd: AccControlCmd) {
    let plugin_name = is_not_empty_or_more_times_and_reply(e, bot, plugin_name);

    let plugin_name = match plugin_name {
        Some(v) => v,
        None => return,
    };

    if plugin_is_self(&plugin_name) && acc_cmd != AccControlCmd::Status {
        e.reply("⛔ 不允许修改CMD插件");
        return;
    }
    match acc_cmd {
        AccControlCmd::Enable(b) => match bot.set_plugin_access_control(&plugin_name, b) {
            Ok(_) => {
                e.reply("✅ 设置成功");
            }
            Err(err) => match err {
                BotError::PluginNotFound(_) => {
                    e.reply(format!("🔎 插件{}不存在", &plugin_name));
                }
                BotError::RefExpired => {
                    panic!("CMD: Bot RefExpired");
                }
            },
        },
        AccControlCmd::SetMode(v) => match bot.set_plugin_access_control_mode(&plugin_name, v) {
            Ok(_) => {
                e.reply("✅ 设置成功");
            }
            Err(err) => match err {
                BotError::PluginNotFound(_) => {
                    e.reply(format!("🔎 插件{}不存在", &plugin_name));
                }
                BotError::RefExpired => {
                    panic!("CMD: Bot RefExpired");
                }
            },
        },
        AccControlCmd::Change(change) => match change {
            CmdSetAccessControlList::GroupAdds(v) => {
                process_ids(v, true, true, &plugin_name, bot, e);
            }
            CmdSetAccessControlList::GroupRemoves(v) => {
                process_ids(v, true, false, &plugin_name, bot, e);
            }
            CmdSetAccessControlList::FriendAdds(v) => {
                process_ids(v, false, true, &plugin_name, bot, e);
            }
            CmdSetAccessControlList::FriendRemoves(v) => {
                process_ids(v, false, false, &plugin_name, bot, e);
            }
        },
        AccControlCmd::Status => {
            let plugin_infos = match bot.get_plugin_info() {
                Ok(v) => v,
                Err(_) => panic!("CMD: Bot RefExpired"),
            };

            for info in plugin_infos {
                if info.name == plugin_name {
                    let boo = if info.access_control { "" } else { "" };
                    let mode = match info.list_mode {
                        AccessControlMode::BlackList => "黑名单",
                        AccessControlMode::WhiteList => "白名单",
                    };
                    let list = info.access_list;
                    let group_list = list.groups;
                    let friend_list = list.friends;
                    let group_list_str = if group_list.is_empty() {
                        "".to_string()
                    } else {
                        group_list
                            .iter()
                            .map(|v| v.to_string())
                            .collect::<Vec<String>>()
                            .join(", ")
                    };
                    let friend_list = if friend_list.is_empty() {
                        "".to_string()
                    } else {
                        friend_list
                            .iter()
                            .map(|v| v.to_string())
                            .collect::<Vec<String>>()
                            .join(", ")
                    };

                    let msg = format!(
                        "📦 插件{}\n访问控制:{}\n模式:{}\n群组:{}\n好友列表:{}",
                        plugin_name, boo, mode, group_list_str, friend_list
                    );
                    e.reply(msg);
                    return;
                }
            }

            e.reply("🔎 插件不存在");
        }
        AccControlCmd::GroupIsEnable(boo) => {
            if e.is_private() {
                e.reply("⛔ 只能在群聊中使用");
                return;
            }

            let set_access = if boo {
                SetAccessControlList::Add(e.group_id.unwrap())
            } else {
                SetAccessControlList::Remove(e.group_id.unwrap())
            };

            match bot.set_plugin_access_control_list(&plugin_name, true, set_access) {
                Ok(_) => {
                    let msg = if boo {
                        format!(
                            "✅ 插件{}访问控制已添加{}",
                            plugin_name,
                            e.group_id.unwrap()
                        )
                    } else {
                        format!(
                            "✅ 插件{}访问控制已移除{}",
                            plugin_name,
                            e.group_id.unwrap()
                        )
                    };
                    e.reply(msg);
                }
                Err(err) => match err {
                    BotError::PluginNotFound(_) => {
                        e.reply(format!("🔎 插件{}不存在", plugin_name));
                    }
                    BotError::RefExpired => {
                        panic!("CMD: Bot RefExpired");
                    }
                },
            }
        }
    }
}

/// 设置插件访问控制列表
fn process_ids(
    v: Vec<String>,
    is_group: bool,
    is_add: bool,
    plugin_name: &str,
    bot: &RuntimeBot,
    e: &AdminMsgEvent,
) {
    let mut vec_i64: Vec<i64> = Vec::new();

    for str in v {
        match str.parse() {
            Ok(v) => {
                vec_i64.push(v);
            }
            Err(_) => {
                e.reply("❎ 设置失败");
                return;
            }
        }
    }

    let vec_i64 = if is_add {
        SetAccessControlList::Adds(vec_i64)
    } else {
        SetAccessControlList::Removes(vec_i64)
    };

    match bot.set_plugin_access_control_list(plugin_name, is_group, vec_i64) {
        Ok(_) => {
            e.reply("✅ 设置成功");
        }
        Err(err) => match err {
            BotError::PluginNotFound(_) => {
                e.reply(format!("🔎 插件{}不存在", plugin_name));
            }
            BotError::RefExpired => {
                panic!("CMD: Bot RefExpired");
            }
        },
    }
}

fn plugin_start(e: &AdminMsgEvent, bot: &RuntimeBot, name: &str) {
    let name = is_not_empty_or_more_times_and_reply(e, bot, name);

    let name = match name {
        Some(v) => v,
        None => return,
    };

    if plugin_is_self(&name) {
        e.reply("🏳️ 这么做...,你想干嘛");
        return;
    }
    match bot.enable_plugin(&name) {
        Ok(_) => {
            e.reply(format!("✅ 插件{}启动成功", name));
        }
        Err(err) => match err {
            BotError::PluginNotFound(_) => {
                e.reply(format!("🔎 插件{}不存在", name));
            }
            BotError::RefExpired => {
                panic!("CMD: Bot RefExpired");
            }
        },
    }
}

fn plugin_stop(e: &AdminMsgEvent, bot: &RuntimeBot, name: &str) {
    let name = is_not_empty_or_more_times_and_reply(e, bot, name);

    let name = match name {
        Some(v) => v,
        None => return,
    };

    if plugin_is_self(&name) {
        e.reply("⛔ 不允许关闭CMD插件");
        return;
    }
    match bot.disable_plugin(&name) {
        Ok(_) => {
            e.reply(format!("✅ 插件{}关闭成功", name));
        }
        Err(err) => match err {
            BotError::PluginNotFound(_) => {
                e.reply(format!("🔎 插件{}不存在", name));
            }
            BotError::RefExpired => {
                panic!("CMD: Bot RefExpired");
            }
        },
    }
}

async fn plugin_restart(e: &AdminMsgEvent, bot: &RuntimeBot, name: &str) {
    let name = is_not_empty_or_more_times_and_reply(e, bot, name);

    let name = match name {
        Some(v) => v,
        None => return,
    };

    if plugin_is_self(&name) {
        e.reply("⛔ 不允许重载CMD插件");
        return;
    }
    match bot.restart_plugin(&name).await {
        Ok(_) => {
            e.reply(format!("✅ 插件{}重载成功", name));
        }
        Err(err) => match err {
            BotError::PluginNotFound(_) => {
                e.reply(format!("🔎 插件{}不存在", name));
            }
            BotError::RefExpired => {
                panic!("CMD: Bot RefExpired");
            }
        },
    }
}

fn plugin_status(e: &AdminMsgEvent, bot: &RuntimeBot) {
    let plugin_info = bot.get_plugin_info().unwrap();
    if plugin_info.is_empty() {
        e.reply("🔎 插件列表为空");
        return;
    }

    let mut msg = "┄ 📑 插件列表 ┄\n".to_string();

    plugin_info.iter().for_each(|info| {
        let boo = if info.enabled { "" } else { "" };

        let msg_ = format!("{} {}(v{})\n", boo, info.name, info.version);
        msg.push_str(&msg_);
    });

    e.reply(msg.trim());
}

/// 检查插件名是否为空或多个插件名并排除掉全匹配,返回第一个插件名或None,顺带回复
fn is_not_empty_or_more_times_and_reply(
    e: &AdminMsgEvent,
    bot: &RuntimeBot,
    name: &str,
) -> Option<String> {
    let names = match get_plugin_full_name(bot, name) {
        Ok(names) => names,
        Err(err) => {
            log::error!("CMD: {}", err);
            panic!("{err}")
        }
    };

    if names.is_empty() {
        e.reply("🔎 插件列表为空");
        return None;
    } else if names.len() > 1 {
        // 检测是否有全匹配
        let full_name = names.iter().find(|n| n == &name);
        if let Some(full_name) = full_name {
            return Some(full_name.clone());
        }

        e.reply(format!("┄ 🔎 寻找到多个插件 ┄\n{}", names.join("\n")));
        return None;
    }

    names.into_iter().next()
}

fn get_plugin_full_name(bot: &RuntimeBot, name: &str) -> Result<Vec<String>, BotError> {
    let plugins = match bot.get_plugin_info() {
        Ok(plugins) => plugins,
        Err(err) => {
            log::error!("CMD: {}", err);
            return Err(err);
        }
    };

    let names = plugins
        .iter()
        .filter_map(|v| {
            if v.name.contains(name) {
                Some(v.name.clone())
            } else {
                None
            }
        })
        .collect();

    Ok(names)
}

fn plugin_is_self(name: &str) -> bool {
    name == env!("CARGO_PKG_NAME")
}

#[test]
fn test_parse() {
    let cmd = KoviArgs::parse(vec![".kovi".to_string()]);

    println!("{:?}", cmd);
}