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
|
use discord::{
model::{
ChannelId,
Event,
},
Discord,
Error,
};
use futures::join;
use tokio::{
sync::mpsc,
task::{
spawn,
spawn_blocking,
},
};
pub async fn handle(
token: Option<String>,
sender: mpsc::UnboundedSender<String>,
mut receiver: mpsc::UnboundedReceiver<String>,
) {
println!("Setting up Discord");
let token = std::env::var("DISCORD_API_TOKEN").unwrap_or(token.unwrap());
let client = Discord::from_bot_token(&token);
if let Ok(client) = client {
let (mut connection, _) = client.connect().expect("discord connect failed"); //TODO
let our_id = client.get_current_user().unwrap().id;
println!("Discord ready");
let (_, _) = join!( //TODO?
spawn_blocking(move || {
loop {
match connection.recv_event() {
Ok(Event::MessageCreate(message)) => {
if message.author.id != our_id {
sender.send(format!("{:?}:{} says: {}",
message.channel_id,
message.author.name,
message.content))
.unwrap();
}
}
Ok(_) => {}
Err(Error::Closed(code, body)) => {
println!("Discord closed with code {:?}: {}", code, body);
break;
}
Err(e) => {
println!("Error: {:?}", e);
}
}
}
}),
spawn(async move {
while let Some(s) = receiver.recv().await {
println!("Discord received '{}'", s);
client.send_message(ChannelId(697057150106599488), //TODO
&s,
"",
false
);
}
})
);
}
}
|