Skip to main content

fishpi_sdk/api/
redpacket.rs

1//! 红包 API 模块
2//!
3//! 这个模块提供了与红包相关的 API 操作,包括打开红包、发送红包等功能。
4//! 主要结构体是 `Redpacket`,用于管理红包的发送和接收。
5//! 红包支持普通红包、猜拳红包等类型。
6//!
7//! # 主要组件
8//!
9//! - [`Redpacket`] - 红包客户端结构体,负责打开和发送红包。
10//!
11//! # 方法列表
12//!
13//! - [`Redpacket::new`] - 创建新的红包客户端实例。
14//! - [`Redpacket::open`] - 打开一个红包。
15//! - [`Redpacket::send`] - 发送一个红包。
16//!
17//! # 示例
18//!
19//! ```rust,no_run
20//! use fishpi_sdk::api::redpacket::Redpacket;
21//! use fishpi_sdk::model::redpacket::{GestureType, RedPacket, RedPacketType};
22//!
23//! #[tokio::main]
24//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
25//!     let redpacket = Redpacket::new("your_api_key".to_string());
26//!
27//!     // 发送红包
28//!     let rp = RedPacket {
29//!         r#type: RedPacketType::Random,
30//!         money: 32,
31//!         count: 5,
32//!         msg: "古德古德".to_string(),
33//!         recivers: vec![],
34//!         gesture: Some(GestureType::Rock),
35//!     };
36//!     redpacket.send(&rp).await?;
37//!
38//!     // 打开红包
39//!     let info = redpacket.open("redpacket_id", Some(GestureType::Paper)).await?;
40//!     println!("Opened redpacket: {:?}", info);
41//!
42//!     Ok(())
43//! }
44//! ```
45use serde_json::json;
46
47use crate::api::chatroom::ChatRoom;
48use crate::model::redpacket::{GestureType, RedPacket, RedPacketInfo};
49use crate::utils::error::Error;
50use crate::utils::post;
51
52pub struct Redpacket {
53    api_key: String,
54    chatroom: ChatRoom,
55}
56
57impl Redpacket {
58    pub fn new(api_key: String) -> Self {
59        Self {
60            api_key: api_key.clone(),
61            chatroom: ChatRoom::new(api_key),
62        }
63    }
64
65    /// 打开一个红包
66    ///
67    /// * `oId` 红包消息 Id
68    /// * `gesture` 猜拳类型 [GestureType]
69    ///
70    /// [RedPacketInfo]返回红包信息
71    pub async fn open(
72        &self,
73        oid: &str,
74        gesture: Option<GestureType>,
75    ) -> Result<RedPacketInfo, Error> {
76        let url = "chat-room/red-packet/open".to_string();
77
78        let data = json!({
79            "oId": oid,
80            "gesture": gesture.map(|g| g as u8),
81            "apiKey": self.api_key
82        });
83
84        let resp = post(&url, Some(data)).await?;
85
86        if let Some(code) = resp.get("code").and_then(|c| c.as_i64())
87            && code != 0
88        {
89            return Err(Error::Api(
90                resp["msg"].as_str().unwrap_or("API error").to_string(),
91            ));
92        }
93
94        let red_packet_info: RedPacketInfo = RedPacketInfo::from_value(&resp)?;
95        Ok(red_packet_info)
96    }
97
98    /// 发送一个红包
99    ///
100    /// #### 参数
101    /// * `redpacket` 红包对象 [RedPacket]
102    pub async fn send(&self, redpacket: &RedPacket) -> Result<(), Error> {
103        let data = json!({
104            "type": redpacket.r#type.as_str(),
105            "money": redpacket.money,
106            "count": redpacket.count,
107            "msg": redpacket.msg,
108            "recivers": redpacket.recivers,
109            "gesture": redpacket.gesture.clone().map(|g| g as u8),
110            "apiKey": self.api_key
111        });
112
113        self.chatroom
114            .send(format!("[redpacket]{}[/redpacket]", data))
115            .await?;
116        Ok(())
117    }
118}