Skip to main content

slack_example/
slack_example.rs

1//
2// Copyright 2014-2016 the slack-rs authors.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16//
17// This is a simple example of using slack-rs.
18// You can run it with `cargo run --example slack_example -- <api_key>`
19//
20// NOTE: Only classic app bots can connect to rtm https://api.slack.com/rtm#classic
21//
22// NOTE: This will post in the #general channel of the account you connect
23// to.
24//
25
26use slack;
27use slack::{Event, RtmClient};
28
29struct MyHandler;
30
31#[allow(unused_variables)]
32impl slack::EventHandler for MyHandler {
33    fn on_event(&mut self, cli: &RtmClient, event: Event) {
34        println!("on_event(event: {:?})", event);
35        if let Event::Hello = event {
36            // find the general channel id from the `StartResponse`
37            let general_channel_id = cli
38                .start_response()
39                .channels
40                .as_ref()
41                .and_then(|channels| {
42                    channels.iter().find(|chan| match chan.name {
43                        None => false,
44                        Some(ref name) => name == "general",
45                    })
46                })
47                .and_then(|chan| chan.id.as_ref())
48                .expect("general channel not found");
49            let _ = cli
50                .sender()
51                .send_message(&general_channel_id, "Hello world! (rtm)");
52            // Send a message over the real time api websocket
53        }
54    }
55
56    fn on_close(&mut self, cli: &RtmClient) {
57        println!("on_close");
58    }
59
60    fn on_connect(&mut self, cli: &RtmClient) {
61        println!("on_connect");
62    }
63}
64
65fn main() {
66    let args: Vec<String> = std::env::args().collect();
67    let api_key = match args.len() {
68        0 | 1 => {
69            panic!("No api-key in args! Usage: cargo run --example slack_example -- <api-key>")
70        }
71        x => args[x - 1].clone(),
72    };
73    let mut handler = MyHandler;
74    let r = RtmClient::login_and_run(&api_key, &mut handler);
75    match r {
76        Ok(_) => {}
77        Err(err) => panic!("Error: {}", err),
78    }
79}