-
Notifications
You must be signed in to change notification settings - Fork 0
/
generic.rs
159 lines (135 loc) · 4.17 KB
/
generic.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#![allow(missing_docs, dead_code)]
use std::{
fmt::{self, Display},
ops::Add,
};
use serenity::all::{
async_trait, Client, Context, CreateInteractionResponse, CreateInteractionResponseMessage,
EventHandler, GatewayIntents, GuildId, Interaction,
};
use serenity_commands::{BasicOption, Command, Commands};
#[derive(Debug, Commands)]
#[allow(clippy::enum_variant_names)]
enum AllCommands {
/// Add two integers together.
AddInts(AddCommand<u64>),
/// Add two floats together.
AddFloats(AddCommand<f64>),
/// Add two vectors together.
AddVec2s(AddCommand<Vec2>),
}
impl AllCommands {
fn run(self) -> String {
match self {
Self::AddInts(add) => add.run().to_string(),
Self::AddFloats(add) => add.run().to_string(),
Self::AddVec2s(add) => add.run().to_string(),
}
}
}
#[derive(Debug, Command)]
struct AddCommand<T: BasicOption + Add> {
/// The first thing.
a: T,
/// The second thing.
b: T,
}
impl<T: BasicOption + Add> AddCommand<T> {
fn run(self) -> T::Output {
self.a + self.b
}
}
#[derive(Debug)]
struct Vec2 {
x: f64,
y: f64,
}
impl BasicOption for Vec2 {
fn create_option(
name: impl Into<String>,
description: impl Into<String>,
) -> serenity::all::CreateCommandOption {
serenity::all::CreateCommandOption::new(
serenity::all::CommandOptionType::String,
name,
description,
)
.required(true)
}
fn from_value(
value: Option<&serenity::all::CommandDataOptionValue>,
) -> serenity_commands::Result<Self> {
let value = value.ok_or(serenity_commands::Error::MissingRequiredCommandOption)?;
let serenity::all::CommandDataOptionValue::String(choice) = value else {
return Err(serenity_commands::Error::IncorrectCommandOptionType {
got: value.kind(),
expected: serenity::all::CommandOptionType::String,
});
};
let (x, y) = choice
.split_once(',')
.ok_or_else(|| serenity_commands::Error::Custom("expected comma".into()))?;
Ok(Self {
x: x.parse()
.map_err(|_| serenity_commands::Error::Custom("expected float".into()))?,
y: y.parse()
.map_err(|_| serenity_commands::Error::Custom("expected float".into()))?,
})
}
}
impl Add for Vec2 {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self {
x: self.x + rhs.x,
y: self.y + rhs.y,
}
}
}
impl Display for Vec2 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}, {}", self.x, self.y)
}
}
struct Handler {
guild_id: GuildId,
}
#[async_trait]
impl EventHandler for Handler {
async fn ready(&self, ctx: Context, _: serenity::all::Ready) {
self.guild_id
.set_commands(&ctx, AllCommands::create_commands())
.await
.unwrap();
}
async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
if let Interaction::Command(command) = interaction {
let command_data = AllCommands::from_command_data(&command.data).unwrap();
command
.create_response(
ctx,
CreateInteractionResponse::Message(
CreateInteractionResponseMessage::new().content(command_data.run()),
),
)
.await
.unwrap();
}
}
}
#[tokio::main]
pub async fn main() {
let token = std::env::var("DISCORD_TOKEN").expect("expected `DISCORD_TOKEN` to be set");
let guild_id = std::env::var("DISCORD_GUILD_ID")
.expect("expected `DISCORD_GUILD_ID` to be set")
.parse()
.expect("expected `DISCORD_GUILD_ID` to be a valid guild ID");
let mut client = Client::builder(token, GatewayIntents::non_privileged())
.event_handler(Handler { guild_id })
.await
.expect("client should be created successfully");
client
.start()
.await
.expect("client should start successfully");
}