1use std::time::Duration;
2
3use async_trait::async_trait;
4use chrono::{
5 format::{DelayedFormat, StrftimeItems},
6 Utc,
7};
8use reqwest::{
9 header::{AUTHORIZATION, USER_AGENT},
10 Client, Method, RequestBuilder,
11};
12use serde::{Deserialize, Serialize};
13use url::Url;
14
15use crate::{
16 wss::{EmojiEvent, HeartbeatEvent, LoginEvent, MessageEvent, Subscription},
17 QQResult,
18};
19
20mod secret_key;
21
22#[derive(Serialize, Deserialize, Default, Debug, Clone)]
23pub struct QQSecret {
24 bot_app_id: u64,
25 bot_secret: String,
26 bot_token: String,
27 test: ChannelIds,
28 deploy: ChannelIds,
29}
30
31#[derive(Serialize, Deserialize, Default, Debug, Clone)]
32pub struct ChannelIds {
33 guild_id: u64,
34 channel_id: u64,
35}
36
37fn current_time<'a>() -> DelayedFormat<StrftimeItems<'a>> {
38 Utc::now().format("%F %H:%M:%S")
39}
40
41#[async_trait]
42#[allow(unused_variables)]
43pub trait QQBotProtocol: Send {
44 fn build_bot_token(&self) -> String;
45 fn build_request(&self, method: Method, url: Url) -> RequestBuilder;
46 fn subscription(&self) -> Subscription {
47 Subscription::GUILD_MESSAGES
49 | Subscription::GUILD_MESSAGE_REACTIONS
50 | Subscription::INTERACTION
51 | Subscription::PUBLIC_GUILD_MESSAGES
52 }
53 async fn on_connected(&mut self, event: HeartbeatEvent) -> QQResult {
54 println!("[{}] 协议 10", current_time());
55 println!(" 已连接");
56 Ok(())
57 }
58 async fn on_login_success(&mut self, event: LoginEvent) -> QQResult {
59 println!("[{}] 协议 9", current_time());
60 println!(" 登录成功, 登陆为 {:?}", event.user.username);
61 Ok(())
62 }
63 async fn on_login_failure(&mut self) -> QQResult {
64 println!("[{}] 协议 9", current_time());
65 println!(" 鉴权参数有误");
66 Ok(())
67 }
68 async fn on_heartbeat(&mut self, heartbeat_id: u32) -> QQResult {
69 println!("[{}] 协议 1", current_time());
70 println!(" 发送心跳包 {}", heartbeat_id);
71 Ok(())
72 }
73 async fn on_message(&mut self, event: MessageEvent) -> QQResult {
74 println!("[{}] 协议 0", current_time());
75 println!(" 收到消息, 发送者为 {:?}", event.author.username);
76 Ok(())
77 }
78 async fn on_emoji(&mut self, event: EmojiEvent) -> QQResult {
79 println!("[{}] 协议 0", current_time());
80 println!(" 消息 {} 表情变动", event.target.id);
81 Ok(())
82 }
83 async fn on_save(&mut self) -> QQResult {
84 Ok(())
85 }
86}
87
88pub struct SimpleBot {
89 pub heartbeat_interval: u64,
90 pub secret: QQSecret,
91}
92
93#[async_trait]
94impl QQBotProtocol for SimpleBot {
95 fn build_bot_token(&self) -> String {
96 self.secret.bot_token()
97 }
98 fn build_request(&self, method: Method, url: Url) -> RequestBuilder {
99 self.secret.as_request(method, url)
100 }
101 async fn on_connected(&mut self, event: HeartbeatEvent) -> QQResult {
102 self.heartbeat_interval = event.heartbeat_interval;
103 Ok(())
104 }
105 async fn on_message(&mut self, event: MessageEvent) -> QQResult {
106 println!("收到消息 {:#?}", event);
108 Ok(())
109 }
110}