echo_bot.rs

 1use futures::{future, Sink, Stream};
 2use std::env::args;
 3use std::process::exit;
 4use tokio::runtime::current_thread::Runtime;
 5use tokio_xmpp::Client;
 6use xmpp_parsers::{Jid, Element, TryFrom};
 7use xmpp_parsers::message::{Body, Message, MessageType};
 8use xmpp_parsers::presence::{Presence, Show as PresenceShow, Type as PresenceType};
 9
10fn main() {
11    let args: Vec<String> = args().collect();
12    if args.len() != 3 {
13        println!("Usage: {} <jid> <password>", args[0]);
14        exit(1);
15    }
16    let jid = &args[1];
17    let password = &args[2];
18
19    // tokio_core context
20    let mut rt = Runtime::new().unwrap();
21    // Client instance
22    let client = Client::new(jid, password).unwrap();
23
24    // Make the two interfaces for sending and receiving independent
25    // of each other so we can move one into a closure.
26    let (mut sink, stream) = client.split();
27    // Wrap sink in Option so that we can take() it for the send(self)
28    // to consume and return it back when ready.
29    let mut send = move |stanza| {
30        sink.start_send(stanza).expect("start_send");
31    };
32    // Main loop, processes events
33    let done = stream.for_each(|event| {
34        if event.is_online() {
35            println!("Online!");
36
37            let presence = make_presence();
38            send(presence);
39        } else if let Some(message) = event
40            .into_stanza()
41            .and_then(|stanza| Message::try_from(stanza).ok())
42        {
43            // This is a message we'll echo
44            match (message.from, message.bodies.get("")) {
45                (Some(from), Some(body)) => {
46                    if message.type_ != MessageType::Error {
47                        let reply = make_reply(from, &body.0);
48                        send(reply);
49                    }
50                }
51                _ => (),
52            }
53        }
54
55        Box::new(future::ok(()))
56    });
57
58    // Start polling `done`
59    match rt.block_on(done) {
60        Ok(_) => (),
61        Err(e) => {
62            println!("Fatal: {}", e);
63            ()
64        }
65    }
66}
67
68// Construct a <presence/>
69fn make_presence() -> Element {
70    let mut presence = Presence::new(PresenceType::None);
71    presence.show = PresenceShow::Chat;
72    presence
73        .statuses
74        .insert(String::from("en"), String::from("Echoing messages."));
75    presence.into()
76}
77
78// Construct a chat <message/>
79fn make_reply(to: Jid, body: &str) -> Element {
80    let mut message = Message::new(Some(to));
81    message.bodies.insert(String::new(), Body(body.to_owned()));
82    message.into()
83}