Skip to main content

basic_structure/
main.rs

1#![warn(clippy::str_to_string)]
2
3mod commands;
4
5use poise::serenity_prelude as serenity;
6use std::{
7    collections::HashMap,
8    env::var,
9    sync::{Arc, Mutex},
10    time::Duration,
11};
12
13// Types used by all command functions
14type Error = Box<dyn std::error::Error + Send + Sync>;
15type Context<'a> = poise::Context<'a, Data, Error>;
16
17// Custom user data passed to all command functions
18pub struct Data {
19    votes: Mutex<HashMap<String, u32>>,
20}
21
22async fn on_error(error: poise::FrameworkError<'_, Data, Error>) {
23    // This is our custom error handler
24    // They are many errors that can occur, so we only handle the ones we want to customize
25    // and forward the rest to the default handler
26    match error {
27        poise::FrameworkError::Setup { error, .. } => panic!("Failed to start bot: {:?}", error),
28        poise::FrameworkError::Command { error, ctx, .. } => {
29            println!("Error in command `{}`: {:?}", ctx.command().name, error,);
30        }
31        error => {
32            if let Err(e) = poise::builtins::on_error(error).await {
33                println!("Error while handling error: {}", e)
34            }
35        }
36    }
37}
38
39#[tokio::main]
40async fn main() {
41    tracing_subscriber::fmt::init();
42
43    // FrameworkOptions contains all of poise's configuration option in one struct
44    // Every option can be omitted to use its default value
45    let options = poise::FrameworkOptions {
46        commands: vec![commands::vote(), commands::getvotes()],
47        prefix_options: poise::PrefixFrameworkOptions {
48            prefix: Some("~".into()),
49            edit_tracker: Some(Arc::new(poise::EditTracker::for_timespan(
50                Duration::from_secs(3600),
51            ))),
52            additional_prefixes: vec![
53                poise::Prefix::Literal("hey bot,"),
54                poise::Prefix::Literal("hey bot"),
55            ],
56            ..Default::default()
57        },
58        // The global error handler for all error cases that may occur
59        on_error: |error| Box::pin(on_error(error)),
60        // This code is run before every command
61        pre_command: |ctx| {
62            Box::pin(async move {
63                println!("Executing command {}...", ctx.command().qualified_name);
64            })
65        },
66        // This code is run after a command if it was successful (returned Ok)
67        post_command: |ctx| {
68            Box::pin(async move {
69                println!("Executed command {}!", ctx.command().qualified_name);
70            })
71        },
72        // Every command invocation must pass this check to continue execution
73        command_check: Some(|ctx| {
74            Box::pin(async move {
75                if ctx.author().id == 123456789 {
76                    return Ok(false);
77                }
78                Ok(true)
79            })
80        }),
81        // Enforce command checks even for owners (enforced by default)
82        // Set to true to bypass checks, which is useful for testing
83        skip_checks_for_owners: false,
84        event_handler: |_framework, event| {
85            Box::pin(async move {
86                println!(
87                    "Got an event in event handler: {:?}",
88                    event.snake_case_name()
89                );
90                Ok(())
91            })
92        },
93        ..Default::default()
94    };
95
96    let framework = poise::Framework::builder()
97        .setup(move |ctx, ready, framework| {
98            Box::pin(async move {
99                println!("Logged in as {}", ready.user.name);
100                poise::builtins::register_globally(ctx, &framework.options().commands).await?;
101                Ok(Data {
102                    votes: Mutex::new(HashMap::new()),
103                })
104            })
105        })
106        .options(options)
107        .build();
108
109    let token = var("DISCORD_TOKEN")
110        .expect("Missing `DISCORD_TOKEN` env var, see README for more information.");
111    let intents =
112        serenity::GatewayIntents::non_privileged() | serenity::GatewayIntents::MESSAGE_CONTENT;
113
114    let client = serenity::ClientBuilder::new(token, intents)
115        .framework(framework)
116        .await;
117
118    client.unwrap().start().await.unwrap()
119}