kovi_onebot/
message_trait.rs1use serde::Serialize;
2use serde_json::{Value, json};
3use std::fmt::Display;
4
5use kovi::{Message, Segment};
6
7pub trait MessageRegistrar: Sized {
8 fn push(&mut self, s: Segment);
9
10 fn add_text<T>(mut self, text: T) -> Self
12 where
13 String: From<T>,
14 T: Serialize + Display,
15 {
16 self.push(Segment {
17 kind: "text".to_string(),
18 data: json!({ "text": text }),
19 });
20 self
21 }
22
23 fn add_at(mut self, id: &str) -> Self {
25 self.push(Segment {
26 kind: "at".to_string(),
27 data: json!({ "qq": id }),
28 });
29 self
30 }
31
32 fn add_mention(mut self, id: &str) -> Self {
34 self.push(Segment {
35 kind: "at".to_string(),
36 data: json!({ "qq": id }),
37 });
38 self
39 }
40
41 fn add_reply(mut self, message_id: i32) -> Self {
43 self.push(Segment {
44 kind: "reply".to_string(),
45 data: json!({ "id": message_id.to_string() }),
46 });
47 self
48 }
49
50 fn add_face(mut self, id: i64) -> Self {
52 self.push(Segment {
53 kind: "face".to_string(),
54 data: json!({ "id": id.to_string() }),
55 });
56 self
57 }
58
59 fn add_image(mut self, file: &str) -> Self {
61 self.push(Segment {
62 kind: "image".to_string(),
63 data: json!({ "file": file }),
64 });
65 self
66 }
67
68 fn add_segment<T>(mut self, segment: T) -> Self
70 where
71 Value: From<T>,
72 T: Serialize,
73 {
74 let value = Value::from(segment);
75 if let Ok(segment) = serde_json::from_value(value) {
76 self.push(segment);
77 }
78 self
79 }
80
81 fn push_text<T>(&mut self, text: T)
83 where
84 String: From<T>,
85 T: Serialize + Display,
86 {
87 self.push(Segment {
88 kind: "text".to_string(),
89 data: json!({ "text": text }),
90 });
91 }
92
93 fn push_at(&mut self, id: &str) {
95 self.push(Segment {
96 kind: "at".to_string(),
97 data: json!({ "qq": id }),
98 });
99 }
100
101 fn push_reply(&mut self, message_id: i32) {
103 self.push(Segment {
104 kind: "reply".to_string(),
105 data: json!({ "id": message_id.to_string() }),
106 });
107 }
108
109 fn push_face(&mut self, id: i64) {
111 self.push(Segment {
112 kind: "face".to_string(),
113 data: json!({ "id": id.to_string() }),
114 });
115 }
116
117 fn push_image(&mut self, file: &str) {
119 self.push(Segment {
120 kind: "image".to_string(),
121 data: json!({ "file": file }),
122 });
123 }
124}
125
126impl MessageRegistrar for Message {
127 fn push(&mut self, s: Segment) {
128 self.push(s);
129 }
130}