Skip to main content

kovi_onebot/event/
request_event.rs

1use crate::event::PostType;
2use kovi::bot::BotInformation;
3use kovi::error::EventBuildError;
4use kovi::event::{Event, InternalEvent};
5use kovi::types::ApiAndOptOneshot;
6use serde_json::Value;
7use serde_json::value::Index;
8use tokio::sync::mpsc;
9
10#[derive(Debug, Clone)]
11pub struct RequestEvent {
12    /// 事件发生的时间戳
13    pub time: i64,
14    /// 收到事件的机器人 登陆号
15    pub self_id: i64,
16    /// 上报类型
17    pub post_type: PostType,
18    /// 请求类型
19    pub request_type: String,
20
21    /// 原始的onebot消息,已处理成json格式
22    pub original_json: Value,
23}
24impl Event for RequestEvent {
25    fn de(
26        event: &InternalEvent,
27        _: &BotInformation,
28        _: &mpsc::Sender<ApiAndOptOneshot>,
29    ) -> Option<Self> {
30        let InternalEvent::DriverEvent(json) = event else {
31            return None;
32        };
33
34        Self::new(json).ok()
35    }
36}
37
38impl RequestEvent {
39    pub(crate) fn new(temp: &Value) -> Result<RequestEvent, EventBuildError> {
40        let time = temp
41            .get("time")
42            .and_then(Value::as_i64)
43            .ok_or(EventBuildError::ParseError("time".to_string()))?;
44        let self_id = temp
45            .get("self_id")
46            .and_then(Value::as_i64)
47            .ok_or(EventBuildError::ParseError("self_id".to_string()))?;
48        let post_type = temp
49            .get("post_type")
50            .and_then(|v| serde_json::from_value::<PostType>(v.clone()).ok())
51            .ok_or(EventBuildError::ParseError("Invalid post_type".to_string()))?;
52        let request_type = temp
53            .get("request_type")
54            .and_then(Value::as_str)
55            .map(String::from)
56            .ok_or(EventBuildError::ParseError("request_type".to_string()))?;
57        Ok(RequestEvent {
58            time,
59            self_id,
60            post_type,
61            request_type,
62            original_json: temp.clone(),
63        })
64    }
65}
66
67impl RequestEvent {
68    /// 直接从原始的 Json Value 获取某值
69    ///
70    /// # example
71    ///
72    /// ```ignore
73    /// use kovi::PluginBuilder;
74    ///
75    /// PluginBuilder::on_request(|event| async move {
76    ///     let time = event.get("time").and_then(|v| v.as_i64()).unwrap();
77    ///
78    ///     assert_eq!(time, event.time);
79    /// });
80    /// ```
81    pub fn get<I: Index>(&self, index: I) -> Option<&Value> {
82        self.original_json.get(index)
83    }
84}
85
86impl<I> std::ops::Index<I> for RequestEvent
87where
88    I: Index,
89{
90    type Output = Value;
91
92    fn index(&self, index: I) -> &Self::Output {
93        &self.original_json[index]
94    }
95}