Skip to content

Commit

Permalink
Add interpolation for tags
Browse files Browse the repository at this point in the history
  • Loading branch information
mattfbacon committed Jul 6, 2024
1 parent b61cebc commit 881f30b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
5 changes: 3 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 22 additions & 1 deletion crates/bot/src/bot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -547,9 +547,28 @@ async fn tag_autocomplete(ctx: Context<'_>, partial_tag: &str) -> Vec<TagName> {
.unwrap_or_else(|_| Vec::new())
}

fn interpolate<'a>(template: &str, mut params: impl Iterator<Item = &'a str>) -> String {
let mut buf = String::with_capacity(template.len() / 2);
for chunk in template.split("%%") {
let mut chunks = chunk.split("%s");
buf += chunks.next().unwrap();
for chunk in chunks {
buf += params.next().unwrap_or("%s");
buf += chunk;
}
buf += "%";
}
// Remove last `%`.
buf.pop();
buf
}

/// Print the content of a tag by name.
///
/// Syntax: `?tag <tag name>`
/// Syntax: `?tag <tag name> <parameters...>`
///
/// If the tag has placeholders (set with `%s`),
/// then you can fill them with the subsequent arguments.
///
/// Note that tags are local to the guild.
#[poise::command(prefix_command, slash_command, track_edits)]
Expand All @@ -559,6 +578,7 @@ async fn tag(
#[description = "The tag to print"]
#[autocomplete = "tag_autocomplete"]
TagName(tag_name): TagName,
#[description = "Any parameters for the tag"] parameters: Vec<String>,
) -> Result<(), PoiseError> {
let database = &ctx.data().database;
let guild_id = ctx.guild_id().ok_or("no guild id, so no tags")?.get();
Expand All @@ -571,6 +591,7 @@ async fn tag(
.map(|row| row.get::<_, String>("text"))
.transpose()?;
let text = text.unwrap_or_else(|| "That tag is not defined.".into());
let text = interpolate(&text, parameters.iter().map(String::as_str));
ctx.say(text).await?;
Ok(())
}
Expand Down

0 comments on commit 881f30b

Please sign in to comment.