Skip to main content

babyrite/
event.rs

1//! Event handling module for Discord events.
2//!
3//! [`handle`] is spawned once per gateway event received by the shard in
4//! `main`, and dispatches it to the handling it needs.
5
6use crate::cache::{invalidate_channel, invalidate_guild_roles};
7use crate::config::BabyriteConfig;
8use crate::context::BotContext;
9use crate::expand::{EXPANDERS, ExpandContext, ExpandedContent};
10use futures_util::future::join_all;
11use std::sync::Arc;
12use tracing::Instrument;
13use twilight_gateway::Event;
14use twilight_model::channel::{Channel, Message};
15use twilight_model::id::{
16    Id,
17    marker::{ChannelMarker, MessageMarker},
18};
19
20/// Handles one gateway event.
21pub async fn handle(ctx: Arc<BotContext>, event: Event) {
22    // Every arm but `Ready`, `GatewayClose` and `MessageCreate` exists only to
23    // keep the caches from outliving the permissions they hold.
24    // `check_visibility` decides whether a link may be expanded from the cached
25    // permission overwrites and role permissions, so a cached channel or role
26    // that Discord has since restricted keeps being treated as visible.
27    // Channel creations and deletions are included because the guild's channel
28    // list is cached as one value, and a stale list answers for channels that
29    // no longer exist and misses ones that now do.
30    match event {
31        Event::Ready(ready) => {
32            tracing::info!(
33                version = env!("CARGO_PKG_VERSION"),
34                user = %ready.user.name,
35                guilds = ready.guilds.len(),
36                "connected"
37            );
38        }
39        Event::ChannelCreate(channel) => on_channel_change(&channel).await,
40        Event::ChannelUpdate(channel) => on_channel_change(&channel).await,
41        Event::ChannelDelete(channel) => on_channel_change(&channel).await,
42        Event::ThreadCreate(thread) => on_channel_change(&thread).await,
43        Event::ThreadUpdate(thread) => on_channel_change(&thread).await,
44        Event::ThreadDelete(thread) => invalidate_channel(thread.guild_id, thread.id).await,
45        Event::RoleCreate(role) => invalidate_guild_roles(role.guild_id).await,
46        Event::RoleUpdate(role) => invalidate_guild_roles(role.guild_id).await,
47        Event::RoleDelete(role) => invalidate_guild_roles(role.guild_id).await,
48        // Role events missed while disconnected are never replayed; the guild
49        // arriving again is the only sign that its roles may have changed.
50        Event::GuildCreate(guild) => invalidate_guild_roles(guild.id()).await,
51        Event::GatewayClose(frame) => {
52            tracing::warn!(?frame, "gateway connection closed; reconnecting");
53        }
54        Event::MessageCreate(message) => on_message(&ctx, &message).await,
55        _ => {}
56    }
57}
58
59async fn on_channel_change(channel: &Channel) {
60    if let Some(guild_id) = channel.guild_id {
61        invalidate_channel(guild_id, channel.id).await;
62    }
63}
64
65async fn on_message(ctx: &BotContext, request: &Message) {
66    if request.author.bot {
67        return;
68    }
69
70    let Some(request_guild_id) = request.guild_id else {
71        return;
72    };
73
74    // Correlation span: every log emitted while handling this message
75    // carries these fields, so a single request can be traced end-to-end
76    // (e.g. via Grafana Loki). `request.id` is the unique Discord message
77    // ID and serves as the correlation key.
78    let span = tracing::info_span!(
79        "message",
80        message_id = %request.id,
81        guild_id = %request_guild_id,
82        channel_id = %request.channel_id,
83        author = %request.author.name,
84    );
85
86    async {
87        let config = BabyriteConfig::get();
88
89        // Expanders are independent of each other, so run them concurrently.
90        // `join_all` preserves registration order in the combined results.
91        let cx = ExpandContext {
92            ctx,
93            message: request,
94            guild_id: request_guild_id,
95        };
96        let results: Vec<ExpandedContent> = join_all(
97            EXPANDERS
98                .iter()
99                .filter(|expander| expander.enabled(config))
100                .map(|expander| expander.expand_all(&cx)),
101        )
102        .await
103        .into_iter()
104        .flatten()
105        .collect();
106
107        if results.is_empty() {
108            tracing::debug!("no expandable content found");
109            return;
110        }
111
112        send_expanded_contents(&ctx.http, request.channel_id, request.id, results).await;
113    }
114    .instrument(span)
115    .await;
116}
117
118/// Sends expanded contents as a reply to the original message.
119///
120/// A failed send is reported and skipped rather than aborting the rest: the
121/// expansions are independent, so one rejected message must not silence the
122/// others.
123async fn send_expanded_contents(
124    http: &twilight_http::Client,
125    channel_id: Id<ChannelMarker>,
126    request_id: Id<MessageMarker>,
127    results: Vec<ExpandedContent>,
128) {
129    let embeds = results
130        .iter()
131        .filter(|result| matches!(result, ExpandedContent::Embed(_)))
132        .count();
133    let code_blocks = results.len() - embeds;
134
135    let messages = crate::reply::build_messages(request_id, results);
136    let total = messages.len();
137    let mut sent = 0;
138    for message in &messages {
139        let mut request = http
140            .create_message(channel_id)
141            .allowed_mentions(Some(&message.allowed_mentions));
142        if let Some(content) = message.content.as_deref() {
143            request = request.content(content);
144        }
145        if !message.embeds.is_empty() {
146            request = request.embeds(&message.embeds);
147        }
148        if let Some(id) = message.reply_to {
149            request = request.reply(id);
150        }
151        match request.await {
152            Ok(_) => sent += 1,
153            Err(e) => tracing::error!(error = ?e, "failed to send expanded content"),
154        }
155    }
156
157    // `sent`/`total` count messages, not expansions: every embed shares one.
158    if sent == total {
159        tracing::info!(embeds, code_blocks, "preview sent");
160    } else {
161        tracing::warn!(embeds, code_blocks, sent, total, "preview partially sent");
162    }
163}