Skip to main content

fluent_localization/
main.rs

1mod translation;
2
3use poise::serenity_prelude as serenity;
4use translation::tr;
5
6pub struct Data {
7    translations: &'static translation::Translations,
8}
9
10type Error = Box<dyn std::error::Error + Send + Sync>;
11type Context<'a> = poise::Context<'a, Data, Error>;
12
13#[derive(poise::ChoiceParameter)]
14pub enum WelcomeChoice {
15    Ask,
16    GoodPerson,
17    Controller,
18    Coffee,
19}
20
21#[poise::command(slash_command)]
22pub async fn welcome(
23    ctx: Context<'_>,
24    user: serenity::User,
25    message: WelcomeChoice,
26) -> Result<(), Error> {
27    use poise::ChoiceParameter as _;
28
29    ctx.say(format!("<@{}> {}", user.id, tr!(ctx, message.name())))
30        .await?;
31    Ok(())
32}
33
34#[poise::command(slash_command)]
35pub async fn info(ctx: Context<'_>) -> Result<(), Error> {
36    let guild = ctx
37        .partial_guild()
38        .await
39        .ok_or_else(|| tr!(ctx, "not-in-guild-error"))?;
40
41    let response = tr!(ctx, "guild-info",
42        name: &*guild.name,
43        emojiCount: guild.emojis.len(),
44        emojis: guild.emojis.values().map(|e| e.to_string()).collect::<String>(),
45        roleCount: guild.roles.len(),
46        stickerCount: guild.stickers.len(),
47    );
48
49    ctx.say(response).await?;
50    Ok(())
51}
52
53#[poise::command(prefix_command)]
54async fn register(ctx: Context<'_>) -> Result<(), Error> {
55    poise::builtins::register_application_commands_buttons(ctx).await?;
56    Ok(())
57}
58
59#[tokio::main]
60async fn main() {
61    tracing_subscriber::fmt::init();
62
63    let mut commands = vec![welcome(), info(), register()];
64    let translations = translation::read_ftl().expect("failed to read translation files");
65
66    // We leak the translations so we can easily copy around `&'static str`s, to the downside
67    // that the OS will reclaim the memory at the end of `main` instead of the Drop implementation.
68    let translations: &'static translation::Translations = Box::leak(Box::new(translations));
69
70    translation::apply_translations(translations, &mut commands);
71
72    let token = std::env::var("TOKEN").unwrap();
73    let intents = serenity::GatewayIntents::non_privileged();
74
75    let framework = poise::Framework::builder()
76        .options(poise::FrameworkOptions {
77            commands,
78            ..Default::default()
79        })
80        .setup(move |_, _, _| Box::pin(async move { Ok(Data { translations }) }))
81        .build();
82
83    let client = serenity::ClientBuilder::new(token, intents)
84        .framework(framework)
85        .await;
86
87    client.unwrap().start().await.unwrap()
88}