-
Notifications
You must be signed in to change notification settings - Fork 563
/
mod.rs
693 lines (600 loc) · 25 KB
/
mod.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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! The framework is a customizable method of separating commands, used in
//! combination with [`Client::with_framework`].
//!
//! The framework has a number of configurations, and can have any number of
//! commands bound to it. The primary purpose of it is to offer the utility of
//! not needing to manually match message content strings to determine if a
//! message is a command.
//!
//! Additionally, "checks" can be added to commands, to ensure that a certain
//! condition is met prior to calling a command; this could be a check that the
//! user who posted a message owns the bot, for example.
//!
//! Each command has a given named, and an associated function/closure. For
//! example, you might have two commands: `"ping"` and `"weather"`. These each
//! have an associated function that are called if the framework determines
//! that a message is of that command.
//!
//! Assuming a command prefix of `"~"`, then the following would occur with the
//! two previous commands:
//!
//! ```ignore
//! ~ping // calls the ping command's function
//! ~pin // does not
//! ~ ping // _does_ call it _if_ the `allow_whitespace` option is enabled
//! ~~ping // does not
//! ```
//!
//! # Examples
//!
//! Configuring a Client with a framework, which has a prefix of `"~"` and a
//! ping and about command:
//!
//! ```rust,ignore
//! use serenity::client::{Client, Context};
//! use serenity::model::Message;
//! use std::env;
//!
//! let mut client = Client::login_bot(&env::var("DISCORD_BOT_TOKEN").unwrap());
//!
//! client.with_framework(|f| f
//! .configure(|c| c.prefix("~"))
//! .command("about", |c| c.exec_str("A simple test bot"))
//! .command("ping", |c| c.exec(ping)));
//!
//! command!(about(context) {
//! let _ = context.say("A simple test bot");
//! });
//!
//! command!(ping(context) {
//! let _ = context.say("Pong!");
//! });
//! ```
//!
//! [`Client::with_framework`]: ../../client/struct.Client.html#method.with_framework
pub mod help_commands;
mod command;
mod configuration;
mod create_command;
mod create_group;
mod buckets;
pub use self::buckets::{Bucket, MemberRatelimit, Ratelimit};
pub use self::command::{Command, CommandType, CommandGroup};
pub use self::configuration::{AccountType, Configuration};
pub use self::create_command::CreateCommand;
pub use self::create_group::CreateGroup;
use self::command::{AfterHook, BeforeHook};
use std::collections::HashMap;
use std::default::Default;
use std::sync::Arc;
use std::thread;
use ::client::Context;
use ::model::{Message, UserId};
use ::utils;
#[cfg(feature="cache")]
use ::client::CACHE;
/// A macro to generate "named parameters". This is useful to avoid manually
/// using the "arguments" parameter and manually parsing types.
///
/// This is meant for use with the command [`Framework`].
///
/// # Examples
///
/// Create a regular `ping` command which takes no arguments:
///
/// ```rust,ignore
/// command!(ping(_context, message, _args) {
/// if let Err(why) = message.reply("Pong!") {
/// println!("Error sending pong: {:?}", why);
/// }
/// });
/// ```
///
/// Create a command named `multiply` which accepts 2 floats and multiplies
/// them, sending the product as a reply:
///
/// ```rust,ignore
/// command!(multiply(_context, message, _args, first: f64, second: f64) {
/// let product = first * second;
///
/// if let Err(why) = message.reply(&product.to_string()) {
/// println!("Error sending product: {:?}", why);
/// }
/// });
/// ```
///
/// [`Framework`]: ext/framework/index.html
#[macro_export]
macro_rules! command {
($fname:ident($c:ident) $b:block) => {
pub fn $fname($c: &Context, _: &Message, _: Vec<String>) -> Result<(), String> {
$b
Ok(())
}
};
($fname:ident($c:ident, $m:ident) $b:block) => {
pub fn $fname($c: &Context, $m: &Message, _: Vec<String>) -> Result<(), String> {
$b
Ok(())
}
};
($fname:ident($c:ident, $m:ident, $a:ident) $b:block) => {
pub fn $fname($c: &Context, $m: &Message, $a: Vec<String>) -> Result<(), String> {
$b
Ok(())
}
};
($fname:ident($c:ident, $m:ident, $a:ident, $($name:ident: $t:ty),*) $b:block) => {
pub fn $fname($c: &Context, $m: &Message, $a: Vec<String>) -> Result<(), String> {
let mut i = $a.iter();
let mut arg_counter = 0;
$(
arg_counter += 1;
let $name = match i.next() {
Some(v) => match v.parse::<$t>() {
Ok(v) => v,
Err(_) => return Err(format!("Failed to parse argument #{} of type {:?}",
arg_counter,
stringify!($t))),
},
None => return Err(format!("Failed to parse argument #{} of type {:?}",
arg_counter,
stringify!($t))),
};
)*
drop(i);
$b
Ok(())
}
};
}
/// A utility for easily managing dispatches to commands.
///
/// Refer to the [module-level documentation] for more information.
///
/// [module-level documentation]: index.html
#[allow(type_complexity)]
#[derive(Default)]
pub struct Framework {
configuration: Configuration,
groups: HashMap<String, Arc<CommandGroup>>,
before: Option<Arc<BeforeHook>>,
buckets: HashMap<String, Bucket>,
after: Option<Arc<AfterHook>>,
/// Whether the framework has been "initialized".
///
/// The framework is initialized once one of the following occurs:
///
/// - configuration has been set;
/// - a command handler has been set;
/// - a command check has been set.
///
/// This is used internally to determine whether or not - in addition to
/// dispatching to the [`Client::on_message`] handler - to have the
/// framework check if a [`Event::MessageCreate`] should be processed by
/// itself.
///
/// [`Client::on_message`]: ../../client/struct.Client.html#method.on_message
/// [`Event::MessageCreate`]: ../../model/event/enum.Event.html#variant.MessageCreate
pub initialized: bool,
user_info: (u64, bool),
}
impl Framework {
/// Configures the framework, setting non-default values. All fields are
/// optional. Refer to [`Configuration::default`] for more information on
/// the default values.
///
/// # Examples
///
/// Configuring the framework for a [`Client`], setting the [`depth`] to 3,
/// [allowing whitespace], and setting the [`prefix`] to `"~"`:
///
/// ```rust,no_run
/// use serenity::Client;
/// use std::env;
///
/// let mut client = Client::login_bot(&env::var("DISCORD_TOKEN").unwrap());
/// client.with_framework(|f| f
/// .configure(|c| c
/// .depth(3)
/// .allow_whitespace(true)
/// .prefix("~")));
/// ```
///
/// [`Client`]: ../../client/struct.Client.html
/// [`Configuration::default`]: struct.Configuration.html#method.default
/// [`depth`]: struct.Configuration.html#method.depth
/// [`prefix`]: struct.Configuration.html#method.prefix
/// [allowing whitespace]: struct.Configuration.html#method.allow_whitespace
pub fn configure<F>(mut self, f: F) -> Self
where F: FnOnce(Configuration) -> Configuration {
self.configuration = f(self.configuration);
self
}
/// Defines a bucket with `delay` between each command, and the `limit` of uses
/// per `time_span`.
pub fn bucket<S>(mut self, s: S, delay: i64, time_span: i64, limit: i32) -> Self
where S: Into<String> {
self.buckets.insert(s.into(), Bucket {
ratelimit: Ratelimit {
delay: delay,
limit: Some((time_span, limit)),
},
users: HashMap::new(),
});
self
}
/// Defines a bucket just with `delay` between each command.
pub fn simple_bucket<S>(mut self, s: S, delay: i64) -> Self
where S: Into<String> {
self.buckets.insert(s.into(), Bucket {
ratelimit: Ratelimit {
delay: delay,
limit: None,
},
users: HashMap::new(),
});
self
}
#[allow(cyclomatic_complexity)]
#[doc(hidden)]
pub fn dispatch(&mut self, context: Context, message: Message) {
match self.configuration.account_type {
AccountType::Selfbot => {
if message.author.id != self.user_info.0 {
return;
}
},
AccountType::Bot => if message.author.bot {
return;
},
AccountType::Automatic => {
if self.user_info.1 {
if message.author.bot {
return;
}
} else if message.author.id != self.user_info.0 {
return;
}
},
AccountType::Any => {}
}
let res = command::positions(&context, &message.content, &self.configuration);
let positions = match res {
Some(positions) => positions,
None => return,
};
// Ensure that the message length is at least longer than a prefix
// length. There's no point in checking further ahead if there's nothing
// _to_ check.
if positions.iter().all(|p| message.content.len() <= *p) {
return;
}
'outer: for position in positions {
let mut built = String::new();
for i in 0..self.configuration.depth {
if i != 0 {
built.push(' ');
}
built.push_str(match {
message.content
.split_at(position)
.1
.trim()
.split_whitespace()
.collect::<Vec<&str>>()
.get(i)
} {
Some(piece) => piece,
None => continue,
});
let groups = self.groups.clone();
for group in groups.values() {
let to_check = if let Some(ref prefix) = group.prefix {
if built.starts_with(prefix) && built.len() > prefix.len() + 1 {
built[(prefix.len() + 1)..].to_owned()
} else {
continue;
}
} else {
built.clone()
};
if let Some(command) = group.commands.get(&to_check) {
let is_owner = self.configuration.owners.contains(&message.author.id);
// Most of the checks don't apply to owners.
if !is_owner {
if command.owners_only {
if let Some(ref message) = self.configuration.invalid_permission_message {
let _ = context.say(message);
}
return;
}
if !self.configuration.allow_dm {
if let Some(ref message) = self.configuration.no_dm_message {
let _ = context.say(message);
}
return;
}
if self.configuration.blocked_users.contains(&message.author.id) {
if let Some(ref message) = self.configuration.blocked_user_message {
let _ = context.say(message);
}
return;
}
if self.configuration.disabled_commands.contains(&to_check) ||
self.configuration.disabled_commands.contains(&built) {
if let Some(ref message) = self.configuration.command_disabled_message {
let msg = message.replace("%command%", &to_check);
let _ = context.say(&msg);
}
return;
}
if let Some(ref bucket_name) = command.bucket {
let rate_limit = self.ratelimit_time(bucket_name, message.author.id.0);
if rate_limit > 0 {
if let Some(ref message) = self.configuration.rate_limit_message {
let msg = message.replace("%time%", &rate_limit.to_string());
let _ = context.say(&msg);
}
return;
}
}
#[cfg(feature="cache")]
{
if let Some(guild_id) = message.guild_id() {
if self.configuration.blocked_guilds.contains(&guild_id) {
if let Some(ref message) = self.configuration.blocked_guild_message {
let _ = context.say(message);
}
return;
}
}
if let Some(guild_id) = message.guild_id() {
if let Some(guild) = guild_id.find() {
if self.configuration.blocked_users.contains(&guild.owner_id) {
if let Some(ref message) = self.configuration.blocked_guild_message {
let _ = context.say(message);
}
return;
}
}
}
if message.is_private() {
if command.guild_only {
if let Some(ref message) = self.configuration.no_guild_message {
let _ = context.say(message);
}
return;
}
} else if command.dm_only {
if let Some(ref message) = self.configuration.no_dm_message {
let _ = context.say(message);
}
return;
}
}
for check in &command.checks {
if !(check)(&context, &message) {
if let Some(ref message) = self.configuration.invalid_check_message {
let _ = context.say(message);
}
continue 'outer;
}
}
}
let before = self.before.clone();
let command = command.clone();
let after = self.after.clone();
let groups = self.groups.clone();
let args = if command.use_quotes {
utils::parse_quotes(&message.content[position + built.len()..])
} else {
message.content[position + built.len()..]
.split_whitespace()
.map(|arg| arg.to_owned())
.collect::<Vec<String>>()
};
if let Some(x) = command.min_args {
if args.len() < x as usize {
if let Some(ref message) = self.configuration.not_enough_args_message {
let msg = message.replace("%min%", &x.to_string())
.replace("%given%", &args.len().to_string());
let _ = context.say(&msg);
}
return;
}
}
if let Some(x) = command.max_args {
if args.len() > x as usize {
if let Some(ref message) = self.configuration.too_many_args_message {
let msg = message.replace("%max%", &x.to_string())
.replace("%given%", &args.len().to_string());
let _ = context.say(&msg);
}
return;
}
}
#[cfg(feature="cache")]
{
if !is_owner && !command.required_permissions.is_empty() {
let mut permissions_fulfilled = false;
if let Some(member) = message.get_member() {
let cache = CACHE.read().unwrap();
if let Ok(guild_id) = member.find_guild() {
if let Some(guild) = cache.get_guild(guild_id) {
let perms = guild.permissions_for(message.channel_id, message.author.id);
permissions_fulfilled = perms.contains(command.required_permissions);
}
}
}
if !permissions_fulfilled {
if let Some(ref message) = self.configuration.invalid_permission_message {
let _ = context.say(message);
}
return;
}
}
}
thread::spawn(move || {
if let Some(before) = before {
if !is_owner && !(before)(&context, &message, &built) {
return;
}
}
let result = match command.exec {
CommandType::StringResponse(ref x) => {
let _ = &context.say(x);
Ok(())
},
CommandType::Basic(ref x) => {
(x)(&context, &message, args)
},
CommandType::WithCommands(ref x) => {
(x)(&context, &message, groups, args)
}
};
if let Some(after) = after {
(after)(&context, &message, &built, result);
}
});
return;
}
}
}
}
}
/// Adds a function to be associated with a command, which will be called
/// when a command is used in a message.
///
/// This requires that a check - if one exists - passes, prior to being
/// called.
///
/// Note that once v0.2.0 lands, you will need to use the command builder
/// via the [`command`] method to set checks. This command will otherwise
/// only be for simple commands.
///
/// Refer to the [module-level documentation] for more information and
/// usage.
///
/// [`command`]: #method.command
/// [module-level documentation]: index.html
pub fn on<F, S>(mut self, command_name: S, f: F) -> Self
where F: Fn(&Context, &Message, Vec<String>) -> Result<(), String> + Send + Sync + 'static,
S: Into<String> {
{
let ungrouped = self.groups.entry("Ungrouped".to_owned())
.or_insert_with(|| Arc::new(CommandGroup::default()));
if let Some(ref mut group) = Arc::get_mut(ungrouped) {
let name = command_name.into();
group.commands.insert(name, Arc::new(Command::new(f)));
}
}
self.initialized = true;
self
}
/// Adds a command using command builder.
///
/// # Examples
///
/// ```rust,ignore
/// framework.command("ping", |c| c
/// .description("Responds with 'pong'.")
/// .exec(|ctx, _, _| {
/// let _ = ctx.say("pong");
/// }));
/// ```
pub fn command<F, S>(mut self, command_name: S, f: F) -> Self
where F: FnOnce(CreateCommand) -> CreateCommand,
S: Into<String> {
{
let ungrouped = self.groups.entry("Ungrouped".to_owned())
.or_insert_with(|| Arc::new(CommandGroup::default()));
if let Some(ref mut group) = Arc::get_mut(ungrouped) {
let cmd = f(CreateCommand(Command::default())).0;
let name = command_name.into();
group.commands.insert(name, Arc::new(cmd));
}
}
self.initialized = true;
self
}
pub fn group<F, S>(mut self, group_name: S, f: F) -> Self
where F: FnOnce(CreateGroup) -> CreateGroup,
S: Into<String> {
let group = f(CreateGroup(CommandGroup::default())).0;
self.groups.insert(group_name.into(), Arc::new(group));
self.initialized = true;
self
}
/// Specify the function to be called prior to every command's execution.
/// If that function returns true, the command will be executed.
pub fn before<F>(mut self, f: F) -> Self
where F: Fn(&Context, &Message, &String) -> bool + Send + Sync + 'static {
self.before = Some(Arc::new(f));
self
}
/// Specify the function to be called after every command's execution.
/// Fourth argument exists if command returned an error which you can handle.
pub fn after<F>(mut self, f: F) -> Self
where F: Fn(&Context, &Message, &String, Result<(), String>) + Send + Sync + 'static {
self.after = Some(Arc::new(f));
self
}
/// Adds a "check" to a command, which checks whether or not the command's
/// associated function should be called.
///
/// # Examples
///
/// Ensure that the user who created a message, calling a "ping" command,
/// is the owner.
///
/// ```rust,ignore
/// use serenity::client::{Client, Context};
/// use serenity::model::Message;
/// use std::env;
///
/// let mut client = Client::login_bot(&env::var("DISCORD_TOKEN").unwrap());
///
/// client.with_framework(|f| f
/// .configure(|c| c.prefix("~"))
/// .on("ping", ping)
/// .set_check("ping", owner_check));
///
/// command!(ping(context) {
/// let _ = context.say("Pong!");
/// });
///
/// fn owner_check(_context: &Context, message: &Message) -> bool {
/// // replace with your user ID
/// message.author.id == 7
/// }
/// ```
#[deprecated(since="0.1.2", note="Use the `CreateCommand` builder's `check` instead.")]
pub fn set_check<F, S>(mut self, command: S, check: F) -> Self
where F: Fn(&Context, &Message) -> bool + Send + Sync + 'static,
S: Into<String> {
{
let ungrouped = self.groups.entry("Ungrouped".to_owned())
.or_insert_with(|| Arc::new(CommandGroup::default()));
if let Some(group) = Arc::get_mut(ungrouped) {
let name = command.into();
if let Some(ref mut command) = group.commands.get_mut(&name) {
if let Some(command) = Arc::get_mut(command) {
command.checks.push(Box::new(check));
}
}
}
}
self
}
#[doc(hidden)]
pub fn update_current_user(&mut self, user_id: UserId, is_bot: bool) {
self.user_info = (user_id.0, is_bot);
}
fn ratelimit_time(&mut self, bucket_name: &str, user_id: u64) -> i64 {
self.buckets
.get_mut(bucket_name)
.map(|bucket| bucket.take(user_id))
.unwrap_or(0)
}
}