Skip to main content

dingtalk_stream/handlers/
graph.rs

1//! Graph API 处理器,对齐 Python graph.py GraphHandler
2
3use crate::handlers::callback::CallbackHandler;
4use crate::messages::graph::{GraphRequest, GraphResponse, StatusLine};
5use crate::transport::http::HttpClient;
6use async_trait::async_trait;
7use std::collections::HashMap;
8
9/// Graph API 处理器 trait
10#[async_trait]
11pub trait GraphHandler: CallbackHandler {
12    /// 处理 Graph 请求
13    async fn on_graph_request(&self, request: &GraphRequest) -> crate::Result<GraphResponse>;
14}
15
16/// Graph 回复工具
17pub struct GraphReplier {
18    http_client: HttpClient,
19}
20
21impl GraphReplier {
22    /// Graph Markdown 模板 ID
23    pub const MARKDOWN_TEMPLATE_ID: &'static str = "d28e2ac5-fb34-4d93-94bc-cf5c580c2d4f.schema";
24
25    /// 创建新的 `GraphReplier`
26    pub fn new(http_client: HttpClient) -> Self {
27        Self { http_client }
28    }
29
30    /// 通过 webhook 回复 markdown
31    pub async fn reply_markdown(
32        &self,
33        webhook: &str,
34        content: &str,
35    ) -> crate::Result<(u16, String)> {
36        let payload = serde_json::json!({
37            "contentType": "ai_card",
38            "content": {
39                "templateId": Self::MARKDOWN_TEMPLATE_ID,
40                "cardData": {
41                    "content": content,
42                }
43            }
44        });
45
46        self.http_client.post_json_raw(webhook, &payload).await
47    }
48
49    /// 构建成功响应
50    pub fn success_response(payload: Option<serde_json::Value>) -> GraphResponse {
51        let body = payload.unwrap_or_default();
52        GraphResponse {
53            body: Some(serde_json::to_string(&body).unwrap_or_default()),
54            headers: {
55                let mut h = HashMap::new();
56                h.insert("Content-Type".to_owned(), "application/json".to_owned());
57                h
58            },
59            status_line: StatusLine {
60                code: 200,
61                reason_phrase: "OK".to_owned(),
62                extensions: HashMap::new(),
63            },
64            extensions: HashMap::new(),
65        }
66    }
67}