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 std::env::args;
8use std::str::FromStr;
9use tokio_xmpp::parsers::{message::MessageType, BareJid, Jid};
10use xmpp::{ClientBuilder, ClientFeature, ClientType, Event};
11
12#[tokio::main]
13async fn main() -> Result<(), Option<()>> {
14 env_logger::init();
15
16 let args: Vec<String> = args().collect();
17 if args.len() != 3 {
18 println!("Usage: {} <jid> <password>", args[0]);
19 return Err(None);
20 }
21
22 let jid = BareJid::from_str(&args[1]).expect(&format!("Invalid JID: {}", &args[1]));
23 let password = &args[2];
24
25 // Client instance
26 let mut client = ClientBuilder::new(jid, password)
27 .set_client(ClientType::Bot, "xmpp-rs")
28 .set_website("https://gitlab.com/xmpp-rs/xmpp-rs")
29 .set_default_nick("bot")
30 .enable_feature(ClientFeature::Avatars)
31 .enable_feature(ClientFeature::ContactList)
32 .enable_feature(ClientFeature::JoinRooms)
33 .build();
34
35 while let Some(events) = client.wait_for_events().await {
36 for event in events {
37 match event {
38 Event::Online => {
39 println!("Online.");
40 }
41 Event::Disconnected(e) => {
42 println!("Disconnected because of {}.", e);
43 return Err(None);
44 }
45 Event::ContactAdded(contact) => {
46 println!("Contact {} added.", contact.jid);
47 }
48 Event::ContactRemoved(contact) => {
49 println!("Contact {} removed.", contact.jid);
50 }
51 Event::ContactChanged(contact) => {
52 println!("Contact {} changed.", contact.jid);
53 }
54 Event::ChatMessage(_id, jid, body, time_info) => {
55 println!("Message from {} at {}: {}", jid, time_info.received, body.0);
56 }
57 Event::JoinRoom(jid, conference) => {
58 println!("Joining room {} ({:?})…", jid, conference.name);
59 client
60 .join_room(
61 jid,
62 conference.nick,
63 conference.password,
64 "en",
65 "Yet another bot!",
66 )
67 .await;
68 }
69 Event::LeaveRoom(jid) => {
70 println!("Leaving room {}…", jid);
71 }
72 Event::LeaveAllRooms => {
73 println!("Leaving all rooms…");
74 }
75 Event::RoomJoined(jid) => {
76 println!("Joined room {}.", jid);
77 client
78 .send_message(Jid::from(jid), MessageType::Groupchat, "en", "Hello world!")
79 .await;
80 }
81 Event::RoomLeft(jid) => {
82 println!("Left room {}.", jid);
83 }
84 Event::RoomMessage(_id, jid, nick, body, time_info) => {
85 println!(
86 "Message in room {} from {} at {}: {}",
87 jid, nick, time_info.received, body.0
88 );
89 }
90 Event::AvatarRetrieved(jid, path) => {
91 println!("Received avatar for {} in {}.", jid, path);
92 }
93 _ => (),
94 }
95 }
96 }
97
98 Ok(())
99}