aboutsummaryrefslogtreecommitdiff
path: root/examples/06_command_framework.rs
blob: 1324a2e46732ccd26c593ba22bd3b0e42f161b23 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
#[macro_use]
extern crate serenity;

use serenity::client::Context;
use serenity::Client;
use serenity::model::Message;
use std::env;

fn main() {
    // Configure the client with your Discord bot token in the environment.
    let token = env::var("DISCORD_TOKEN")
        .expect("Expected a token in the environment");
    let mut client = Client::login_bot(&token);

    client.on_message(|_context, message| {
        println!("Received message: {:?}", message);
    });

    client.on_ready(|_context, ready| {
        println!("{} is connected!", ready.user.name);
    });

    // Commands are equivilant to:
    // "~about"
    // "~emoji cat"
    // "~emoji dog"
    // "~ping"
    // "~some complex command"
    client.with_framework(|f| f
        .configure(|c| c
            .on_mention(true)
            .allow_whitespace(true)
            .prefix("~"))
        .on("ping", ping_command)
        .set_check("ping", owner_check) // Ensure only the owner can run this
        .on("emoji cat", cat_command)
        .on("emoji dog", dog_command)
        .on("multiply", multiply)
        .on("some complex command", some_complex_command)
        // Commands can be in closure-form as well
        .on("about", |context, _message, _args| drop(context.say("A test bot"))));

    let _ = client.start();
}

fn cat_command(context: Context, _msg: Message, _args: Vec<String>) {
    let _ = context.say(":cat:");
}

fn dog_command(context: Context, _msg: Message, _args: Vec<String>) {
    let _ = context.say(":dog:");
}

fn ping_command(_context: Context, message: Message, _args: Vec<String>) {
    let _ = message.reply("Pong!");
}

fn owner_check(_context: &Context, message: &Message) -> bool {
    // Replace 7 with your ID
    message.author.id == 7
}

fn some_complex_command(context: Context, _msg: Message, args: Vec<String>) {
    let _ = context.say(&format!("Arguments: {:?}", args));
}

command!(multiply(context, _message, args, first: f64, second: f64) {
    let res = first * second;

    let _ = context.say(&res.to_string());

    println!("{:?}", args);
});