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 context;
13mod event;
14mod expand;
15mod reply;
16mod utils;
17
18use crate::{
19    config::{BabyriteConfig, EnvConfig, LogFormat},
20    context::BotContext,
21};
22use std::sync::Arc;
23use std::time::Duration;
24use tracing_subscriber::EnvFilter;
25use twilight_gateway::{ConfigBuilder, EventTypeFlags, Intents, Shard, ShardId, StreamExt as _};
26use twilight_model::gateway::{
27    payload::outgoing::update_presence::UpdatePresencePayload,
28    presence::{Activity, ActivityType, MinimalActivity, Status},
29};
30
31/// The gateway events [`event::handle`] acts on.
32///
33/// Everything else is skipped before deserialization, which matters most for
34/// the large guild payloads; `GUILD_CREATE` is kept only to invalidate roles.
35const WANTED_EVENTS: EventTypeFlags = EventTypeFlags::READY
36    .union(EventTypeFlags::MESSAGE_CREATE)
37    .union(EventTypeFlags::CHANNEL_CREATE)
38    .union(EventTypeFlags::CHANNEL_UPDATE)
39    .union(EventTypeFlags::CHANNEL_DELETE)
40    .union(EventTypeFlags::THREAD_CREATE)
41    .union(EventTypeFlags::THREAD_UPDATE)
42    .union(EventTypeFlags::THREAD_DELETE)
43    .union(EventTypeFlags::ROLE_CREATE)
44    .union(EventTypeFlags::ROLE_UPDATE)
45    .union(EventTypeFlags::ROLE_DELETE)
46    .union(EventTypeFlags::GUILD_CREATE);
47
48#[tokio::main]
49async fn main() -> anyhow::Result<()> {
50    dotenvy::dotenv().ok();
51
52    BabyriteConfig::init()?;
53    let envs = EnvConfig::get();
54    let config = BabyriteConfig::get();
55
56    // `RUST_LOG` takes precedence; otherwise fall back to the `[log] level`
57    // configured in `config.toml` (defaults to `babyrite=info`).
58    let filter = EnvFilter::try_from_default_env()
59        .unwrap_or_else(|_| EnvFilter::new(config.log.level.clone()));
60    let builder = tracing_subscriber::fmt().with_env_filter(filter);
61    match config.resolved_log_format() {
62        LogFormat::Json => builder.json().init(),
63        LogFormat::Compact => builder.compact().init(),
64    }
65    tracing::debug!("Config: {:?}", config);
66
67    let token = envs.discord_api_token.clone();
68    let ctx = Arc::new(BotContext {
69        http: twilight_http::Client::new(token.clone()),
70        // The raw-content read caps bytes, not time: without a timeout a stalled
71        // server would hold the fetch open indefinitely.
72        github: reqwest::Client::builder()
73            .timeout(Duration::from_secs(10))
74            .build()
75            .expect("Failed to build HTTP client."),
76    });
77
78    let mut activity = Activity::from(MinimalActivity {
79        kind: ActivityType::Custom,
80        name: "Custom Status".into(),
81        url: None,
82    });
83    activity.state = Some(format!("Running v{}", env!("CARGO_PKG_VERSION")));
84    // Sent with IDENTIFY rather than set once connected, so every re-identify
85    // after a lost session restores it without the bot doing anything.
86    let presence = UpdatePresencePayload::new(vec![activity], false, None, Status::Online)
87        .expect("presence has one activity");
88
89    let intents = Intents::GUILDS | Intents::GUILD_MESSAGES | Intents::MESSAGE_CONTENT;
90    let shard_config = ConfigBuilder::new(token, intents)
91        .presence(presence)
92        .build();
93    let mut shard = Shard::with_config(ShardId::ONE, shard_config);
94
95    while let Some(item) = shard.next_event(WANTED_EVENTS).await {
96        match item {
97            Ok(event) => {
98                tokio::spawn(event::handle(Arc::clone(&ctx), event));
99            }
100            // Not fatal: the shard reconnects on its own.
101            Err(source) => tracing::warn!(?source, "error receiving gateway event"),
102        }
103    }
104
105    // The stream ends only on a close code that reconnecting cannot fix (e.g.
106    // an invalid token or disallowed intents), so exit non-zero and let the
107    // supervisor decide.
108    anyhow::bail!("gateway connection closed fatally")
109}