hello_bot.rs

 1// Copyright (c) 2019 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
 2//
 3// This Source Code Form is subject to the terms of the Mozilla Public
 4// License, v. 2.0. If a copy of the MPL was not distributed with this
 5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
 6
 7use futures::{Future, Stream, sync::mpsc};
 8use std::env::args;
 9use std::process::exit;
10use std::str::FromStr;
11use tokio::runtime::current_thread::Runtime;
12use xmpp_parsers::{Jid, message::MessageType};
13use xmpp::{ClientBuilder, ClientType, ClientFeature, Event};
14
15fn main() {
16    let args: Vec<String> = args().collect();
17    if args.len() != 5 {
18        println!("Usage: {} <jid> <password> <room JID> <nick>", args[0]);
19        exit(1);
20    }
21    let jid = &args[1];
22    let password = &args[2];
23    let room_jid = &args[3];
24    let nick: &str = &args[4];
25
26    // tokio_core context
27    let mut rt = Runtime::new().unwrap();
28
29    let (value_tx, value_rx) = mpsc::unbounded();
30
31    // Client instance
32    let (client, mut agent) = ClientBuilder::new(jid, password)
33        .set_client(ClientType::Bot, "xmpp-rs")
34        .set_website("https://gitlab.com/xmpp-rs/xmpp-rs")
35        .enable_feature(ClientFeature::Avatars)
36        .enable_feature(ClientFeature::ContactList)
37        .build(value_tx)
38        .unwrap();
39
40    let forwarder = value_rx.for_each(|evt: Event| {
41        match evt {
42            Event::Online => {
43                println!("Online.");
44                let room_jid = Jid::from_str(room_jid).unwrap().with_resource(nick);
45                agent.join_room(room_jid, "en", "Yet another bot!");
46            },
47            Event::Disconnected => {
48                println!("Disconnected.");
49                return Err(());
50            },
51            Event::ContactAdded(contact) => {
52                println!("Contact {:?} added.", contact);
53            },
54            Event::ContactRemoved(contact) => {
55                println!("Contact {:?} removed.", contact);
56            },
57            Event::ContactChanged(contact) => {
58                println!("Contact {:?} changed.", contact);
59            },
60            Event::RoomJoined(jid) => {
61                println!("Joined room {}.", jid);
62                agent.send_message(jid.into_bare_jid(), MessageType::Groupchat, "en", "Hello world!");
63            },
64            Event::AvatarRetrieved(jid, path) => {
65                println!("Received avatar for {} in {}.", jid, path);
66            },
67        }
68        Ok(())
69    })
70        .map_err(|e| println!("{:?}", e));
71
72    // Start polling
73    match rt.block_on(client
74        .select2(forwarder)
75        .map(|_| ())
76        .map_err(|_| ())
77    ) {
78        Ok(_) => (),
79        Err(e) => {
80            println!("Fatal: {:?}", e);
81            ()
82        }
83    }
84}