Skip to main content

djs_model/
poll.rs

1//! [Polls](https://docs.discord.com/developers/resources/poll) attached to messages.
2//!
3//! A poll lives on its [message](crate::message::Message): it has a question, up to 10
4//! answers and, once people vote, [results](Results). The request body that creates a poll
5//! belongs to the REST layer.
6
7use compact_str::CompactString;
8use serde::{Deserialize, Serialize};
9
10use crate::{emoji::PartialEmoji, macros::int_enum, util::Timestamp};
11
12/// A [poll](https://docs.discord.com/developers/resources/poll#poll-object).
13///
14/// discord.js counterpart: `Poll`.
15#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
16#[non_exhaustive]
17pub struct Poll {
18    /// The question (only [`text`](Media::text) is supported).
19    pub question: Media,
20    /// The answers to choose from.
21    pub answers: Vec<Answer>,
22    /// When the poll ends. Discord documents it as nullable for polls that may never expire,
23    /// although currently every poll has an expiry.
24    pub expiry: Option<Timestamp>,
25    /// Whether a user can choose several answers.
26    pub allow_multiselect: bool,
27    /// How the poll is displayed.
28    pub layout_type: LayoutType,
29    /// The vote counts. `None` means *unknown* results, not *no* votes: some responses omit
30    /// them because Discord did not fetch them (results received earlier stay valid). Ended
31    /// polls always have results.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub results: Option<Results>,
34}
35
36int_enum! {
37    /// The [layout of a poll](https://docs.discord.com/developers/resources/poll#layout-type).
38    ///
39    /// discord.js counterpart: `PollLayoutType`.
40    #[doc(alias = "PollLayoutType")]
41    #[derive(Default)]
42    pub enum LayoutType: u8 {
43        /// The default layout.
44        #[default]
45        Default = 1,
46    }
47}
48
49/// The [text and/or emoji](https://docs.discord.com/developers/resources/poll#poll-media-object)
50/// of a poll question or answer.
51///
52/// discord.js counterpart: `PollQuestionMedia` / `PollAnswer` (text and emoji).
53#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
54#[non_exhaustive]
55#[doc(alias = "PollMedia")]
56pub struct Media {
57    /// The text (questions: max 300 characters, answers: max 55 characters).
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub text: Option<CompactString>,
60    /// The emoji (answers only).
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub emoji: Option<PartialEmoji>,
63}
64
65/// An [answer of a poll](https://docs.discord.com/developers/resources/poll#poll-answer-object).
66///
67/// discord.js counterpart: `PollAnswer`.
68#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
69#[non_exhaustive]
70#[doc(alias = "PollAnswer")]
71pub struct Answer {
72    /// The answer's ID: currently `1`, `2`, … in order, but treat it as opaque.
73    pub answer_id: u32,
74    /// The answer's text and/or emoji.
75    pub poll_media: Media,
76}
77
78/// The [results of a poll](https://docs.discord.com/developers/resources/poll#poll-results-object).
79///
80/// While a poll is running, the counts are usually but not always accurate; after it ends, a
81/// final tally runs, and once [`is_finalized`](Self::is_finalized) is `true` they are exact. An
82/// answer without an entry in [`answer_counts`](Self::answer_counts) has no votes.
83///
84/// discord.js counterpart: `APIPollResults` (discord-api-types).
85#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
86#[non_exhaustive]
87#[doc(alias = "PollResults")]
88pub struct Results {
89    /// Whether the votes have been precisely counted.
90    pub is_finalized: bool,
91    /// The counts per answer.
92    pub answer_counts: Vec<AnswerCount>,
93}
94
95/// The [vote count of one answer](https://docs.discord.com/developers/resources/poll#poll-results-object-poll-answer-count-object-structure).
96///
97/// discord.js counterpart: `APIPollAnswerCount` (discord-api-types).
98#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
99#[non_exhaustive]
100#[doc(alias = "PollAnswerCount")]
101pub struct AnswerCount {
102    /// The [`Answer::answer_id`].
103    pub id: u32,
104    /// The number of votes.
105    pub count: u32,
106    /// Whether the current user voted for this answer.
107    pub me_voted: bool,
108}
109
110/// A [poll to create](https://docs.discord.com/developers/resources/poll#poll-create-request-object),
111/// sent with a new message or an interaction response.
112///
113/// discord.js counterpart: `PollData` (the `poll` option of message create options).
114///
115/// # Examples
116///
117/// ```
118/// use djs_model::poll::{CreatePoll, Media};
119///
120/// let mut poll = CreatePoll::new("Tabs or spaces?", [Media::new("Tabs"), Media::new("Spaces")]);
121/// poll.duration = Some(24);
122/// assert_eq!(
123///     serde_json::to_string(&poll).unwrap(),
124///     concat!(
125///         r#"{"question":{"text":"Tabs or spaces?"},"answers":[{"poll_media":{"text":"Tabs"}},"#,
126///         r#"{"poll_media":{"text":"Spaces"}}],"duration":24}"#,
127///     )
128/// );
129/// ```
130#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
131#[non_exhaustive]
132#[doc(alias = "PollCreateRequest")]
133pub struct CreatePoll {
134    /// The question (text only, max 300 characters).
135    pub question: Media,
136    /// The answers (up to 10; text max 55 characters, optionally an emoji), written as answer
137    /// objects without IDs.
138    #[serde(with = "create_answers")]
139    pub answers: Vec<Media>,
140    /// How long the poll is open, in hours (up to 32 days; Discord's default is 24 hours).
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub duration: Option<u32>,
143    /// Whether users can select several answers (Discord's default: `false`).
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub allow_multiselect: Option<bool>,
146    /// The layout (Discord's default: [`LayoutType::Default`]).
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub layout_type: Option<LayoutType>,
149}
150
151impl CreatePoll {
152    /// Creates a poll with Discord's defaults for everything else.
153    ///
154    /// discord.js counterpart: `PollData`.
155    #[must_use]
156    pub fn new(
157        question: impl Into<CompactString>,
158        answers: impl IntoIterator<Item = Media>,
159    ) -> Self {
160        Self {
161            question: Media::new(question),
162            answers: answers.into_iter().collect(),
163            duration: None,
164            allow_multiselect: None,
165            layout_type: None,
166        }
167    }
168}
169
170impl Media {
171    /// Creates media with text and no emoji (set [`emoji`](Self::emoji) for an answer emoji).
172    ///
173    /// discord.js counterpart: `PollAnswerData`.
174    #[must_use]
175    pub fn new(text: impl Into<CompactString>) -> Self {
176        Self {
177            text: Some(text.into()),
178            emoji: None,
179        }
180    }
181}
182
183/// (De)serializes the answers of a [`CreatePoll`] as `[{"poll_media": …}]`.
184mod create_answers {
185    use serde::{Deserialize, Deserializer, Serialize, Serializer, ser::SerializeSeq};
186
187    use super::Media;
188
189    #[derive(Serialize)]
190    struct AnswerRef<'a> {
191        poll_media: &'a Media,
192    }
193
194    #[derive(Deserialize)]
195    struct Answer {
196        poll_media: Media,
197    }
198
199    pub(super) fn serialize<S: Serializer>(
200        answers: &[Media],
201        serializer: S,
202    ) -> Result<S::Ok, S::Error> {
203        let mut seq = serializer.serialize_seq(Some(answers.len()))?;
204        for poll_media in answers {
205            seq.serialize_element(&AnswerRef { poll_media })?;
206        }
207        seq.end()
208    }
209
210    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
211        deserializer: D,
212    ) -> Result<Vec<Media>, D::Error> {
213        let answers = Vec::<Answer>::deserialize(deserializer)?;
214        Ok(answers
215            .into_iter()
216            .map(|answer| answer.poll_media)
217            .collect())
218    }
219}