main.rs 20.5 KB
Newer Older
tec's avatar
tec committed
1
2
3
4
5
6
use serenity::{
    model::{channel, channel::Message, gateway::Ready, guild::Member},
    prelude::*,
    utils::MessageBuilder,
};

tec's avatar
tec committed
7
8
use rand::Rng;

9
10
static DISCORD_TOKEN: &str = include_str!("discord_token");

tec's avatar
tec committed
11
static SERVER_ID: u64 = 606351521117896704;
tec's avatar
tec committed
12
// #general
tec's avatar
tec committed
13
static MAIN_CHANNEL: serenity::model::id::ChannelId =
tec's avatar
tec committed
14
15
    serenity::model::id::ChannelId(606351521117896706);
// #the-corner
tec's avatar
tec committed
16
static WELCOME_CHANNEL: serenity::model::id::ChannelId =
tec's avatar
tec committed
17
    serenity::model::id::ChannelId(606351613816209418);
tec's avatar
tec committed
18
19
20
// #general
static ANNOUNCEMENT_CHANNEL: serenity::model::id::ChannelId =
    serenity::model::id::ChannelId(606351521117896706);
tec's avatar
tec committed
21

tec's avatar
tec committed
22
static BOT_ID: u64 = 607078903969742848;
tec's avatar
tec committed
23

tec's avatar
tec committed
24
25
26
static VOTE_POOL_SIZE: i8 = 2;
static VOTE_ROLE: u64 = 607478818038480937;
static TIEBREAKER_ROLE: u64 = 607509283483025409;
tec's avatar
tec committed
27
28
static UNREGISTERED_MEMBER_ROLE: u64 = 608282247350714408;
static REGISTERED_MEMBER_ROLE: u64 = 608282133118582815;
tec's avatar
tec committed
29

tec's avatar
tec committed
30
31
32
static FOR_VOTE: &str = "👍";
static AGAINST_VOTE: &str = "👎";
static ABSTAIN_VOTE: &str = "🙊";
tec's avatar
tec committed
33
34
35
36
37
38
39
40
41
42
43
static APPROVE_REACT: &str = "⬆";
static DISAPPROVE_REACT: &str = "⬇";
static UNSURE_REACT: &str = "❔";
static ALLOWED_REACTS: &[&'static str] = &[
    FOR_VOTE,
    AGAINST_VOTE,
    ABSTAIN_VOTE,
    APPROVE_REACT,
    DISAPPROVE_REACT,
    UNSURE_REACT,
];
tec's avatar
tec committed
44

Tom Almeida's avatar
Tom Almeida committed
45
46
47
48
macro_rules! e {
    ($error: literal, $x:expr) => {
        match $x {
            Ok(_) => (),
49
            Err(why) => eprintln!($error, why),
Tom Almeida's avatar
Tom Almeida committed
50
        }
51
    };
Tom Almeida's avatar
Tom Almeida committed
52
53
54
55
}

struct Handler;

tec's avatar
tec committed
56
57
58
59
60
61
62
63
impl EventHandler for Handler {
    // Set a handler for the `message` event - so that whenever a new message
    // is received - the closure (or function) passed will be called.
    //
    // Event handlers are dispatched through a threadpool, and so multiple
    // events can be dispatched simultaneously.
    fn message(&self, ctx: Context, msg: Message) {
        if msg.author.id.0 == 159652921083035648 {
tec's avatar
tec committed
64
            let mut rng = rand::thread_rng();
tec's avatar
tec committed
65
            let mut message = MessageBuilder::new();
tec's avatar
tec committed
66
67
            message.push(
                [
tec's avatar
tec committed
68
                    "That's quite enough from you ",
tec's avatar
tec committed
69
70
71
                    "Why do you continue to bother us ",
                    "Oh. It's you again ",
                    "What are you doing ",
tec's avatar
tec committed
72
                ][rng.gen_range(0, 4)],
tec's avatar
tec committed
73
            );
tec's avatar
tec committed
74
75
76
77
78
            message.mention(&msg.author);
            if let Err(why) = msg.channel_id.say(&ctx.http, message.build()) {
                println!("Error sending message: {:?}", why);
            }
        }
Tom Almeida's avatar
Tom Almeida committed
79
80
81
82

        let message_content: Vec<_> = msg.content.splitn(2, ' ').collect();
        match message_content[0] {
            "!join" => {
83
84
85
86
87
88
89
                e!(
                    "Unable to get user: {:?}",
                    serenity::model::id::GuildId(SERVER_ID)
                        .member(ctx.http.clone(), msg.author.id)
                        .map(|member| new_member(&ctx, member))
                );
            }
Tom Almeida's avatar
Tom Almeida committed
90
91
92
93
94
            "!move" => {
                let motion = message_content[1];
                if motion.len() > 0 {
                    create_motion(&ctx, &msg, motion);
                } else {
Tom Almeida's avatar
Tom Almeida committed
95
96
                    e!("Error sending message: {:?}",
                       msg.channel_id.say(
Tom Almeida's avatar
Tom Almeida committed
97
98
                        &ctx.http,
                        "If there's something you want to motion, put it after the !move keyword",
Tom Almeida's avatar
Tom Almeida committed
99
                    ));
tec's avatar
tec committed
100
                }
101
            }
Tom Almeida's avatar
Tom Almeida committed
102
            "!motion" => {
Tom Almeida's avatar
Tom Almeida committed
103
104
                e!("Error sending message: {:?}",
                   msg.channel_id.say(
tec's avatar
tec committed
105
                    &ctx.http,
Tom Almeida's avatar
Tom Almeida committed
106
                    "I hope you're not having a motion. You may have wanted to !move something instead."
Tom Almeida's avatar
Tom Almeida committed
107
                ));
108
            }
Tom Almeida's avatar
Tom Almeida committed
109
110
111
            "!poll" => {
                let topic = message_content[1];
                if topic.len() > 0 {
Tom Almeida's avatar
Tom Almeida committed
112
                    create_poll(&ctx, &msg, topic);
Tom Almeida's avatar
Tom Almeida committed
113
                } else {
Tom Almeida's avatar
Tom Almeida committed
114
115
                    e!("Error sending message: {:?}",
                       msg.channel_id.say(
Tom Almeida's avatar
Tom Almeida committed
116
117
                        &ctx.http,
                        "If there's something you want to motion, put it after the !move keyword",
Tom Almeida's avatar
Tom Almeida committed
118
                    ));
tec's avatar
tec committed
119
                }
120
            }
Tom Almeida's avatar
Tom Almeida committed
121
122
123
            "!register" => {
                let name = message_content[1];
                if name.len() > 0 {
124
125
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
154
155
156
157
158
159
                    e!(
                        "Unable to get member: {:?}",
                        serenity::model::id::GuildId(SERVER_ID)
                            .member(ctx.http.clone(), msg.author.id)
                            .map(|mut member| {
                                e!(
                                    "Unable to remove role: {:?}",
                                    member.remove_role(&ctx.http, UNREGISTERED_MEMBER_ROLE)
                                );
                                e!(
                                    "Unable to edit nickname: {:?}",
                                    member
                                        .edit(&ctx.http, |m| {
                                            let mut rng = rand::thread_rng();
                                            m.nickname(format!(
                                                "{}, {}",
                                                name,
                                                [
                                                    "The Big Cheese",
                                                    "The One and Only",
                                                    "The Exalted One",
                                                    "not to be trusted",
                                                    "The Scoundrel",
                                                    "A big fish in a small pond",
                                                ][rng.gen_range(0, 5)]
                                            ));
                                            m
                                        })
                                        .map(|()| {
                                            e!(
                                                "Unable to add role: {:?}",
                                                member.add_role(&ctx.http, REGISTERED_MEMBER_ROLE)
                                            );
                                        })
                                );
                            })
Tom Almeida's avatar
Tom Almeida committed
160
                    );
161
                    e!("Error deleting register message: {:?}", msg.delete(ctx));
Tom Almeida's avatar
Tom Almeida committed
162
                } else {
163
164
165
166
167
                    e!(
                        "Error sending message: {:?}",
                        msg.channel_id
                            .say(&ctx.http, "Usage: !register <ucc username>")
                    );
tec's avatar
tec committed
168
                }
169
            }
Tom Almeida's avatar
Tom Almeida committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
            "!cowsay" => {
                let mut text = message_content[1].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,
                );
186
187
188
189
190
                e!(
                    "Error sending message: {:?}",
                    msg.channel_id.say(&ctx.http, message.build())
                );
            }
Tom Almeida's avatar
Tom Almeida committed
191
192
193
194
            "!help" => {
                let mut message = MessageBuilder::new();
                message.push_line("Use !move <action> to make a circular motion");
                message.push_line("Use !poll <proposal> to see what people think about something");
195
196
197
198
199
                e!(
                    "Error sending message: {:?}",
                    msg.channel_id.say(&ctx.http, message.build())
                );
            }
Tom Almeida's avatar
Tom Almeida committed
200
            _ => {}
tec's avatar
tec committed
201
202
203
        }
    }

tec's avatar
tec committed
204
205
206
207
208
209
210
    fn reaction_add(&self, ctx: Context, add_reaction: channel::Reaction) {
        match add_reaction.message(&ctx.http) {
            Ok(mut message) => {
                if message.author.id.0 == BOT_ID {
                    if let Ok(user) = add_reaction.user(&ctx) {
                        match user.has_role(&ctx, SERVER_ID, VOTE_ROLE) {
                            Ok(true) => {
tec's avatar
tec committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
                                for react in [FOR_VOTE, AGAINST_VOTE, 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) {
                                                println!("Error deleting react: {:?}", why);
                                            };
                                        }
                                    }
                                }
                                if !ALLOWED_REACTS.contains(&add_reaction.emoji.as_data().as_str())
                                {
                                    if let Err(why) = add_reaction.delete(&ctx) {
                                        println!("Error deleting react: {:?}", why);
                                    };
                                }
                                if user.id.0 != BOT_ID {
                                    update_motion(&ctx, &mut message, &user, "add", add_reaction);
                                }
tec's avatar
tec committed
234
235
236
                            }
                            Ok(false) => {
                                if user.id.0 != BOT_ID {
237
238
239
240
241
242
243
                                    if ![APPROVE_REACT, DISAPPROVE_REACT]
                                        .contains(&add_reaction.emoji.as_data().as_str())
                                    {
                                        if let Err(why) = add_reaction.delete(&ctx) {
                                            println!("Error deleting react: {:?}", why);
                                        };
                                    }
tec's avatar
tec committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
                                }
                            }
                            Err(why) => {
                                println!("Error getting user role: {:?}", why);
                            }
                        }
                    }
                }
            }
            Err(why) => {
                println!("Error processing react: {:?}", why);
            }
        }
    }

tec's avatar
tec committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
    fn reaction_remove(&self, ctx: Context, removed_reaction: channel::Reaction) {
        match removed_reaction.message(&ctx.http) {
            Ok(mut message) => {
                if message.author.id.0 == BOT_ID {
                    if let Ok(user) = removed_reaction.user(&ctx) {
                        update_motion(&ctx, &mut message, &user, "remove", removed_reaction);
                    }
                }
            }
            Err(why) => {
                println!("Error getting user role: {:?}", why);
            }
        }
    }

tec's avatar
tec committed
274
275
276
277
    fn guild_member_addition(
        &self,
        ctx: Context,
        _guild_id: serenity::model::id::GuildId,
tec's avatar
tec committed
278
        the_new_member: Member,
tec's avatar
tec committed
279
    ) {
tec's avatar
tec committed
280
        new_member(&ctx, the_new_member);
tec's avatar
tec committed
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
    }

    // Set a handler to be called on the `ready` event. This is called when a
    // shard is booted, and a READY payload is sent by Discord. This payload
    // contains data like the current user's guild Ids, current user data,
    // private channels, and more.
    //
    // In this case, just print what the current user's username is.
    fn ready(&self, _: Context, ready: Ready) {
        println!("{} is connected!", ready.user.name);
    }
}

fn main() {
    // Configure the client with your Discord bot token in the environment.
296
    let token = DISCORD_TOKEN;
tec's avatar
tec committed
297
298
299
300
301
302
303
304
305
306
307
308
309
310

    // Create a new instance of the Client, logging in as a bot. This will
    // automatically prepend your bot token with "Bot ", which is a requirement
    // by Discord for bot users.
    let mut client = Client::new(&token, Handler).expect("Err creating client");

    // Finally, start a single shard, and start listening to events.
    //
    // Shards will automatically attempt to reconnect, and will perform
    // exponential backoff until it reconnects.
    if let Err(why) = client.start() {
        println!("Client error: {:?}", why);
    }
}
tec's avatar
tec committed
311
312

fn create_motion(ctx: &Context, msg: &Message, topic: &str) {
tec's avatar
tec committed
313
    println!("{} created a motion {}", msg.author.name, topic);
tec's avatar
tec committed
314
315
    match msg.channel_id.send_message(&ctx.http, |m| {
        m.embed(|embed| {
tec's avatar
tec committed
316
317
318
319
320
321
322
323
324
            embed.author(|a| {
                a.name(&msg.author.name);
                a.icon_url(
                    msg.author
                        .static_avatar_url()
                        .expect("Expected author to have avatar"),
                );
                a
            });
tec's avatar
tec committed
325
326
327
            embed.colour(serenity::utils::Colour::GOLD);
            embed.title(format!("Motion to {}", topic));
            let mut desc = MessageBuilder::new();
tec's avatar
tec committed
328
329
            desc.role(VOTE_ROLE);
            desc.push(" take a look at this motion from ");
tec's avatar
tec committed
330
331
332
            desc.mention(&msg.author);
            embed.description(desc.build());
            embed.field("Status", "Under Consideration", true);
tec's avatar
tec committed
333
            embed.field("Votes", "For: 0\nAgainst: 0\nAbstain: 0", true);
tec's avatar
tec committed
334
335
            embed
        });
336
337
338
339
340
341
342
        m.reactions(vec![
            FOR_VOTE,
            AGAINST_VOTE,
            ABSTAIN_VOTE,
            APPROVE_REACT,
            DISAPPROVE_REACT,
        ]);
tec's avatar
tec committed
343
344
345
346
347
        m
    }) {
        Err(why) => {
            println!("Error sending message: {:?}", why);
        }
tec's avatar
tec committed
348
349
350
        Ok(_) => {
            if let Err(why) = msg.delete(ctx) {
                println!("Error deleting motion prompt: {:?}", why);
tec's avatar
tec committed
351
352
353
354
355
            }
        }
    }
}

tec's avatar
tec committed
356
357
358
359
fn create_poll(ctx: &Context, msg: &Message, topic: &str) {
    println!("{} created a poll {}", msg.author.name, topic);
    match msg.channel_id.send_message(&ctx.http, |m| {
        m.embed(|embed| {
tec's avatar
tec committed
360
361
362
363
364
365
366
367
368
            embed.author(|a| {
                a.name(&msg.author.name);
                a.icon_url(
                    msg.author
                        .static_avatar_url()
                        .expect("Expected author to have avatar"),
                );
                a
            });
tec's avatar
tec committed
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
            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
        });
        m.reactions(vec![APPROVE_REACT, DISAPPROVE_REACT, UNSURE_REACT]);
        m
    }) {
        Err(why) => {
            println!("Error sending message: {:?}", why);
        }
        Ok(_) => {
            if let Err(why) = msg.delete(ctx) {
                println!("Error deleting motion prompt: {:?}", why);
            }
        }
    }
}

tec's avatar
tec committed
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
fn update_motion(
    ctx: &Context,
    msg: &mut Message,
    user: &serenity::model::user::User,
    change: &str,
    reaction: channel::Reaction,
) {
    let for_votes = msg.reaction_users(ctx, FOR_VOTE, None, None).unwrap().len() as isize - 1;
    let against_votes = msg
        .reaction_users(ctx, AGAINST_VOTE, None, None)
        .unwrap()
        .len() as isize
        - 1;
    let abstain_votes = msg
        .reaction_users(ctx, ABSTAIN_VOTE, None, None)
        .unwrap()
        .len() as isize
        - 1;

    let strength_buff = |react: &str| {
        msg.reaction_users(ctx, react, None, None)
            .unwrap()
            .iter()
            .filter(|u| match u.has_role(ctx, SERVER_ID, TIEBREAKER_ROLE) {
                Ok(true) => true,
                _ => false,
            })
            .count()
            > 0
    };

    let for_strength = for_votes as f32 + (if strength_buff(FOR_VOTE) { 0.5 } else { 0.0 });
    let against_strength = against_votes as f32
        + (if strength_buff(AGAINST_VOTE) {
            0.5
        } else {
            0.0
        });
    let abstain_strength = abstain_votes as f32
        + (if strength_buff(ABSTAIN_VOTE) {
            0.5
        } else {
            0.0
        });

tec's avatar
tec committed
436
    let old_embed = msg.embeds[0].clone();
tec's avatar
tec committed
437
    let topic = old_embed.clone().title.unwrap();
tec's avatar
tec committed
438

tec's avatar
tec committed
439
440
441
442
443
444
445
    println!(
        "  {:10} {:6} {} on {}",
        user.name,
        change,
        reaction.emoji.as_data().as_str(),
        topic
    );
tec's avatar
tec committed
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472

    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,
            );
            println!("Motion to {} now {}", topic, status);
            //
            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) = ANNOUNCEMENT_CHANNEL.say(&ctx.http, message.build()) {
                println!("Error sending message: {:?}", why);
            };
        }
    };

tec's avatar
tec committed
473
474
    if let Err(why) = msg.edit(ctx, |m| {
        m.embed(|e| {
tec's avatar
tec committed
475
476
477
478
479
480
481
482
483
484
            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
            });
tec's avatar
tec committed
485
            e.title(&topic);
tec's avatar
tec committed
486
            e.description(old_embed.description.unwrap());
tec's avatar
tec committed
487
            let last_status_full = old_embed
tec's avatar
tec committed
488
489
490
491
492
493
494
495
496
                .fields
                .iter()
                .filter(|f| f.name == "Status")
                .next()
                .expect("No previous status")
                .clone()
                .value;
            if for_strength > (VOTE_POOL_SIZE / 2) as f32 {
                e.colour(serenity::utils::Colour::TEAL);
tec's avatar
tec committed
497
                update_status(e, "Passed", last_status_full, &topic);
tec's avatar
tec committed
498
499
            } else if against_strength + abstain_strength > (VOTE_POOL_SIZE / 2) as f32 {
                e.colour(serenity::utils::Colour::RED);
tec's avatar
tec committed
500
                update_status(e, "Failed", last_status_full, &topic);
tec's avatar
tec committed
501
502
            } else {
                e.colour(serenity::utils::Colour::GOLD);
tec's avatar
tec committed
503
                update_status(e, "Under Consideration", last_status_full, &topic);
tec's avatar
tec committed
504
505
506
507
508
509
510
511
512
513
514
515
516
            }
            e.field(
                format!(
                    "Votes ({}/{})",
                    for_votes + against_votes + abstain_votes,
                    VOTE_POOL_SIZE
                ),
                format!(
                    "For: {}\nAgainst: {}\nAbstain: {}",
                    for_votes, against_votes, abstain_votes
                ),
                true,
            );
tec's avatar
tec committed
517
518
519
520
521
522
            e
        })
    }) {
        println!("Error updating motion: {:?}", why);
    }
}
tec's avatar
tec committed
523
524
525
526
527
528
529
530
531
532
533
534
535

fn new_member(ctx: &Context, mut new_member: Member) {
    let mut message = MessageBuilder::new();
    message.push("Nice to see you here ");
    message.mention(&new_member);
    message.push_line("! Would you care to introduce yourself?");
    message.push_line("If you're not sure where to start, perhaps you could tell us about your projects, your first computer…");
    message.push_line("You should also know that we follow the Freenode Channel Guidelines: https://freenode.net/changuide");
    if let Err(why) = WELCOME_CHANNEL.say(&ctx, message.build()) {
        println!("Error sending message: {:?}", why);
    }

    let mut message = MessageBuilder::new();
tec's avatar
tec committed
536
    message.push(format!("Say hi to {} in ", new_member.display_name()));
tec's avatar
tec committed
537
538
539
540
541
542
543
544
545
    message.mention(&WELCOME_CHANNEL);
    if let Err(why) = MAIN_CHANNEL.say(&ctx, message.build()) {
        println!("Error sending message: {:?}", why);
    }

    if let Err(why) = new_member.add_role(&ctx.http, UNREGISTERED_MEMBER_ROLE) {
        println!("Error adding user role: {:?}", why);
    };
}