Skip to main content

babyrite/
main.rs

1//! Babyrite - A Discord bot for message link previews.
2//!
3//! This bot automatically generates previews for Discord message links
4//! shared within the same guild, and expands GitHub permalinks into
5//! code blocks.
6
7#![deny(clippy::all)]
8#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
9
10mod cache;
11mod config;
12mod event;
13mod expand;
14mod reply;
15mod utils;
16
17use crate::{
18    config::{BabyriteConfig, EnvConfig, LogFormat},
19    event::BabyriteEventHandler,
20    expand::github::HttpClient,
21};
22use serenity::all::GatewayIntents;
23use std::time::Duration;
24use tracing_subscriber::EnvFilter;
25
26#[tokio::main]
27async fn main() -> anyhow::Result<()> {
28    dotenvy::dotenv().ok();
29
30    BabyriteConfig::init()?;
31    let envs = EnvConfig::get();
32    let config = BabyriteConfig::get();
33
34    // `RUST_LOG` takes precedence; otherwise fall back to the `[log] level`
35    // configured in `config.toml` (defaults to `babyrite=info`).
36    let filter = EnvFilter::try_from_default_env()
37        .unwrap_or_else(|_| EnvFilter::new(config.log.level.clone()));
38    let builder = tracing_subscriber::fmt().with_env_filter(filter);
39    match config.resolved_log_format() {
40        LogFormat::Json => builder.json().init(),
41        LogFormat::Compact => builder.compact().init(),
42    }
43    tracing::debug!("Config: {:?}", config);
44
45    let mut client = serenity::Client::builder(
46        &envs.discord_api_token,
47        GatewayIntents::MESSAGE_CONTENT | GatewayIntents::GUILD_MESSAGES | GatewayIntents::GUILDS,
48    )
49    .event_handler(BabyriteEventHandler)
50    .await
51    .expect("Failed to initialize client.");
52
53    // Register the shared HTTP client for GitHub API requests.
54    {
55        let mut data = client.data.write().await;
56        // The raw-content read caps bytes, not time: without a timeout a stalled
57        // server would hold the fetch open indefinitely.
58        data.insert::<HttpClient>(
59            reqwest::Client::builder()
60                .timeout(Duration::from_secs(10))
61                .build()
62                .expect("Failed to build HTTP client."),
63        );
64    }
65
66    client.start().await?;
67
68    Ok(())
69}