aboutsummaryrefslogtreecommitdiffstats
path: root/src/discord.rs
blob: 3933aba8e3585db5c99193232e3bc558d5c98322 (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
74
75
76
77
78
79
80
81
82
83
84
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
118
119
120
121
122
use crate::agenda::{
    parse_message,
    AgendaPoint
};

use discord::{
    model::{
        ChannelId,
        Event,
        PossibleServer,
    },
    Discord,
    Error,
};
use futures::join;
use std::sync::{
    Arc,
    Mutex,
};
use tokio::{
    sync::mpsc,
    task::{
        spawn,
        spawn_blocking,
    },
};

const TOKEN: Option<&str> = None;
const CHANNEL: Option<u64> = None;

pub async fn handle(
    sender: mpsc::UnboundedSender<AgendaPoint>,
    receiver: mpsc::UnboundedReceiver<AgendaPoint>,
) {
    println!("Setting up Discord");

    let token = std::env::var("DISCORD_API_TOKEN").unwrap_or_else(|_| TOKEN.expect("Missing Discord token").to_string());
    let client = Discord::from_bot_token(&token);

    if let Ok(client) = client {
        let (connection, _) = client.connect().expect("Discord connect failed"); //TODO
        let our_id = client.get_current_user().unwrap().id;
        let client = Arc::new(Mutex::new(client));

        let channel = match std::env::var("DISCORD_CHANNEL") {
            Ok(channel) => Some(ChannelId(channel.parse::<u64>().unwrap())),
            Err(_) => CHANNEL,
        };

        let (_, _) = join!( //TODO?
            spawn(receive_from_slack(receiver, Arc::clone(&client), channel)),
            spawn_blocking(move || receive_events(our_id, connection, sender, client, channel)),
        );
    }
}

fn receive_events(
    _our_id: discord::model::UserId,
    mut connection: discord::Connection,
    sender: mpsc::UnboundedSender<AgendaPoint>,
    client: Arc<Mutex<discord::Discord>>,
    channel: Option<ChannelId>,
) {
    loop {
        match connection.recv_event() {
            Ok(Event::ServerCreate(server)) => {
                if let PossibleServer::Online(server) = server {
                    println!("Discord channels in {}: {:#?}",
                             server.name,
                             server
                             .channels
                             .iter()
                             .map(|channel| format!("{}: {} ({:?})",
                                                    channel.name,
                                                    channel.id,
                                                    channel.kind))
                             .collect::<Vec<_>>());
                }
            }

            Ok(Event::MessageCreate(message)) => {
                if let Some(channel) = channel {
                    if let Ok(Some(s)) = parse_message(
                        &message.content,
                        &message.author.name,
                        &sender,
                    ) {
                        client.lock().unwrap().send_message(channel,
                                                            &s,
                                                            "",
                                                            false).unwrap();
                    }
                }
            }
            Ok(_) => {}
            Err(Error::Closed(code, body)) => {
                println!("Discord closed with code {:?}: {}", code, body);
                break;
            }
            Err(e) => {
                println!("Discord error: {:?}", e);
            }
        }
    }
}

async fn receive_from_slack(
    mut receiver: mpsc::UnboundedReceiver<AgendaPoint>,
    client: Arc<Mutex<discord::Discord>>,
    channel: Option<ChannelId>
) {
    if let Some(channel) = channel {
        while let Some(point) = receiver.recv().await {
            println!("Discord received '{}'", point);
            client.lock().unwrap().send_message(channel,
                                                &point.to_add_message(),
                                                "",
                                                false).unwrap();
        }
    }

}