forked from serenity-rs/poise
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautocomplete.rs
More file actions
69 lines (62 loc) · 2.36 KB
/
autocomplete.rs
File metadata and controls
69 lines (62 loc) · 2.36 KB
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
use futures::{Stream, StreamExt};
use std::fmt::Write as _;
use poise::serenity_prelude as serenity;
use crate::{Context, Error};
// Poise supports autocomplete on slash command parameters. You need to provide an autocomplete
// function, which will be called on demand when the user is typing a command.
//
// The first parameter of that function is ApplicationContext or Context, and the second parameter
// is a &str of the partial input which the user has typed so far.
//
// As the return value of autocomplete functions, you can return a Stream, an Iterator, or an
// IntoIterator like Vec<T> and [T; N].
//
// The returned collection type must be a &str/String (or number, if you're implementing
// autocomplete on a number type). Wrap the type in serenity::AutocompleteChoice to set a custom label
// for each choice which will be displayed in the Discord UI.
//
// Example function return types (assuming non-number parameter -> autocomplete choices are string):
// - `-> impl Stream<String>`
// - `-> Vec<String>`
// - `-> impl Iterator<String>`
// - `-> impl Iterator<&str>`
// - `-> impl Iterator<serenity::AutocompleteChoice>
async fn autocomplete_name<'a>(
_ctx: Context<'_>,
partial: &'a str,
) -> impl Stream<Item = String> + 'a {
futures::stream::iter(&["Amanda", "Bob", "Christian", "Danny", "Ester", "Falk"])
.filter(move |name| futures::future::ready(name.starts_with(partial)))
.map(|name| name.to_string())
}
async fn autocomplete_number(
_ctx: Context<'_>,
_partial: &str,
) -> impl Iterator<Item = serenity::AutocompleteChoice> {
// Dummy choices
[1_u32, 2, 3, 4, 5].iter().map(|&n| {
serenity::AutocompleteChoice::new(
format!("{n} (why did discord even give autocomplete choices separate labels)"),
n,
)
})
}
/// Greet a user. Showcasing autocomplete!
#[poise::command(slash_command)]
pub async fn greet(
ctx: Context<'_>,
#[description = "Who to greet"]
#[autocomplete = "autocomplete_name"]
name: String,
#[description = "A number... idk I wanted to test number autocomplete"]
#[autocomplete = "autocomplete_number"]
number: Option<u32>,
) -> Result<(), Error> {
let mut response = format!("Hello {}", name);
if let Some(number) = number {
let _ = write!(response, "#{}", number);
}
response += "!";
ctx.say(response).await?;
Ok(())
}