-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic.rs
122 lines (103 loc) · 3.04 KB
/
basic.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
#![allow(missing_docs, dead_code)]
use serenity::all::{
async_trait, Client, Context, CreateInteractionResponse, CreateInteractionResponseMessage,
EventHandler, GatewayIntents, GuildId, Interaction,
};
use serenity_commands::{Command, Commands, SubCommand};
#[derive(Debug, Commands)]
enum AllCommands {
/// Ping the bot.
Ping,
/// Echo a message.
Echo {
/// The message to echo.
message: String,
},
/// Perform math operations.
Math(MathCommand),
}
impl AllCommands {
fn run(self) -> String {
match self {
Self::Ping => "Pong!".to_string(),
Self::Echo { message } => message,
Self::Math(math) => math.run().to_string(),
}
}
}
#[derive(Debug, Command)]
enum MathCommand {
/// Add two numbers.
Add(BinaryOperation),
/// Subtract two numbers.
Subtract(BinaryOperation),
/// Multiply two numbers.
Multiply(BinaryOperation),
/// Divide two numbers.
Divide(BinaryOperation),
/// Negate a number.
Negate {
/// The number to negate.
a: f64,
},
}
impl MathCommand {
fn run(self) -> f64 {
match self {
Self::Add(BinaryOperation { a, b }) => a + b,
Self::Subtract(BinaryOperation { a, b }) => a - b,
Self::Multiply(BinaryOperation { a, b }) => a * b,
Self::Divide(BinaryOperation { a, b }) => a / b,
Self::Negate { a } => -a,
}
}
}
#[derive(Debug, SubCommand)]
struct BinaryOperation {
/// The first number.
a: f64,
/// The second number.
b: f64,
}
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");
}