botcat-capoo 1.0.3

A NapCat based QQ bot implemented in Rust
Documentation
use std::error::Error;

use serde_json::json;

use crate::{
    api::napcat::napcat_request,
    config::AppConfig,
    model::{
        api::history::{GroupHistoryResponse, PrivateHistoryResponse},
        event::{GroupMessageEvent, PrivateMessageEvent},
    },
};

pub async fn get_group_history(
    config: &AppConfig,
    group_id: u64,
    count: u64,
    reverse: bool,
) -> Result<Vec<GroupMessageEvent>, Box<dyn Error>> {
    let body = json!({
        "group_id": group_id,
        "message_seq": 0,
        "count": count,
        "reverseOrder": reverse,
    });

    let raw_resp = &napcat_request(config, "/get_group_msg_history", &body).await?;
    let response: GroupHistoryResponse = serde_json::from_value(raw_resp.to_owned())?;

    if let Some(data) = response.data {
        Ok(data.messages)
    } else {
        Err(Box::new(std::io::Error::other(format!(
            "Unknown error occurred, raw response is {raw_resp}"
        ))))
    }
}

pub async fn get_private_history(
    config: &AppConfig,
    user_id: u64,
    count: u64,
    reverse: bool,
) -> Result<Vec<PrivateMessageEvent>, Box<dyn Error>> {
    let body = json!({
        "user_id": user_id,
        "message_seq": 0,
        "count": count,
        "reverseOrder": reverse,
    });

    let raw_resp = &napcat_request(config, "/get_friend_msg_history", &body).await?;
    let response: PrivateHistoryResponse = serde_json::from_value(raw_resp.to_owned())?;

    if let Some(data) = response.data {
        Ok(data.messages)
    } else {
        Err(Box::new(std::io::Error::other(format!(
            "Unknown error occurred, raw response is {raw_resp}"
        ))))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    #[ignore = "Requires an API server in internal network"]
    async fn test_get_group_history() {
        let config = AppConfig::init().expect("Failed to load config");
        println!("Loaded config");

        match get_group_history(&config, 738943282, 20, true).await {
            Ok(messages) => {
                println!("Successfully fetched {} group messages:", messages.len());
            }
            Err(err) => {
                eprintln!("Failed to fetch group history: {err}");
            }
        }
    }

    #[tokio::test]
    #[ignore = "Requires an API server in internal network"]
    async fn test_get_private_history() {
        let config = AppConfig::init().expect("Failed to load config");
        println!("Loaded config");

        match get_private_history(&config, 46595749, 20, true).await {
            Ok(messages) => {
                println!("Successfully fetched {} private messages:", messages.len());
            }
            Err(err) => {
                eprintln!("Failed to fetch private history: {err}");
            }
        }
    }
}