-
Notifications
You must be signed in to change notification settings - Fork 562
/
help_commands.rs
1342 lines (1178 loc) · 38.8 KB
/
help_commands.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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A collection of default help commands for the framework.
//!
//! # Example
//!
//! Using the [`with_embeds`] function to have the framework's help message use
//! embeds:
//!
//! ```rs,no_run
//! use serenity::framework::standard::help_commands;
//! use serenity::Client;
//! use std::env;
//!
//! let mut client = Client::new(&env::var("DISCORD_TOKEN").unwrap());
//! use serenity::framework::StandardFramework;
//!
//! client.with_framework(StandardFramework::new()
//! .command("help", |c| c.exec_help(help_commands::with_embeds)));
//! ```
//!
//! The same can be accomplished with no embeds by substituting `with_embeds`
//! with the [`plain`] function.
//!
//! [`plain`]: fn.plain.html
//! [`with_embeds`]: fn.with_embeds.html
#[cfg(all(feature = "cache", feature = "http"))]
use super::{
Args, CommandGroup, CommandOptions,
CommandResult, has_correct_roles, HelpBehaviour, HelpOptions,
has_correct_permissions, OnlyIn,
structures::Command as InternalCommand,
};
#[cfg(all(feature = "cache", feature = "http"))]
use crate::{
cache::CacheRwLock,
client::Context,
framework::standard::CommonOptions,
model::channel::Message,
Error,
http::Http,
model::id::{ChannelId, UserId},
utils::Colour,
};
#[cfg(all(feature = "cache", feature = "http"))]
use std::{
borrow::Borrow,
collections::HashSet,
fmt::Write,
hash::BuildHasher,
ops::{Index, IndexMut},
};
#[cfg(all(feature = "cache", feature = "http"))]
use log::warn;
/// Macro to format a command according to a `HelpBehaviour` or
/// continue to the next command-name upon hiding.
#[cfg(all(feature = "cache", feature = "http"))]
macro_rules! format_command_name {
($behaviour:expr, $command_name:expr) => {
match $behaviour {
HelpBehaviour::Strike => format!("~~`{}`~~", $command_name),
HelpBehaviour::Nothing => format!("`{}`", $command_name),
HelpBehaviour::Hide => continue,
HelpBehaviour::__Nonexhaustive => unreachable!(),
}
};
}
/// Wraps around `warn`-macro in order to keep
/// the literal same for all formats of help.
#[cfg(all(feature = "cache", feature = "http"))]
macro_rules! warn_about_failed_send {
($customised_help:expr, $error:expr) => {
warn!("Failed to send {:?} because: {:?}", $customised_help, $error);
}
}
/// A single group containing its name and all related commands that are eligible
/// in relation of help-settings measured to the user.
#[derive(Clone, Debug, Default)]
pub struct GroupCommandsPair {
name: &'static str,
prefixes: Vec<&'static str>,
command_names: Vec<String>,
sub_groups: Vec<GroupCommandsPair>,
}
/// A single suggested command containing its name and Levenshtein distance
/// to the actual user's searched command name.
#[derive(Clone, Debug, Default)]
struct SuggestedCommandName {
name: String,
levenshtein_distance: usize,
}
/// A single command containing all related pieces of information.
#[derive(Clone, Debug)]
pub struct Command<'a> {
name: &'static str,
group_name: &'static str,
group_prefixes: &'a [&'static str],
aliases: Vec<&'static str>,
availability: &'a str,
description: Option<&'static str>,
usage: Option<&'static str>,
usage_sample: Option<&'static str>,
checks: Vec<String>,
}
/// Contains possible suggestions in case a command could not be found
/// but are similar enough.
#[derive(Clone, Debug, Default)]
pub struct Suggestions(Vec<SuggestedCommandName>);
#[cfg(all(feature = "cache", feature = "http"))]
impl Suggestions {
/// Immutably borrow inner `Vec`.
#[inline]
fn as_vec(&self) -> &Vec<SuggestedCommandName> {
&self.0
}
/// Concats names of suggestions with a given `separator`.
fn join(&self, separator: &str) -> String {
let mut iter = self.as_vec().iter();
let first_iter_element = match iter.next() {
Some(first_iter_element) => first_iter_element,
None => return String::new(),
};
let size = self
.as_vec()
.iter()
.fold(0, |total_size, size| total_size + size.name.len());
let byte_len_of_sep = self.as_vec().len().checked_sub(1).unwrap_or(0) * separator.len();
let mut result = String::with_capacity(size + byte_len_of_sep);
result.push_str(first_iter_element.name.borrow());
for element in iter {
result.push_str(&*separator);
result.push_str(element.name.borrow());
}
result
}
}
/// Covers possible outcomes of a help-request and
/// yields relevant data in customised textual
/// representation.
#[derive(Clone, Debug)]
pub enum CustomisedHelpData<'a> {
/// To display suggested commands.
SuggestedCommands {
help_description: String,
suggestions: Suggestions,
},
/// To display groups and their commands by name.
GroupedCommands {
help_description: String,
groups: Vec<GroupCommandsPair>,
},
/// To display one specific command.
SingleCommand { command: Command<'a> },
/// To display failure in finding a fitting command.
NoCommandFound { help_error_message: &'a str },
#[doc(hidden)]
__Nonexhaustive,
}
/// Wraps around a `Vec<Vec<T>>` and provides access
/// via indexing of tuples representing x and y.
#[derive(Debug)]
#[cfg(all(feature = "cache", feature = "http"))]
struct Matrix {
vec: Vec<usize>,
width: usize,
}
#[cfg(all(feature = "cache", feature = "http"))]
impl Matrix {
fn new(columns: usize, rows: usize) -> Matrix {
Matrix {
vec: vec![0; columns * rows],
width: rows,
}
}
}
#[cfg(all(feature = "cache", feature = "http"))]
impl Index<(usize, usize)> for Matrix {
type Output = usize;
fn index(&self, matrix_entry: (usize, usize)) -> &usize {
&self.vec[matrix_entry.1 * self.width + matrix_entry.0]
}
}
#[cfg(all(feature = "cache", feature = "http"))]
impl IndexMut<(usize, usize)> for Matrix {
fn index_mut(&mut self, matrix_entry: (usize, usize)) -> &mut usize {
&mut self.vec[matrix_entry.1 * self.width + matrix_entry.0]
}
}
/// Calculates and returns levenshtein distance between
/// two passed words.
#[cfg(all(feature = "cache", feature = "http"))]
pub(crate) fn levenshtein_distance(word_a: &str, word_b: &str) -> usize {
let len_a = word_a.chars().count();
let len_b = word_b.chars().count();
if len_a == 0 {
return len_b;
} else if len_b == 0 {
return len_a;
}
let mut matrix = Matrix::new(len_b + 1, len_a + 1);
for x in 0..len_a {
matrix[(x + 1, 0)] = matrix[(x, 0)] + 1;
}
for y in 0..len_b {
matrix[(0, y + 1)] = matrix[(0, y)] + 1;
}
for (x, char_a) in word_a.chars().enumerate() {
for (y, char_b) in word_b.chars().enumerate() {
matrix[(x + 1, y + 1)] = (matrix[(x, y + 1)] + 1)
.min(matrix[(x + 1, y)] + 1)
.min(matrix[(x, y)] + if char_a == char_b { 0 } else { 1 });
}
}
matrix[(len_a, len_b)]
}
/// Checks whether a user is member of required roles
/// and given the required permissions.
#[cfg(feature = "cache")]
pub fn has_all_requirements(
cache: impl AsRef<CacheRwLock>,
cmd: &CommandOptions,
msg: &Message,
) -> bool {
if let Some(guild) = msg.guild(&cache) {
let guild = guild.read();
if let Some(member) = guild.members.get(&msg.author.id) {
if let Ok(permissions) = member.permissions(&cache) {
return if cmd.allowed_roles.is_empty() {
permissions.administrator() || has_correct_permissions(&cache, &cmd, msg)
} else {
permissions.administrator()
|| (has_correct_roles(&cmd, &guild, member)
&& has_correct_permissions(&cache, &cmd, msg))
};
}
}
}
cmd.only_in != OnlyIn::Guild
}
/// Checks if `search_on` starts with `word` and is then cleanly followed by a
/// `" "`.
#[inline]
#[cfg(all(feature = "cache", feature = "http"))]
fn starts_with_whole_word(search_on: &str, word: &str) -> bool {
search_on.starts_with(word) && search_on.get(word.len()..word.len() + 1)
.map_or(false, |slice| slice == " ")
}
#[inline]
#[cfg(all(feature = "cache", feature = "http"))]
fn find_any_command_matches(
command: &'static InternalCommand,
group: &CommandGroup,
name: &mut String,
) -> Option<&'static str> {
command
.options
.names
.iter()
.find(|n| {
group
.options
.prefixes
.iter()
.any(|prefix|
if starts_with_whole_word(&name, &prefix) {
name.drain(..prefix.len() + 1);
n == &name
} else {
false
}
)
}).cloned()
}
#[cfg(all(feature = "cache", feature = "http"))]
fn check_command_behaviour(
msg: &Message,
options: &impl CommonOptions,
owners: &HashSet<UserId, impl BuildHasher>,
help_options: &HelpOptions,
cache: &CacheRwLock,
) -> HelpBehaviour {
if !&options.help_available() {
return HelpBehaviour::Hide;
}
if options.only_in() == OnlyIn::None
|| options.only_in() == OnlyIn::Dm && msg.is_private()
|| options.only_in() == OnlyIn::Guild && !msg.is_private()
{
if options.owners_only() && !owners.contains(&msg.author.id) {
return help_options.lacking_ownership.clone();
}
if has_correct_permissions(&cache, options, msg) {
if let Some(guild) = msg.guild(&cache) {
let guild = guild.read();
if let Some(member) = guild.members.get(&msg.author.id) {
if has_correct_roles(options, &guild, &member) {
return HelpBehaviour::Nothing;
} else {
return help_options.lacking_role.clone();
}
}
} else {
return HelpBehaviour::Nothing;
}
} else {
return help_options.lacking_permissions.clone();
}
} else {
return help_options.wrong_channel.clone();
}
HelpBehaviour::Nothing
}
#[cfg(all(feature = "cache", feature = "http"))]
fn nested_group_command_search<'a>(
cache: &CacheRwLock,
groups: &[&'static CommandGroup],
name: &mut String,
help_options: &'a HelpOptions,
msg: &Message,
similar_commands: &mut Vec<SuggestedCommandName>,
owners: &HashSet<UserId, impl BuildHasher>,
) -> Result<CustomisedHelpData<'a>, ()> {
for group in groups {
let group = *group;
let mut found: Option<&'static InternalCommand> = None;
let group_behaviour = check_command_behaviour(
&msg,
&group.options,
&owners,
&help_options,
&cache,
);
match &group_behaviour {
HelpBehaviour::Nothing => (),
_ => {
continue;
}
}
for command in group.commands {
let command = *command;
let search_command_name_matched = if group.options.prefixes.is_empty() {
command
.options
.names
.iter()
.find(|n| **n == name)
.cloned()
} else {
find_any_command_matches(&command, &group, name)
};
if let Some(n) = search_command_name_matched {
if n == command.options.names[0] {
if HelpBehaviour::Nothing == check_command_behaviour(
&msg,
&command.options,
&owners,
&help_options,
&cache,
) {
found = Some(command);
} else {
break;
}
} else {
// Alias.
return Ok(CustomisedHelpData::SuggestedCommands {
help_description: help_options.suggestion_text.replace("{}", name),
suggestions: Suggestions::default(),
});
}
} else if help_options.max_levenshtein_distance > 0 {
let command_name = if let Some(first_prefix) = group.options.prefixes.get(0) {
format!("{} {}", &first_prefix, &command.options.names[0])
} else {
command.options.names[0].to_string()
};
let levenshtein_distance = levenshtein_distance(&command_name, &name);
if levenshtein_distance <= help_options.max_levenshtein_distance
&& HelpBehaviour::Nothing == check_command_behaviour(
&msg,
&command.options,
&owners,
&help_options,
&cache,
)
{
similar_commands.push(SuggestedCommandName {
name: command_name,
levenshtein_distance,
});
}
}
}
if let Some(command) = found {
let options = &command.options;
if !options.help_available {
return Ok(CustomisedHelpData::NoCommandFound {
help_error_message: &help_options.no_help_available_text,
});
}
let available_text = if options.only_in == OnlyIn::Dm {
&help_options.dm_only_text
} else if options.only_in == OnlyIn::Guild {
&help_options.guild_only_text
} else {
&help_options.dm_and_guild_text
};
similar_commands
.sort_unstable_by(|a, b| a.levenshtein_distance.cmp(&b.levenshtein_distance));
let check_names: Vec<String> = command
.options
.checks
.iter()
.chain(group.options.checks.iter())
.filter_map(|check| {
if check.display_in_help {
Some(check.name.to_string())
} else {
None
}
})
.collect();
return Ok(CustomisedHelpData::SingleCommand {
command: Command {
name: options.names[0],
description: options.desc,
group_name: group.name,
group_prefixes: &group.options.prefixes,
checks: check_names,
aliases: options.names[1..].to_vec(),
availability: available_text,
usage: options.usage,
usage_sample: options.example,
},
});
}
match nested_group_command_search(
cache,
&group.sub_groups,
name,
help_options,
msg,
similar_commands,
owners,
) {
Ok(found) => return Ok(found),
Err(()) => (),
}
}
Err(())
}
/// Tries to extract a single command matching searched command name otherwise
/// returns similar commands.
#[cfg(feature = "cache")]
fn fetch_single_command<'a>(
cache: impl AsRef<CacheRwLock>,
groups: &[&'static CommandGroup],
name: &str,
help_options: &'a HelpOptions,
msg: &Message,
owners: &HashSet<UserId, impl BuildHasher>,
) -> Result<CustomisedHelpData<'a>, Vec<SuggestedCommandName>> {
let mut similar_commands: Vec<SuggestedCommandName> = Vec::new();
let cache = cache.as_ref();
let mut name = name.to_string();
match nested_group_command_search(
&cache,
&groups,
&mut name,
&help_options,
&msg,
&mut similar_commands,
&owners,
) {
Ok(found) => Ok(found),
Err(()) => Err(similar_commands),
}
}
#[cfg(feature = "cache")]
fn fill_eligible_commands<'a>(
context: &Context,
commands: &[&'static InternalCommand],
owners: &HashSet<UserId, impl BuildHasher>,
help_options: &'a HelpOptions,
group: &'a CommandGroup,
msg: &Message,
to_fill: &mut GroupCommandsPair,
highest_formatter: &mut HelpBehaviour,
) {
to_fill.name = group.name;
to_fill.prefixes = group.options.prefixes.to_vec();
let group_behaviour = {
if let HelpBehaviour::Hide = highest_formatter {
HelpBehaviour::Hide
} else {
std::cmp::max(
*highest_formatter,
check_command_behaviour(
msg,
&group.options,
owners,
help_options,
&context.cache,
)
)
}
};
*highest_formatter = group_behaviour;
for command in commands {
let command = *command;
let options = &command.options;
let name = &options.names[0];
match &group_behaviour {
HelpBehaviour::Nothing => (),
_ => {
let name = format_command_name!(&group_behaviour, &name);
to_fill.command_names.push(name);
continue;
}
}
let command_behaviour = check_command_behaviour(
msg,
&command.options,
owners,
help_options,
&context.cache,
);
let name = format_command_name!(command_behaviour, &name);
to_fill.command_names.push(name);
}
}
/// Tries to extract a single command matching searched command name.
#[cfg(feature = "cache")]
fn fetch_all_eligible_commands_in_group<'a>(
context: &Context,
commands: &[&'static InternalCommand],
owners: &HashSet<UserId, impl BuildHasher>,
help_options: &'a HelpOptions,
group: &'a CommandGroup,
msg: &Message,
highest_formatter: HelpBehaviour,
) -> GroupCommandsPair {
let mut group_with_cmds = GroupCommandsPair::default();
let mut highest_formatter = highest_formatter;
fill_eligible_commands(
&context,
&commands,
&owners,
&help_options,
&group,
&msg,
&mut group_with_cmds,
&mut highest_formatter,
);
for sub_group in group.sub_groups {
let grouped_cmd = fetch_all_eligible_commands_in_group(
&context,
&sub_group.commands,
&owners,
&help_options,
&sub_group,
&msg,
highest_formatter,
);
group_with_cmds.sub_groups.push(grouped_cmd);
}
group_with_cmds
}
/// Fetch groups with their commands.
#[cfg(feature = "cache")]
fn create_command_group_commands_pair_from_groups<'a>(
context: &Context,
groups: &[&'static CommandGroup],
owners: &HashSet<UserId, impl BuildHasher>,
msg: &Message,
help_options: &'a HelpOptions,
) -> Vec<GroupCommandsPair> {
let mut listed_groups: Vec<GroupCommandsPair> = Vec::default();
for group in groups {
let group = *group;
let group_with_cmds = create_single_group(&context, group, &owners, &msg, &help_options);
if !group_with_cmds.command_names.is_empty() {
listed_groups.push(group_with_cmds);
}
}
listed_groups
}
/// Fetches a single group with its commands.
#[cfg(feature = "cache")]
fn create_single_group(
context: &Context,
group: &CommandGroup,
owners: &HashSet<UserId, impl BuildHasher>,
msg: &Message,
help_options: &HelpOptions,
) -> GroupCommandsPair {
let mut group_with_cmds = fetch_all_eligible_commands_in_group(
&context,
&group.commands,
&owners,
&help_options,
&group,
&msg,
HelpBehaviour::Nothing,
);
group_with_cmds.name = group.name;
group_with_cmds
}
/// Iterates over all commands and forges them into a `CustomisedHelpData`.
/// taking `HelpOptions` into consideration when deciding on whether a command
/// shall be picked and in what textual format.
#[cfg(feature = "cache")]
pub fn create_customised_help_data<'a>(
context: &Context,
groups: &[&'static CommandGroup],
owners: &HashSet<UserId, impl BuildHasher>,
args: &'a Args,
help_options: &'a HelpOptions,
msg: &Message,
) -> CustomisedHelpData<'a> {
let cache = &context.cache;
if !args.is_empty() {
let name = args.message();
return match fetch_single_command(&cache, &groups, &name, &help_options, &msg, owners) {
Ok(single_command) => single_command,
Err(suggestions) => {
let searched_named_lowercase = name.to_lowercase();
for group in groups {
if group.name.to_lowercase() == searched_named_lowercase
|| group
.options
.prefixes
.iter()
.any(|prefix| *prefix == searched_named_lowercase)
{
let single_group =
create_single_group(&context, &group, &owners, &msg, &help_options);
if !single_group.command_names.is_empty() {
return CustomisedHelpData::GroupedCommands {
help_description: group
.options
.description
.as_ref()
.map(|s| s.to_string())
.unwrap_or_default(),
groups: vec![single_group],
};
}
}
}
if suggestions.is_empty() {
CustomisedHelpData::NoCommandFound {
help_error_message: &help_options.no_help_available_text,
}
} else {
CustomisedHelpData::SuggestedCommands {
help_description: help_options.suggestion_text.to_string(),
suggestions: Suggestions(suggestions),
}
}
}
};
}
let strikethrough_command_tip = if msg.is_private() {
&help_options.strikethrough_commands_tip_in_guild
} else {
&help_options.strikethrough_commands_tip_in_dm
};
let description = if let Some(ref strikethrough_command_text) = strikethrough_command_tip {
format!(
"{}\n{}",
&help_options.individual_command_tip, &strikethrough_command_text
)
} else {
help_options.individual_command_tip.to_string()
};
let listed_groups = create_command_group_commands_pair_from_groups(
&context,
&groups,
&owners,
&msg,
&help_options,
);
if listed_groups.is_empty() {
CustomisedHelpData::NoCommandFound {
help_error_message: &help_options.no_help_available_text,
}
} else {
CustomisedHelpData::GroupedCommands {
help_description: description,
groups: listed_groups,
}
}
}
/// Flattens a group with all its nested sub-groups into the passed `group_text`
/// buffer.
/// If `nest_level` is `0`, this function will skip the group's name.
#[cfg(all(feature = "cache", feature = "http"))]
fn flatten_group_to_string(
group_text: &mut String,
group: &GroupCommandsPair,
nest_level: usize,
help_options: &HelpOptions,
) {
let repeated_indent_str = help_options.indention_prefix.repeat(nest_level);
if nest_level > 0 {
let _ = writeln!(group_text,
"{}__**{}**__",
repeated_indent_str,
group.name,
);
}
if !group.prefixes.is_empty() {
let _ = writeln!(group_text,
"{}{}: `{}`",
&repeated_indent_str,
help_options.group_prefix,
group.prefixes.join("`, `"),
);
};
let mut joined_commands = group
.command_names
.join(&format!("\n{}", &repeated_indent_str));
if group.command_names.len() >= 1 {
joined_commands.insert_str(0, &repeated_indent_str);
}
let _ = writeln!(group_text, "{}", joined_commands);
for sub_group in &group.sub_groups {
if !sub_group.command_names.is_empty() {
let mut sub_group_text = String::default();
flatten_group_to_string(
&mut sub_group_text,
&sub_group,
nest_level + 1,
&help_options,
);
let _ = write!(group_text, "{}", sub_group_text);
}
}
}
/// Flattens a group with all its nested sub-groups into the passed `group_text`
/// buffer respecting the plain help format.
/// If `nest_level` is `0`, this function will skip the group's name.
#[cfg(all(feature = "cache", feature = "http"))]
fn flatten_group_to_plain_string(
group_text: &mut String,
group: &GroupCommandsPair,
nest_level: usize,
help_options: &HelpOptions,
) {
let repeated_indent_str = help_options.indention_prefix.repeat(nest_level);
if nest_level > 0 {
let _ = write!(group_text,
"\n{}**{}**",
repeated_indent_str,
group.name,
);
}
if group.prefixes.is_empty() {
let _ = write!(group_text, ": ");
} else {
let _ = write!(group_text,
" ({}: `{}`): ",
help_options.group_prefix,
group.prefixes.join("`, `"),
);
}
let joined_commands = format!("`{}`", group.command_names.join("`, `"));
let _ = write!(group_text, "{}", joined_commands);
for sub_group in &group.sub_groups {
let mut sub_group_text = String::default();
flatten_group_to_plain_string(
&mut sub_group_text,
&sub_group,
nest_level + 1,
&help_options,
);
let _ = write!(group_text, "{}", sub_group_text);
}
}
/// Sends an embed listing all groups with their commands.
#[cfg(all(feature = "cache", feature = "http"))]
fn send_grouped_commands_embed(
http: impl AsRef<Http>,
help_options: &HelpOptions,
channel_id: ChannelId,
help_description: &str,
groups: &[GroupCommandsPair],
colour: Colour,
) -> Result<Message, Error> {
channel_id.send_message(&http, |m| {
m.embed(|embed| {
embed.colour(colour);
embed.description(help_description);
for group in groups {
let mut embed_text = String::default();
flatten_group_to_string(
&mut embed_text,
&group,
0,
&help_options,
);
embed.field(group.name, &embed_text, true);
}
embed
});
m
})
}
/// Sends embed showcasing information about a single command.
#[cfg(all(feature = "cache", feature = "http"))]
fn send_single_command_embed(
http: impl AsRef<Http>,
help_options: &HelpOptions,
channel_id: ChannelId,
command: &Command<'_>,
colour: Colour,
) -> Result<Message, Error> {
channel_id.send_message(&http, |m| {
m.embed(|embed| {
embed.title(&command.name);
embed.colour(colour);
if let Some(ref desc) = command.description {
embed.description(desc);
}
if let Some(ref usage) = command.usage {
let full_usage_text = if let Some(first_prefix) = command.group_prefixes.get(0) {
format!("`{} {} {}`", first_prefix, command.name, usage)
} else {
format!("`{} {}`", command.name, usage)
};
embed.field(&help_options.usage_label, full_usage_text, true);
}
embed.field(&help_options.grouped_label, command.group_name, true);
if !command.aliases.is_empty() {
embed.field(
&help_options.aliases_label,
format!("`{}`", command.aliases.join("`, `")),
true,
);
}
embed.field(&help_options.available_text, &command.availability, true);
if !command.checks.is_empty() {
embed.field(
&help_options.checks_label,
format!("`{}`", command.checks.join("`, `")),
true,
);
}
embed
});
m
})
}
/// Sends embed listing commands that are similar to the sent one.
#[cfg(all(feature = "cache", feature = "http"))]
fn send_suggestion_embed(
http: impl AsRef<Http>,
channel_id: ChannelId,
help_description: &str,
suggestions: &Suggestions,
colour: Colour,
) -> Result<Message, Error> {
let text = help_description
.replace("{}", &suggestions.join("`, `"))
.to_string();
channel_id.send_message(&http, |m| {
m.embed(|e| {
e.colour(colour);
e.description(text);
e
});