voting.rs 15.5 KB
Newer Older
tec's avatar
tec committed
1
2
3
4
5
use serenity::{
    model::{channel, channel::Message},
    prelude::*,
    utils::MessageBuilder,
};
tec's avatar
tec committed
6
7
use std::collections::HashMap;
use std::sync::Mutex;
tec's avatar
tec committed
8
9
10
11
12
13
14

use crate::config;

macro_rules! e {
    ($error: literal, $x:expr) => {
        match $x {
            Ok(_) => (),
tec's avatar
tec committed
15
            Err(why) => error!($error, why),
tec's avatar
tec committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
        }
    };
}

pub struct Commands;
impl Commands {
    pub fn move_something(ctx: Context, msg: Message, content: &str) {
        let motion = content;
        if motion.len() > 0 {
            create_motion(&ctx, &msg, motion);
        } else {
            e!(
                "Error sending message: {:?}",
                msg.channel_id.say(
                    &ctx.http,
                    "If there's something you want to motion, put it after the !move keyword",
                )
            );
        }
    }
    pub fn motion(ctx: Context, msg: Message, _content: &str) {
        e!("Error sending message: {:?}",
                msg.channel_id.say(
                &ctx.http,
                "I hope you're not having a motion. You may have wanted to !move something instead."
            ));
    }
    pub fn poll(ctx: Context, msg: Message, content: &str) {
        let topic = content;
        if topic.len() > 0 {
            create_poll(&ctx, &msg, topic);
        } else {
            e!(
                "Error sending message: {:?}",
                msg.channel_id.say(
                    &ctx.http,
                    "If there's something you want to motion, put it after the !move keyword",
                )
            );
        }
    }
    pub fn cowsay(ctx: Context, msg: Message, content: &str) {
        let mut text = content.to_owned();
        text.escape_default();
        // Guess what buddy! You definitely are passing a string to cowsay
        text.insert(0, '\'');
        text.insert(text.len(), '\'');
        let output = std::process::Command::new("cowsay")
            .arg(text)
            .output()
            // btw, if we can't execute cowsay we crash
            .expect("failed to execute cowsay");
        let mut message = MessageBuilder::new();
        message.push_codeblock(
            String::from_utf8(output.stdout).expect("unable to parse stdout to String"),
            None,
        );
        e!(
            "Error sending message: {:?}",
            msg.channel_id.say(&ctx.http, message.build())
        );
    }
}

fn create_motion(ctx: &Context, msg: &Message, topic: &str) {
tec's avatar
tec committed
81
    info!("{} created a motion {}", msg.author.name, topic);
tec's avatar
tec committed
82
    if let Err(why) = msg.delete(ctx) {
tec's avatar
tec committed
83
        error!("Error deleting motion prompt: {:?}", why);
tec's avatar
tec committed
84
    }
tec's avatar
tec committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    match msg.channel_id.send_message(&ctx.http, |m| {
        m.embed(|embed| {
            embed.author(|a| {
                a.name(&msg.author.name);
                a.icon_url(
                    msg.author
                        .static_avatar_url()
                        .expect("Expected author to have avatar"),
                );
                a
            });
            embed.colour(serenity::utils::Colour::GOLD);
            embed.title(format!("Motion to {}", topic));
            let mut desc = MessageBuilder::new();
            desc.role(config::VOTE_ROLE);
            desc.push(" take a look at this motion from ");
            desc.mention(&msg.author);
            embed.description(desc.build());
            embed.field("Status", "Under Consideration", true);
            embed.field("Votes", "For: 0\nAgainst: 0\nAbstain: 0", true);
            embed.timestamp(msg.timestamp.to_rfc3339());
            embed
        });
        m.reactions(vec![
            config::FOR_VOTE,
            config::AGAINST_VOTE,
            config::ABSTAIN_VOTE,
            config::APPROVE_REACT,
            config::DISAPPROVE_REACT,
        ]);
        m
    }) {
        Err(why) => {
tec's avatar
tec committed
118
            error!("Error creating motion: {:?}", why);
tec's avatar
tec committed
119
        }
tec's avatar
tec committed
120
        Ok(_) => {}
tec's avatar
tec committed
121
122
123
124
    }
}

fn create_poll(ctx: &Context, msg: &Message, topic: &str) {
tec's avatar
tec committed
125
    info!("{} created a poll {}", msg.author.name, topic);
tec's avatar
tec committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
    match msg.channel_id.send_message(&ctx.http, |m| {
        m.embed(|embed| {
            embed.author(|a| {
                a.name(&msg.author.name);
                a.icon_url(
                    msg.author
                        .static_avatar_url()
                        .expect("Expected author to have avatar"),
                );
                a
            });
            embed.colour(serenity::utils::Colour::BLUE);
            embed.title(format!("Poll {}", topic));
            let mut desc = MessageBuilder::new();
            desc.mention(&msg.author);
            desc.push(" wants to know what you think.");
            embed.description(desc.build());
            embed.timestamp(msg.timestamp.to_rfc3339());
            embed
        });
        m.reactions(vec![
            config::APPROVE_REACT,
            config::DISAPPROVE_REACT,
            config::UNSURE_REACT,
        ]);
        m
    }) {
        Err(why) => {
tec's avatar
tec committed
154
            error!("Error sending message: {:?}", why);
tec's avatar
tec committed
155
156
157
        }
        Ok(_) => {
            if let Err(why) = msg.delete(ctx) {
tec's avatar
tec committed
158
                error!("Error deleting motion prompt: {:?}", why);
tec's avatar
tec committed
159
160
161
162
163
            }
        }
    }
}

tec's avatar
tec committed
164
165
166
167
168
169
170
171
172
173
174
175
176
#[derive(Debug, Clone)]
struct MotionInfo {
    votes: HashMap<&'static str, Vec<serenity::model::user::User>>,
}

lazy_static! {
    static ref MOTIONS_CACHE: Mutex<HashMap<serenity::model::id::MessageId, MotionInfo>> =
        Mutex::new(HashMap::new());
}

fn get_cached_motion(ctx: &Context, msg: &Message) -> MotionInfo {
    let mut cached_motions = MOTIONS_CACHE.lock().unwrap();
    if !cached_motions.contains_key(&msg.id) {
tec's avatar
tec committed
177
        info!("Initialising representation of motion {:?}", msg.id);
tec's avatar
tec committed
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
        let this_motion = MotionInfo {
            votes: {
                let mut m = HashMap::new();
                m.insert(
                    config::FOR_VOTE,
                    msg.reaction_users(ctx, config::FOR_VOTE, None, None)
                        .unwrap(),
                );
                m.insert(
                    config::AGAINST_VOTE,
                    msg.reaction_users(ctx, config::AGAINST_VOTE, None, None)
                        .unwrap(),
                );
                m.insert(
                    config::ABSTAIN_VOTE,
                    msg.reaction_users(ctx, config::ABSTAIN_VOTE, None, None)
                        .unwrap(),
                );
                m
            },
        };
        cached_motions.insert(msg.id, this_motion);
    }
    return (*cached_motions.get(&msg.id).unwrap()).clone();
}
fn set_cached_motion(id: &serenity::model::id::MessageId, motion_info: MotionInfo) {
    if let Some(motion) = MOTIONS_CACHE.lock().unwrap().get_mut(id) {
        *motion = motion_info;
    } else {
tec's avatar
tec committed
207
        warn!("{}", "Couldn't find motion in cache to set");
tec's avatar
tec committed
208
209
210
    }
}

tec's avatar
tec committed
211
212
213
214
215
216
217
fn update_motion(
    ctx: &Context,
    msg: &mut Message,
    user: &serenity::model::user::User,
    change: &str,
    reaction: channel::Reaction,
) {
tec's avatar
tec committed
218
219
220
221
222
    let motion_info: MotionInfo = get_cached_motion(ctx, msg);

    let for_votes = motion_info.votes.get(config::FOR_VOTE).unwrap().len() as isize - 1;
    let against_votes = motion_info.votes.get(config::AGAINST_VOTE).unwrap().len() as isize - 1;
    let abstain_votes = motion_info.votes.get(config::ABSTAIN_VOTE).unwrap().len() as isize - 1;
tec's avatar
tec committed
223

tec's avatar
tec committed
224
225
226
227
228
    let has_tiebreaker = |users: &Vec<serenity::model::user::User>| {
        users.iter().any(|u| {
            u.has_role(ctx, config::SERVER_ID, config::TIEBREAKER_ROLE)
                .unwrap()
        })
tec's avatar
tec committed
229
230
231
    };

    let for_strength = for_votes as f32
tec's avatar
tec committed
232
        + (if has_tiebreaker(motion_info.votes.get(config::FOR_VOTE).unwrap()) {
tec's avatar
tec committed
233
234
235
236
237
            0.5
        } else {
            0.0
        });
    let against_strength = against_votes as f32
tec's avatar
tec committed
238
        + (if has_tiebreaker(motion_info.votes.get(config::AGAINST_VOTE).unwrap()) {
tec's avatar
tec committed
239
240
241
242
243
            0.5
        } else {
            0.0
        });
    let abstain_strength = abstain_votes as f32
tec's avatar
tec committed
244
        + (if has_tiebreaker(motion_info.votes.get(config::ABSTAIN_VOTE).unwrap()) {
tec's avatar
tec committed
245
246
247
248
249
250
251
252
            0.5
        } else {
            0.0
        });

    let old_embed = msg.embeds[0].clone();
    let topic = old_embed.clone().title.unwrap();

tec's avatar
tec committed
253
    info!(
tec's avatar
tec committed
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
        "  {:10} {:6} {} on {}",
        user.name,
        change,
        reaction.emoji.as_data().as_str(),
        topic
    );

    let update_status = |e: &mut serenity::builder::CreateEmbed,
                         status: &str,
                         last_status_full: String,
                         topic: &str| {
        let last_status = last_status_full.lines().next().expect("No previous status");
        if last_status == status {
            e.field("Status", last_status_full, true);
        } else {
            e.field(
                "Status",
                format!("{}\n_was_ {}", status, last_status_full),
                true,
            );
tec's avatar
tec committed
274
            info!("Motion to {} now {}", topic, status);
tec's avatar
tec committed
275
276
277
278
279
280
281
            //
            let mut message = MessageBuilder::new();
            message.push_bold(topic);
            message.push(" is now ");
            message.push_bold(status);
            message.push_italic(format!(" (was {})", last_status));
            if let Err(why) = config::ANNOUNCEMENT_CHANNEL.say(&ctx.http, message.build()) {
tec's avatar
tec committed
282
                error!("Error sending message: {:?}", why);
tec's avatar
tec committed
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
            };
        }
    };

    if let Err(why) = msg.edit(ctx, |m| {
        m.embed(|e| {
            e.author(|a| {
                let old_author = old_embed.clone().author.expect("Expected author in embed");
                a.name(old_author.name);
                a.icon_url(
                    old_author
                        .icon_url
                        .expect("Expected embed author to have icon"),
                );
                a
            });
            e.title(&topic);
            e.description(old_embed.description.unwrap());
            let last_status_full = old_embed
                .fields
                .iter()
                .filter(|f| f.name == "Status")
                .next()
                .expect("No previous status")
                .clone()
                .value;
            if for_strength > (config::VOTE_POOL_SIZE / 2) as f32 {
                e.colour(serenity::utils::Colour::TEAL);
                update_status(e, "Passed", last_status_full, &topic);
            } else if against_strength + abstain_strength > (config::VOTE_POOL_SIZE / 2) as f32 {
                e.colour(serenity::utils::Colour::RED);
                update_status(e, "Failed", last_status_full, &topic);
            } else {
                e.colour(serenity::utils::Colour::GOLD);
                update_status(e, "Under Consideration", last_status_full, &topic);
            }
            e.field(
                format!(
                    "Votes ({}/{})",
                    for_votes + against_votes + abstain_votes,
                    config::VOTE_POOL_SIZE
                ),
                format!(
                    "For: {}\nAgainst: {}\nAbstain: {}",
                    for_votes, against_votes, abstain_votes
                ),
                true,
            );
            e.timestamp(
                old_embed
                    .timestamp
                    .expect("Expected embed to have timestamp"),
            );
            e
        })
    }) {
tec's avatar
tec committed
339
        error!("Error updating motion: {:?}", why);
tec's avatar
tec committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
    }
}

pub fn reaction_add(ctx: Context, add_reaction: channel::Reaction) {
    match add_reaction.message(&ctx.http) {
        Ok(mut message) => {
            if message.author.id.0 == config::BOT_ID {
                if let Ok(user) = add_reaction.user(&ctx) {
                    match user.has_role(&ctx, config::SERVER_ID, config::VOTE_ROLE) {
                        Ok(true) => {
                            for react in
                                [config::FOR_VOTE, config::AGAINST_VOTE, config::ABSTAIN_VOTE]
                                    .iter()
                                    .filter(|r| r != &&add_reaction.emoji.as_data().as_str())
                            {
                                for a_user in
                                    message.reaction_users(&ctx, *react, None, None).unwrap()
                                {
                                    if a_user.id.0 == user.id.0 {
                                        if let Err(why) = add_reaction.delete(&ctx) {
tec's avatar
tec committed
360
                                            error!("Error deleting react: {:?}", why);
tec's avatar
tec committed
361
                                        };
tec's avatar
tec committed
362
                                        return;
tec's avatar
tec committed
363
364
365
366
367
368
369
                                    }
                                }
                            }
                            if !config::ALLOWED_REACTS
                                .contains(&add_reaction.emoji.as_data().as_str())
                            {
                                if let Err(why) = add_reaction.delete(&ctx) {
tec's avatar
tec committed
370
                                    error!("Error deleting react: {:?}", why);
tec's avatar
tec committed
371
                                };
tec's avatar
tec committed
372
                                return;
tec's avatar
tec committed
373
374
                            }
                            if user.id.0 != config::BOT_ID {
tec's avatar
tec committed
375
376
377
378
379
380
381
382
383
                                let mut motion_info = get_cached_motion(&ctx, &message);
                                if let Some(vote) = motion_info
                                    .votes
                                    .get_mut(add_reaction.emoji.as_data().as_str())
                                {
                                    vote.retain(|u| u.id != user.id);
                                    vote.push(user.clone());
                                }
                                set_cached_motion(&message.id, motion_info);
tec's avatar
tec committed
384
385
386
387
388
389
390
391
392
                                update_motion(&ctx, &mut message, &user, "add", add_reaction);
                            }
                        }
                        Ok(false) => {
                            if user.id.0 != config::BOT_ID {
                                if ![config::APPROVE_REACT, config::DISAPPROVE_REACT]
                                    .contains(&add_reaction.emoji.as_data().as_str())
                                {
                                    if let Err(why) = add_reaction.delete(&ctx) {
tec's avatar
tec committed
393
                                        error!("Error deleting react: {:?}", why);
tec's avatar
tec committed
394
                                    };
tec's avatar
tec committed
395
                                    return;
tec's avatar
tec committed
396
397
398
399
                                }
                            }
                        }
                        Err(why) => {
tec's avatar
tec committed
400
                            error!("Error getting user role: {:?}", why);
tec's avatar
tec committed
401
402
403
404
405
406
                        }
                    }
                }
            }
        }
        Err(why) => {
tec's avatar
tec committed
407
            error!("Error processing react: {:?}", why);
tec's avatar
tec committed
408
409
410
411
412
413
414
415
416
        }
    }
}

pub fn reaction_remove(ctx: Context, removed_reaction: channel::Reaction) {
    match removed_reaction.message(&ctx.http) {
        Ok(mut message) => {
            if message.author.id.0 == config::BOT_ID {
                if let Ok(user) = removed_reaction.user(&ctx) {
tec's avatar
tec committed
417
418
419
420
421
422
423
424
                    let mut motion_info = get_cached_motion(&ctx, &message);
                    if let Some(vote) = motion_info
                        .votes
                        .get_mut(removed_reaction.emoji.as_data().as_str())
                    {
                        vote.retain(|u| u.id != user.id);
                    }
                    set_cached_motion(&message.id, motion_info);
tec's avatar
tec committed
425
426
427
428
429
                    update_motion(&ctx, &mut message, &user, "remove", removed_reaction);
                }
            }
        }
        Err(why) => {
tec's avatar
tec committed
430
            error!("Error getting user role: {:?}", why);
tec's avatar
tec committed
431
432
433
        }
    }
}