Skip to main content

zaun_bot/
events.rs

1//! [`EventContext`]: what an event handler can do, and the dispatch of [`Event`]s to the
2//! typed handlers of [`Bot`].
3
4use crate::types::{Event, HostError, Id, Message, MessageBody, Ready};
5use crate::{Bot, Reply, messages};
6
7/// What an event handler can do: send, reply, react, delete and send direct messages. Every
8/// call is an ordinary command on the bot's member, checked by the host.
9#[derive(Debug, Clone, Default)]
10pub struct EventContext {
11    /// Who and where the bot is, once `on_ready` has run (always, for every later event).
12    pub me: Option<Ready>,
13}
14
15impl EventContext {
16    /// Sends a message to a channel. Returns its id.
17    ///
18    /// # Errors
19    /// The host's refusal.
20    pub fn send(&self, channel_id: &str, reply: impl Into<Reply>) -> Result<Id, HostError> {
21        let body: MessageBody = reply.into().build();
22        messages::send(channel_id, &body, None)
23    }
24
25    /// Replies to a message, in its channel.
26    ///
27    /// # Errors
28    /// The host's refusal.
29    pub fn reply_to(&self, message: &Message, reply: impl Into<Reply>) -> Result<Id, HostError> {
30        let body: MessageBody = reply.into().build();
31        messages::send(&message.channel_id, &body, Some(&message.message_id))
32    }
33
34    /// Adds a reaction.
35    ///
36    /// # Errors
37    /// The host's refusal.
38    pub fn react(&self, message: &Message, emoji: &str) -> Result<(), HostError> {
39        messages::react(&message.channel_id, &message.message_id, emoji)
40    }
41
42    /// Deletes a message (the bot's own, or any with `MANAGE_MESSAGES`).
43    ///
44    /// # Errors
45    /// The host's refusal.
46    pub fn delete_message(&self, message: &Message) -> Result<(), HostError> {
47        messages::delete(&message.channel_id, &message.message_id)
48    }
49
50    /// Sends a direct message to a member (capability `dms`). Returns the DM's channel id and
51    /// the message id. `FORBIDDEN` with reason `dms_closed` when the member does not take DMs
52    /// from bots or closed this one.
53    ///
54    /// # Errors
55    /// The host's refusal.
56    pub fn dm(&self, member_id: &str, reply: impl Into<Reply>) -> Result<(Id, Id), HostError> {
57        let body: MessageBody = reply.into().build();
58        messages::dm(member_id, &body)
59    }
60
61    /// Whether `member_id` is the bot itself (to ignore its own messages).
62    #[must_use]
63    pub fn is_me(&self, member_id: &str) -> bool {
64        self.me.as_ref().is_some_and(|me| me.member_id == member_id)
65    }
66
67    /// Whether `message` mentions the bot: by its member id, by `@everyone`, or by one of its
68    /// roles. Only when the message names roles does it ask the host for the bot's own roles
69    /// (`community::get_member`); a refusal there counts as not mentioned.
70    #[must_use]
71    pub fn mentions_me(&self, message: &Message) -> bool {
72        let Some(me) = &self.me else {
73            return false;
74        };
75        let m = &message.mentions;
76        if m.everyone || m.has_member(&me.member_id) {
77            return true;
78        }
79        !m.roles.is_empty()
80            && crate::community::get_member(&me.member_id)
81                .is_ok_and(|mine| m.includes(&me.member_id, &mine.role_ids))
82    }
83}
84
85/// Calls the [`Bot`] handler for `event`.
86pub fn dispatch<B: Bot>(bot: &mut B, ctx: EventContext, event: Event) {
87    match event {
88        Event::Ready(r) => bot.on_ready(ctx, r),
89        Event::MessageCreated(m) => bot.on_message_create(ctx, m.message, m.is_dm),
90        Event::MessageUpdated(m) => bot.on_message_update(ctx, m.message, m.is_dm),
91        Event::MessageDeleted(d) => bot.on_message_delete(ctx, d.channel_id, d.message_id),
92        Event::MessagesBulkDeleted(d) => {
93            bot.on_message_delete_bulk(ctx, d.channel_id, d.message_ids)
94        }
95        Event::ReactionAdded(r) => bot.on_reaction_add(ctx, r),
96        Event::ReactionRemoved(r) => bot.on_reaction_remove(ctx, r),
97        Event::MemberJoined(m) => bot.on_member_join(ctx, m),
98        Event::MemberUpdated(m) => bot.on_member_update(ctx, m),
99        Event::MemberLeft(id) => bot.on_member_leave(ctx, id),
100        Event::MemberRemoved(reason) => bot.on_removed(ctx, reason),
101        Event::MemberRolesUpdated(r) => bot.on_member_roles_update(ctx, r),
102        Event::MemberTimedOut(t) => bot.on_member_timeout(ctx, t),
103        Event::ChannelCreated(c) => bot.on_channel_create(ctx, c),
104        Event::ChannelUpdated(c) => bot.on_channel_update(ctx, c),
105        Event::ChannelDeleted(id) => bot.on_channel_delete(ctx, id),
106        Event::RoleCreated(r) => bot.on_role_create(ctx, r),
107        Event::RoleUpdated(r) => bot.on_role_update(ctx, r),
108        Event::RoleDeleted(id) => bot.on_role_delete(ctx, id),
109        Event::TypingStarted(t) => bot.on_typing_start(ctx, t),
110        Event::PresenceUpdated(p) => bot.on_presence_update(ctx, p),
111        Event::CommunityUpdated(c) => bot.on_community_update(ctx, c),
112        Event::CommandUpdated(bot_id) => bot.on_commands_update(ctx, bot_id),
113        Event::DmCreated(c) => bot.on_dm_open(ctx, c),
114        Event::DmClosed(id) => bot.on_dm_close(ctx, id),
115        Event::Other(raw) => bot.on_raw(ctx, raw),
116    }
117}