Skip to content

Commit 28a1801

Browse files
committed
Implement CAH
1 parent 23c1aa7 commit 28a1801

File tree

17 files changed

+1143
-142
lines changed

17 files changed

+1143
-142
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ discord = { path = "discord" }
1515
futures-util = "0.3.28"
1616
monostate = "0.1.6"
1717
ini = "1.3.0"
18+
rand = "0.8.5"
1819

1920
[patch.crates-io]
2021
serde = { git = "https://github.com/Astavie/serde.git", branch = "integer-tags-for-enums-noprecompile" }

discord/partial_id/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@ pub fn derive_partial(input: proc_macro::TokenStream) -> proc_macro::TokenStream
5858
if ident.to_string() == "id" {
5959
quote!{}
6060
} else {
61-
let get_ident = Ident::new(&format!("get_{}", ident), Span::call_site());
62-
let get_ident_mut = Ident::new(&format!("get_{}_mut", ident), Span::call_site());
61+
let get_ident = Ident::new(&format!("get_{}", ident), ident.span());
62+
let get_ident_mut = Ident::new(&format!("get_{}_mut", ident), ident.span());
6363
quote! {
6464
#vis async fn #get_ident(&mut self, client: &crate::request::Discord) -> crate::request::Result<&#ty> {
6565
crate::request::Result::Ok(match self.#ident {

discord/src/command.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,28 @@ impl CommandData {
6666
#[derive(Debug, Deserialize, Serialize)]
6767
#[serde(tag = "type")]
6868
pub enum CommandOption {
69+
#[serde(rename = 1)]
70+
SubCommand,
71+
#[serde(rename = 2)]
72+
SubCommandGroup,
6973
#[serde(rename = 3)]
7074
String(StringOption),
75+
#[serde(rename = 4)]
76+
Integer,
77+
#[serde(rename = 5)]
78+
Boolean,
79+
#[serde(rename = 6)]
80+
User,
81+
#[serde(rename = 7)]
82+
Channel,
83+
#[serde(rename = 8)]
84+
Role,
85+
#[serde(rename = 9)]
86+
Mentionable,
87+
#[serde(rename = 10)]
88+
Number,
89+
#[serde(rename = 11)]
90+
Attachment,
7191
}
7292

7393
#[derive(Debug, Deserialize, Serialize, Setters)]

discord/src/gateway.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -81,16 +81,17 @@ impl GatewayState {
8181
GatewayOpcode::Dispatch => {
8282
// event happened
8383
self.sequence = message.s;
84-
let event: GatewayEvent = serde_json::from_str(&s).unwrap();
84+
let event: std::result::Result<GatewayEvent, _> = serde_json::from_str(&s);
8585
match event {
86-
GatewayEvent::Ready(ready) => {
86+
Ok(GatewayEvent::Ready(ready)) => {
8787
self.ready = Some(ready);
8888
}
89-
event => {
89+
Ok(event) => {
9090
if self.sender.send(event).await.is_err() {
9191
return Err(());
9292
}
9393
}
94+
_ => (),
9495
}
9596
}
9697
GatewayOpcode::Heartbeat => {
@@ -214,7 +215,7 @@ const NAME: &str = env!("CARGO_PKG_NAME");
214215

215216
impl Gateway {
216217
pub async fn connect(client: &Discord) -> request::Result<Self> {
217-
let GatewayResponse { url } = Request::get("/gateway".to_owned()).request(client).await?;
218+
let GatewayResponse { url } = Request::get("/gateway".into()).request(client).await?;
218219
let full_url = url + "/?v=10&encoding=json";
219220

220221
let (mut ws_stream, _) = connect_async(full_url).await.expect("could not connect");
@@ -236,12 +237,12 @@ impl Gateway {
236237
let identify = serde_json::to_string(&GatewayMessage {
237238
op: GatewayOpcode::Identify,
238239
d: Identify {
239-
token: client.token().to_owned(),
240+
token: client.token().into(),
240241
intents: 0,
241242
properties: ConnectionProperties {
242-
os: "linux".to_owned(),
243-
browser: NAME.to_owned(),
244-
device: NAME.to_owned(),
243+
os: "linux".into(),
244+
browser: NAME.into(),
245+
device: NAME.into(),
245246
},
246247
},
247248
s: None,

discord/src/interaction.rs

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,16 @@ pub struct CreateReply {
9494
flags: EnumSet<ReplyFlag>,
9595
}
9696

97+
#[derive(Default, Setters, Serialize)]
98+
#[setters(strip_option)]
99+
pub struct CreateUpdate {
100+
content: Option<String>,
101+
102+
// send these even if empty, so they can also be removed
103+
embeds: Vec<Embed>,
104+
components: Vec<ActionRow>,
105+
}
106+
97107
#[derive(EnumSetType)]
98108
pub enum ReplyFlag {
99109
Ephemeral = 6,
@@ -120,7 +130,7 @@ impl Client for Webhook {
120130
// send request
121131
let http = isahc::Request::builder()
122132
.method(method)
123-
.uri("https://discord.com/api/v10".to_owned() + uri);
133+
.uri(format!("https://discord.com/api/v10{}", uri));
124134

125135
let mut response = if let Some(body) = body {
126136
let request = http
@@ -231,7 +241,7 @@ pub trait InteractionResource: Sized {
231241
pub trait ComponentInteractionResource: InteractionResource<Data = MessageComponent> {
232242
fn update_request(
233243
self,
234-
f: impl FnOnce(CreateReply) -> CreateReply,
244+
f: impl FnOnce(CreateUpdate) -> CreateUpdate,
235245
) -> Request<
236246
(),
237247
Webhook,
@@ -242,7 +252,7 @@ pub trait ComponentInteractionResource: InteractionResource<Data = MessageCompon
242252
let application_id = token.application_id;
243253
let str = token.token.clone();
244254

245-
let reply = f(CreateReply::default());
255+
let reply = f(CreateUpdate::default());
246256
Request::post(
247257
token.uri_response(),
248258
&Response {
@@ -259,7 +269,7 @@ pub trait ComponentInteractionResource: InteractionResource<Data = MessageCompon
259269
async fn update(
260270
self,
261271
client: &Webhook,
262-
f: impl FnOnce(CreateReply) -> CreateReply + Send,
272+
f: impl FnOnce(CreateUpdate) -> CreateUpdate + Send,
263273
) -> Result<InteractionResponseIdentifier> {
264274
self.update_request(f).request(client).await
265275
}
@@ -289,6 +299,7 @@ pub trait ComponentInteractionResource: InteractionResource<Data = MessageCompon
289299
}
290300
}
291301

302+
#[derive(Clone, PartialEq, Eq)]
292303
pub struct InteractionResponseIdentifier {
293304
application_id: Snowflake<Application>,
294305
token: String,
@@ -343,7 +354,7 @@ impl Endpoint for InteractionResponseIdentifier {
343354
.message
344355
.as_ref()
345356
.map(|id| id.as_int().to_string())
346-
.unwrap_or_else(|| "@original".to_owned());
357+
.unwrap_or_else(|| "@original".into());
347358

348359
format!(
349360
"/webhooks/{}/{}/messages/{}",
@@ -392,11 +403,11 @@ impl<'de> Deserialize<'de> for AnyInteraction {
392403

393404
Ok(match typ {
394405
2 => {
395-
data.insert("application_id".to_owned(), app_id.unwrap());
406+
data.insert("application_id".into(), app_id.unwrap());
396407
AnyInteraction::Command(Interaction::deserialize(value).unwrap())
397408
}
398409
3 => {
399-
data.insert("message".to_owned(), message.unwrap().clone());
410+
data.insert("message".into(), message.unwrap().clone());
400411
AnyInteraction::Component(Interaction::deserialize(value).unwrap())
401412
}
402413
_ => panic!("unsupported type {:?}", typ),

discord/src/lib.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,33 @@ pub mod guild;
1212
pub mod interaction;
1313
pub mod message;
1414
pub mod user;
15+
16+
pub struct EscapedChars<T: Iterator<Item = char>>(T, Option<char>);
17+
18+
impl<T: Iterator<Item = char>> EscapedChars<T> {
19+
pub fn new(t: T) -> Self {
20+
Self(t, None)
21+
}
22+
}
23+
24+
impl<T: Iterator<Item = char>> Iterator for EscapedChars<T> {
25+
type Item = char;
26+
27+
fn next(&mut self) -> Option<Self::Item> {
28+
match self.1.take() {
29+
Some(c) => Some(c),
30+
None => match self.0.next() {
31+
c
32+
@ Some('\\' | '_' | '*' | '|' | '~' | '`' | '[' | ']' | '(' | ')' | '<' | '>') => {
33+
self.1 = c;
34+
Some('\\')
35+
}
36+
c => c,
37+
},
38+
}
39+
}
40+
}
41+
42+
pub fn escape_string(s: &str) -> String {
43+
EscapedChars::new(s.chars()).collect()
44+
}

discord/src/message.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use super::{
1414
user::PartialUser,
1515
};
1616

17-
#[derive(Debug, Deserialize, Copy, Clone)]
17+
#[derive(Debug, Deserialize, Copy, Clone, PartialEq, Eq)]
1818
pub struct MessageIdentifier {
1919
channel_id: Snowflake<Channel>,
2020

@@ -85,7 +85,7 @@ pub struct ActionRow {
8585
pub components: Vec<ActionRowComponent>,
8686
}
8787

88-
#[derive(Debug, Serialize_repr, Deserialize_repr)]
88+
#[derive(Debug, Clone, Copy, Serialize_repr, Deserialize_repr)]
8989
#[repr(u8)]
9090
pub enum ButtonStyle {
9191
Primary = 1,

discord/src/request.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -202,9 +202,9 @@ impl Discord {
202202
fn get_bucket(uri: &str) -> String {
203203
if uri.starts_with("/guilds/") || uri.starts_with("/channels/") {
204204
let s: String = uri.split_inclusive('/').take(3).collect();
205-
s.strip_suffix("/").unwrap_or(&s).to_owned()
205+
s.strip_suffix("/").unwrap_or(&s).into()
206206
} else {
207-
uri.to_owned()
207+
uri.into()
208208
}
209209
}
210210
fn bound_to_global_limit(uri: &str) -> bool {
@@ -268,12 +268,12 @@ impl Client for Discord {
268268
// send request
269269
let http = isahc::Request::builder()
270270
.method(method)
271-
.uri("https://discord.com/api/v10".to_owned() + uri)
271+
.uri(format!("https://discord.com/api/v10{}", uri))
272272
.header(
273273
"User-Agent",
274274
format!("DiscordBot ({}, {})", "https://astavie.github.io/", VERSION),
275275
)
276-
.header("Authorization", "Bot ".to_owned() + &self.token);
276+
.header("Authorization", format!("Bot {}", self.token));
277277

278278
let mut response = if let Some(body) = body {
279279
let request = http
@@ -313,8 +313,8 @@ impl Client for Discord {
313313
};
314314

315315
let mut me = self.limits.lock().await;
316-
me.bucket_cache.insert(bucket, bucket_id.to_owned());
317-
me.buckets.insert(bucket_id.to_owned(), limit);
316+
me.bucket_cache.insert(bucket, bucket_id.into());
317+
me.buckets.insert(bucket_id.into(), limit);
318318
}
319319
}
320320
}

0 commit comments

Comments
 (0)