use crate::event::PostType;
use kovi::bot::BotInformation;
use kovi::error::EventBuildError;
use kovi::event::{Event, InternalEvent};
use kovi::types::ApiAndOptOneshot;
use serde_json::Value;
use serde_json::value::Index;
use tokio::sync::mpsc;
#[derive(Debug, Clone)]
pub struct NoticeEvent {
pub time: i64,
pub self_id: i64,
pub post_type: PostType,
pub notice_type: String,
pub original_json: Value,
}
impl Event for NoticeEvent {
fn de(
event: &InternalEvent,
_: &BotInformation,
_: &mpsc::Sender<ApiAndOptOneshot>,
) -> Option<Self> {
let InternalEvent::DriverEvent(json) = event else {
return None;
};
Self::new(json).ok()
}
}
impl NoticeEvent {
pub(crate) fn new(temp: &Value) -> Result<NoticeEvent, EventBuildError> {
let time = temp
.get("time")
.and_then(Value::as_i64)
.ok_or(EventBuildError::ParseError("time".to_string()))?;
let self_id = temp
.get("self_id")
.and_then(Value::as_i64)
.ok_or(EventBuildError::ParseError("self_id".to_string()))?;
let post_type = temp
.get("post_type")
.and_then(|v| serde_json::from_value::<PostType>(v.clone()).ok())
.ok_or(EventBuildError::ParseError("Invalid post_type".to_string()))?;
let notice_type = temp
.get("notice_type")
.and_then(Value::as_str)
.map(String::from)
.ok_or(EventBuildError::ParseError("notice_type".to_string()))?;
Ok(NoticeEvent {
time,
self_id,
post_type,
notice_type,
original_json: temp.clone(),
})
}
}
impl NoticeEvent {
pub fn get<I: Index>(&self, index: I) -> Option<&Value> {
self.original_json.get(index)
}
}
impl<I> std::ops::Index<I> for NoticeEvent
where
I: Index,
{
type Output = Value;
fn index(&self, index: I) -> &Self::Output {
&self.original_json[index]
}
}