voting.rs 14.8 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
        }
    };
}

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);
tec's avatar
tec committed
26
            return;
tec's avatar
tec committed
27
        }
tec's avatar
tec committed
28 29 30 31 32 33 34
        e!(
            "Error sending message: {:?}",
            msg.channel_id.say(
                &ctx.http,
                "If there's something you want to motion, put it after the !move keyword",
            )
        );
tec's avatar
tec committed
35 36 37 38 39 40 41 42 43 44 45 46
    }
    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);
tec's avatar
tec committed
47
            return;
tec's avatar
tec committed
48
        }
tec's avatar
tec committed
49 50 51 52 53 54 55
        e!(
            "Error sending message: {:?}",
            msg.channel_id.say(
                &ctx.http,
                "If there's something you want to motion, put it after the !move keyword",
            )
        );
tec's avatar
tec committed
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 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
        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;
tec's avatar
tec committed
206
        return;
tec's avatar
tec committed
207
    }
tec's avatar
tec committed
208
    warn!("{}", "Couldn't find motion in cache to set");
tec's avatar
tec committed
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
            0.25
tec's avatar
tec committed
234 235 236 237
        } 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
            0.25
tec's avatar
tec committed
240 241 242 243
        } 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
            0.25
tec's avatar
tec committed
246 247 248 249 250 251 252
        } 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
            };
        }
    };

    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;
309
            if for_strength > (config::VOTE_POOL_SIZE as f32 / 2.0) {
tec's avatar
tec committed
310 311
                e.colour(serenity::utils::Colour::TEAL);
                update_status(e, "Passed", last_status_full, &topic);
312
            } else if against_strength + abstain_strength > (config::VOTE_POOL_SIZE as f32 / 2.0) {
tec's avatar
tec committed
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
                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
    }
}

pub fn reaction_add(ctx: Context, add_reaction: channel::Reaction) {
    match add_reaction.message(&ctx.http) {
        Ok(mut message) => {
tec's avatar
tec committed
346 347 348
            if let Ok(user) = add_reaction.user(&ctx) {
                match user.has_role(&ctx, config::SERVER_ID, config::VOTE_ROLE) {
                    Ok(true) => {
tec's avatar
tec committed
349
                        // remove vote if already voted
tec's avatar
tec committed
350 351 352 353 354
                        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()
tec's avatar
tec committed
355
                            {
tec's avatar
tec committed
356 357 358 359
                                if a_user.id.0 == user.id.0 {
                                    if let Err(why) = add_reaction.delete(&ctx) {
                                        error!("Error deleting react: {:?}", why);
                                    };
tec's avatar
tec committed
360
                                    return;
tec's avatar
tec committed
361 362
                                }
                            }
tec's avatar
tec committed
363
                        }
tec's avatar
tec committed
364
                        // remove 'illegal' reacts
tec's avatar
tec committed
365 366 367 368 369 370 371
                        if !config::ALLOWED_REACTS.contains(&add_reaction.emoji.as_data().as_str())
                        {
                            if let Err(why) = add_reaction.delete(&ctx) {
                                error!("Error deleting react: {:?}", why);
                            };
                            return;
                        }
tec's avatar
tec committed
372 373 374 375 376 377 378 379
                        // update motion
                        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());
tec's avatar
tec committed
380
                        }
tec's avatar
tec committed
381 382
                        set_cached_motion(&message.id, motion_info);
                        update_motion(&ctx, &mut message, &user, "add", add_reaction);
tec's avatar
tec committed
383 384
                    }
                    Ok(false) => {
tec's avatar
tec committed
385 386 387 388 389 390 391
                        if ![config::APPROVE_REACT, config::DISAPPROVE_REACT]
                            .contains(&add_reaction.emoji.as_data().as_str())
                        {
                            if let Err(why) = add_reaction.delete(&ctx) {
                                error!("Error deleting react: {:?}", why);
                            };
                            return;
tec's avatar
tec committed
392 393
                        }
                    }
tec's avatar
tec committed
394 395 396
                    Err(why) => {
                        error!("Error getting user role: {:?}", why);
                    }
tec's avatar
tec committed
397 398 399 400
                }
            }
        }
        Err(why) => {
tec's avatar
tec committed
401
            error!("Error processing react: {:?}", why);
tec's avatar
tec committed
402 403 404 405 406 407 408
        }
    }
}

pub fn reaction_remove(ctx: Context, removed_reaction: channel::Reaction) {
    match removed_reaction.message(&ctx.http) {
        Ok(mut message) => {
tec's avatar
tec committed
409 410 411 412 413 414 415
            if let Ok(user) = removed_reaction.user(&ctx) {
                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);
tec's avatar
tec committed
416
                }
tec's avatar
tec committed
417 418
                set_cached_motion(&message.id, motion_info);
                update_motion(&ctx, &mut message, &user, "remove", removed_reaction);
tec's avatar
tec committed
419 420 421
            }
        }
        Err(why) => {
tec's avatar
tec committed
422
            error!("Error getting user role: {:?}", why);
tec's avatar
tec committed
423 424 425
        }
    }
}