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::prelude::*;
8use std::env::args;
9use std::process::exit;
10use tokio::runtime::current_thread::Runtime;
11use xmpp_parsers::{message::MessageType, Jid};
12use xmpp::{ClientBuilder, ClientType, ClientFeature, Event};
13
14fn main() {
15 let args: Vec<String> = args().collect();
16 if args.len() != 3 {
17 println!("Usage: {} <jid> <password>", args[0]);
18 exit(1);
19 }
20 let jid = &args[1];
21 let password = &args[2];
22
23 // tokio_core context
24 let mut rt = Runtime::new().unwrap();
25
26 // Client instance
27 let (mut agent, stream) = ClientBuilder::new(jid, password)
28 .set_client(ClientType::Bot, "xmpp-rs")
29 .set_website("https://gitlab.com/xmpp-rs/xmpp-rs")
30 .set_default_nick("bot")
31 .enable_feature(ClientFeature::Avatars)
32 .enable_feature(ClientFeature::ContactList)
33 .enable_feature(ClientFeature::JoinRooms)
34 .build()
35 .unwrap();
36
37 // We return either Some(Error) if an error was encountered
38 // or None, if we were simply disconnected
39 let handler = stream.map_err(Some).for_each(|evt: Event| {
40 match evt {
41 Event::Online => {
42 println!("Online.");
43 },
44 Event::Disconnected => {
45 println!("Disconnected.");
46 return Err(None);
47 },
48 Event::ContactAdded(contact) => {
49 println!("Contact {} added.", contact.jid);
50 },
51 Event::ContactRemoved(contact) => {
52 println!("Contact {} removed.", contact.jid);
53 },
54 Event::ContactChanged(contact) => {
55 println!("Contact {} changed.", contact.jid);
56 },
57 Event::JoinRoom(jid, conference) => {
58 println!("Joining room {} ({:?})…", jid, conference.name);
59 agent.join_room(jid, conference.nick, conference.password, "en", "Yet another bot!");
60 },
61 Event::LeaveRoom(jid) => {
62 println!("Leaving room {}…", jid);
63 },
64 Event::LeaveAllRooms => {
65 println!("Leaving all rooms…");
66 },
67 Event::RoomJoined(jid) => {
68 println!("Joined room {}.", jid);
69 agent.send_message(Jid::Bare(jid), MessageType::Groupchat, "en", "Hello world!");
70 },
71 Event::RoomLeft(jid) => {
72 println!("Left room {}.", jid);
73 },
74 Event::AvatarRetrieved(jid, path) => {
75 println!("Received avatar for {} in {}.", jid, path);
76 },
77 }
78 Ok(())
79 });
80
81 rt.block_on(handler).unwrap_or_else(|e| match e {
82 Some(e) => println!("Error: {:?}", e),
83 None => println!("Disconnected."),
84 });
85}