datcord/
commands.rs

1use reqwest::{
2	Client,
3	Response,
4	header
5};
6use serde::{Serialize, Deserialize};
7use serde_repr::{Serialize_repr, Deserialize_repr};
8
9
10
11lazy_static! {
12
13	static ref CLIENT: Client = Client::new();
14
15	static ref CLIENT_ID: String = dotenv::var("CLIENT_ID").unwrap();
16	static ref BOT_TOKEN: String = dotenv::var("BOT_TOKEN").unwrap();
17	
18}
19
20
21
22#[derive(Serialize_repr, Deserialize_repr, Debug)]
23#[repr(u8)]
24pub enum CommandType {
25	ChatInput = 1,
26	User = 2,
27	Message = 3,
28}
29
30#[derive(Serialize, Deserialize)]
31pub struct Command {
32	pub id: String,
33	name: String,
34	#[serde(rename = "type")]
35	typ: CommandType,
36	description: String,
37	options: Option<Vec<CommandOption>>,
38}
39impl Command {
40
41	// creates a new command and registers it in the discord api
42	pub async fn new(name: String, typ: CommandType, description: String, options: Option<Vec<CommandOption>>) -> Result<Self, reqwest::Error> {
43		
44		let command = Self { id: "0".to_string(), name, typ, description, options };
45
46		match CLIENT
47			.post(format!("https://discord.com/api/v10/applications/{}/commands", CLIENT_ID.to_string()))
48			.header(header::AUTHORIZATION, format!("Bot {}", BOT_TOKEN.to_string()))
49			.json(&command)
50			.send()
51			.await {
52				Ok(r) => r.json::<Command>().await,
53				Err(e) => Err(e),
54			}
55
56	}
57
58	// removes current command from the discord api
59	pub async fn remove(self) -> Result<Response, reqwest::Error> {
60
61		CLIENT
62			.delete(format!("https://discord.com/api/v10/applications/{}/commands/{}", dotenv::var("CLIENT_ID").unwrap(), self.id))
63			.header(header::AUTHORIZATION, format!("Bot {}", dotenv::var("BOT_TOKEN").unwrap()))
64			.send()
65			.await
66
67	}
68
69	// gets all commands from the discord api
70	pub async fn get_all() -> Result<Vec<Command>, reqwest::Error> {
71
72		match CLIENT
73			.get(format!("https://discord.com/api/v10/applications/{}/commands", CLIENT_ID.to_string()))
74			.header(header::AUTHORIZATION, format!("Bot {}", BOT_TOKEN.to_string()))
75			.send()
76			.await {
77				Ok(r) => r.json::<Vec<Command>>().await,
78				Err(e) => Err(e),
79			}
80
81	}
82	
83}
84
85
86
87#[derive(Serialize, Deserialize, Debug)]
88pub struct CommandOption {
89	name: String,
90	#[serde(rename = "type")]
91	typ: u8,
92	description: String,
93	required: bool,
94	choices: Option<Vec<CommandOptionChoice>>,
95}
96impl CommandOption {
97	pub	fn new(name: String, typ: u8, description: String, required: bool, choices: Option<Vec<CommandOptionChoice>>) -> Self {
98		Self { name, typ, description, required, choices }
99	}
100}
101
102
103
104#[derive(Serialize, Deserialize, Debug)]
105pub struct CommandOptionChoice {
106	name: String,
107	value: String,
108}
109impl CommandOptionChoice {
110	pub fn new(name: String, value: String) -> Self {
111		Self { name, value }
112	}
113}