Struct Api

Source
pub struct Api { /* private fields */ }
Expand description

Main type for sending requests to the Telegram bot API.

Implementations§

Source§

impl Api

Source

pub fn new<T: AsRef<str>>(token: T) -> Result<Self, Error>

Start construction of the Api instance.

§Examples

Using default connector.

use telegram_bot_fork::Api;

let api = Api::new(telegram_token).unwrap();

Using custom connector.

use telegram_bot_fork::{connector::hyper, Api};

let api = Api::with_connector(telegram_token, hyper::default_connector().unwrap());
Examples found in repository?
examples/get_me.rs (line 16)
11fn main() {
12    tokio::runtime::current_thread::Runtime::new()
13        .unwrap()
14        .block_on(lazy(|| {
15            let token = env::var("TELEGRAM_BOT_TOKEN").unwrap();
16            let api = Api::new(token).unwrap();
17
18            tokio::executor::current_thread::spawn(api.send(GetMe).then(|r| {
19                println!("{:?}", r);
20
21                Ok(())
22            }));
23
24            Ok::<_, Error>(())
25        }))
26        .unwrap();
27}
More examples
Hide additional examples
examples/errors.rs (line 16)
11fn main() {
12    tokio::runtime::current_thread::Runtime::new()
13        .unwrap()
14        .block_on(lazy(|| {
15            let token = env::var("TELEGRAM_BOT_TOKEN").unwrap();
16            let api = Api::new(token).unwrap();
17
18            // Convert stream to the stream with errors in result
19            let stream = api.stream().then(|mb_update| {
20                let res: Result<Result<Update, Error>, ()> = Ok(mb_update);
21                res
22            });
23
24            // Print update or error for each update.
25            stream.for_each(|mb_update| {
26                println!("{:?}", mb_update);
27
28                Ok(())
29            })
30        }))
31        .unwrap();
32}
examples/features.rs (line 181)
176fn main() {
177    tokio::runtime::current_thread::Runtime::new()
178        .unwrap()
179        .block_on(lazy(|| {
180            let token = env::var("TELEGRAM_BOT_TOKEN").unwrap();
181            let api = Api::new(token).unwrap();
182
183            let stream = api.stream().then(|mb_update| {
184                let res: Result<Result<Update, Error>, ()> = Ok(mb_update);
185                res
186            });
187
188            stream.for_each(move |update| {
189                match update {
190                    Ok(update) => {
191                        if let UpdateKind::Message(message) = update.kind {
192                            test(api.clone(), message)
193                        }
194                    }
195                    Err(_) => {}
196                }
197
198                Ok(())
199            })
200        }))
201        .unwrap();
202}
examples/pin.rs (line 29)
24fn main() {
25    tokio::runtime::current_thread::Runtime::new()
26        .unwrap()
27        .block_on(lazy(|| {
28            let token = env::var("TELEGRAM_BOT_TOKEN").unwrap();
29            let api = Api::new(token).unwrap();
30
31            let stream = api.stream().then(|mb_update| {
32                let res: Result<Result<Update, Error>, ()> = Ok(mb_update);
33                res
34            });
35
36            stream.for_each(move |update| {
37                match update {
38                    Ok(update) => {
39                        if let UpdateKind::Message(message) = update.kind {
40                            process(api.clone(), message)
41                        }
42                    }
43                    Err(_) => {}
44                }
45
46                Ok(())
47            })
48        }))
49        .unwrap();
50}
examples/live_location.rs (line 42)
37fn main() {
38    tokio::runtime::current_thread::Runtime::new()
39        .unwrap()
40        .block_on(lazy(|| {
41            let token = env::var("TELEGRAM_BOT_TOKEN").unwrap();
42            let api = Api::new(token).unwrap();
43
44            let stream = api.stream().then(|mb_update| {
45                let res: Result<Result<Update, Error>, ()> = Ok(mb_update);
46                res
47            });
48
49            stream.for_each(move |update| {
50                match update {
51                    Ok(update) => {
52                        if let UpdateKind::Message(message) = update.kind {
53                            if let MessageKind::Text { ref data, .. } = message.kind {
54                                match data.as_str() {
55                                    "/livelocation" => test(api.clone(), message.clone()),
56                                    _ => (),
57                                }
58                            }
59                        }
60                    }
61                    Err(_) => {}
62                }
63
64                Ok(())
65            })
66        }))
67        .unwrap();
68}
examples/simple.rs (line 16)
11fn main() {
12    tokio::runtime::current_thread::Runtime::new()
13        .unwrap()
14        .block_on(lazy(|| {
15            let token = env::var("TELEGRAM_BOT_TOKEN").unwrap();
16            let api = Api::new(token).unwrap();
17
18            let stream = api.stream().then(|mb_update| {
19                let res: Result<Result<Update, Error>, ()> = Ok(mb_update);
20                res
21            });
22
23            // Print update or error for each update.
24            stream.for_each(move |update| {
25                match update {
26                    Ok(update) => {
27                        // If the received update contains a new message...
28                        if let UpdateKind::Message(message) = update.kind {
29                            if let MessageKind::Text { ref data, .. } = message.kind {
30                                // Print received text message to stdout.
31                                println!("<{}>: {}", &message.from.first_name, data);
32
33                                // Answer message with "Hi".
34                                api.spawn(message.text_reply(format!(
35                                    "Hi, {}! You just wrote '{}'",
36                                    &message.from.first_name, data
37                                )));
38                            }
39                        }
40                    }
41                    Err(_) => {}
42                }
43
44                Ok(())
45            })
46        }))
47        .unwrap();
48}
Source

pub fn with_connector<T: AsRef<str>>( token: T, connector: Box<dyn Connector>, ) -> Self

Source

pub fn set_url<T: AsRef<str>>(&mut self, url: T) -> &mut Self

Source

pub fn stream(&self) -> UpdatesStream

Create a stream which produces updates from the Telegram server.

§Examples
use futures::Stream;

let future = api.stream().for_each(|update| {
    println!("{:?}", update);
    Ok(())
});
Examples found in repository?
examples/errors.rs (line 19)
11fn main() {
12    tokio::runtime::current_thread::Runtime::new()
13        .unwrap()
14        .block_on(lazy(|| {
15            let token = env::var("TELEGRAM_BOT_TOKEN").unwrap();
16            let api = Api::new(token).unwrap();
17
18            // Convert stream to the stream with errors in result
19            let stream = api.stream().then(|mb_update| {
20                let res: Result<Result<Update, Error>, ()> = Ok(mb_update);
21                res
22            });
23
24            // Print update or error for each update.
25            stream.for_each(|mb_update| {
26                println!("{:?}", mb_update);
27
28                Ok(())
29            })
30        }))
31        .unwrap();
32}
More examples
Hide additional examples
examples/features.rs (line 183)
176fn main() {
177    tokio::runtime::current_thread::Runtime::new()
178        .unwrap()
179        .block_on(lazy(|| {
180            let token = env::var("TELEGRAM_BOT_TOKEN").unwrap();
181            let api = Api::new(token).unwrap();
182
183            let stream = api.stream().then(|mb_update| {
184                let res: Result<Result<Update, Error>, ()> = Ok(mb_update);
185                res
186            });
187
188            stream.for_each(move |update| {
189                match update {
190                    Ok(update) => {
191                        if let UpdateKind::Message(message) = update.kind {
192                            test(api.clone(), message)
193                        }
194                    }
195                    Err(_) => {}
196                }
197
198                Ok(())
199            })
200        }))
201        .unwrap();
202}
examples/pin.rs (line 31)
24fn main() {
25    tokio::runtime::current_thread::Runtime::new()
26        .unwrap()
27        .block_on(lazy(|| {
28            let token = env::var("TELEGRAM_BOT_TOKEN").unwrap();
29            let api = Api::new(token).unwrap();
30
31            let stream = api.stream().then(|mb_update| {
32                let res: Result<Result<Update, Error>, ()> = Ok(mb_update);
33                res
34            });
35
36            stream.for_each(move |update| {
37                match update {
38                    Ok(update) => {
39                        if let UpdateKind::Message(message) = update.kind {
40                            process(api.clone(), message)
41                        }
42                    }
43                    Err(_) => {}
44                }
45
46                Ok(())
47            })
48        }))
49        .unwrap();
50}
examples/live_location.rs (line 44)
37fn main() {
38    tokio::runtime::current_thread::Runtime::new()
39        .unwrap()
40        .block_on(lazy(|| {
41            let token = env::var("TELEGRAM_BOT_TOKEN").unwrap();
42            let api = Api::new(token).unwrap();
43
44            let stream = api.stream().then(|mb_update| {
45                let res: Result<Result<Update, Error>, ()> = Ok(mb_update);
46                res
47            });
48
49            stream.for_each(move |update| {
50                match update {
51                    Ok(update) => {
52                        if let UpdateKind::Message(message) = update.kind {
53                            if let MessageKind::Text { ref data, .. } = message.kind {
54                                match data.as_str() {
55                                    "/livelocation" => test(api.clone(), message.clone()),
56                                    _ => (),
57                                }
58                            }
59                        }
60                    }
61                    Err(_) => {}
62                }
63
64                Ok(())
65            })
66        }))
67        .unwrap();
68}
examples/simple.rs (line 18)
11fn main() {
12    tokio::runtime::current_thread::Runtime::new()
13        .unwrap()
14        .block_on(lazy(|| {
15            let token = env::var("TELEGRAM_BOT_TOKEN").unwrap();
16            let api = Api::new(token).unwrap();
17
18            let stream = api.stream().then(|mb_update| {
19                let res: Result<Result<Update, Error>, ()> = Ok(mb_update);
20                res
21            });
22
23            // Print update or error for each update.
24            stream.for_each(move |update| {
25                match update {
26                    Ok(update) => {
27                        // If the received update contains a new message...
28                        if let UpdateKind::Message(message) = update.kind {
29                            if let MessageKind::Text { ref data, .. } = message.kind {
30                                // Print received text message to stdout.
31                                println!("<{}>: {}", &message.from.first_name, data);
32
33                                // Answer message with "Hi".
34                                api.spawn(message.text_reply(format!(
35                                    "Hi, {}! You just wrote '{}'",
36                                    &message.from.first_name, data
37                                )));
38                            }
39                        }
40                    }
41                    Err(_) => {}
42                }
43
44                Ok(())
45            })
46        }))
47        .unwrap();
48}
Source

pub fn spawn<Req: Request>(&self, request: Req)

Send a request to the Telegram server and do not wait for a response.

§Examples
let chat = ChatId::new(61031);
api.spawn(chat.text("Message"))
Examples found in repository?
examples/features.rs (line 70)
69fn test_forward(api: Api, message: Message) {
70    api.spawn(message.forward(&message.chat));
71
72    api.spawn(message.forward(&message.from))
73}
74
75fn test_edit_message(api: Api, message: Message) {
76    let round_1 = api.send(message.text_reply("Round 1"));
77
78    let duration_1 = Duration::from_secs(2);
79
80    let sleep_1 = Delay::new(Instant::now().add(duration_1)).from_err();
81
82    let round_2_api = api.clone();
83    let round_2 = round_1
84        .join(sleep_1)
85        .and_then(move |(message, _)| round_2_api.send(message.edit_text("Round 2")));
86
87    let duration_2 = Duration::from_secs(4);
88    let sleep_2 = Delay::new(Instant::now().add(duration_2)).from_err();
89
90    let round_3 = round_2
91        .join(sleep_2)
92        .map_err(|_| ())
93        .and_then(move |(message, _)| {
94            api.spawn(message.edit_text("Round 3"));
95            Ok(())
96        });
97
98    tokio::executor::current_thread::spawn(round_3)
99}
100
101fn test_get_chat(api: Api, message: Message) {
102    let chat = api.send(message.chat.get_chat());
103    let future = chat.and_then(move |chat| api.send(chat.text(format!("Chat id {}", chat.id()))));
104
105    tokio::executor::current_thread::spawn({ future.map_err(|_| ()).map(|_| ()) })
106}
107
108fn test_get_chat_administrators(api: Api, message: Message) {
109    let administrators = api.send(message.chat.get_administrators());
110    let future = administrators.and_then(move |administrators| {
111        let mut response = Vec::new();
112        for member in administrators {
113            response.push(member.user.first_name.clone())
114        }
115        api.send(message.text_reply(format!("Administrators: {}", response.join(", "))))
116    });
117
118    tokio::executor::current_thread::spawn({ future.map_err(|_| ()).map(|_| ()) })
119}
120
121fn test_get_chat_members_count(api: Api, message: Message) {
122    let count = api.send(message.chat.get_members_count());
123    let future = count
124        .and_then(move |count| api.send(message.text_reply(format!("Members count: {}", count))));
125
126    tokio::executor::current_thread::spawn({ future.map_err(|_| ()).map(|_| ()) })
127}
128
129fn test_get_chat_member(api: Api, message: Message) {
130    let member = api.send(message.chat.get_member(&message.from));
131    let future = member.and_then(move |member| {
132        let first_name = member.user.first_name.clone();
133        let status = member.status;
134        api.send(message.text_reply(format!("Member {}, status {:?}", first_name, status)))
135    });
136
137    tokio::executor::current_thread::spawn({ future.map_err(|_| ()).map(|_| ()) })
138}
139
140fn test_get_user_profile_photos(api: Api, message: Message) {
141    let photos = api.send(message.from.get_user_profile_photos());
142
143    let future = photos.and_then(move |photos| {
144        api.send(message.text_reply(format!("Found photos: {}", photos.total_count)))
145    });
146
147    tokio::executor::current_thread::spawn({ future.map_err(|_| ()).map(|_| ()) })
148}
149
150fn test_leave(api: Api, message: Message) {
151    api.spawn(message.chat.leave())
152}
More examples
Hide additional examples
examples/pin.rs (line 16)
11fn process(api: Api, message: Message) {
12    if let MessageKind::Text { ref data, .. } = message.kind {
13        match data.as_str() {
14            "/pin" => message
15                .reply_to_message
16                .map(|message| api.spawn(message.pin()))
17                .unwrap_or(()),
18            "/unpin" => api.spawn(message.chat.unpin_message()),
19            _ => (),
20        }
21    }
22}
examples/simple.rs (lines 34-37)
11fn main() {
12    tokio::runtime::current_thread::Runtime::new()
13        .unwrap()
14        .block_on(lazy(|| {
15            let token = env::var("TELEGRAM_BOT_TOKEN").unwrap();
16            let api = Api::new(token).unwrap();
17
18            let stream = api.stream().then(|mb_update| {
19                let res: Result<Result<Update, Error>, ()> = Ok(mb_update);
20                res
21            });
22
23            // Print update or error for each update.
24            stream.for_each(move |update| {
25                match update {
26                    Ok(update) => {
27                        // If the received update contains a new message...
28                        if let UpdateKind::Message(message) = update.kind {
29                            if let MessageKind::Text { ref data, .. } = message.kind {
30                                // Print received text message to stdout.
31                                println!("<{}>: {}", &message.from.first_name, data);
32
33                                // Answer message with "Hi".
34                                api.spawn(message.text_reply(format!(
35                                    "Hi, {}! You just wrote '{}'",
36                                    &message.from.first_name, data
37                                )));
38                            }
39                        }
40                    }
41                    Err(_) => {}
42                }
43
44                Ok(())
45            })
46        }))
47        .unwrap();
48}
Source

pub fn send_timeout<Req: Request>( &self, request: Req, duration: Duration, ) -> TelegramFuture<Option<<Req::Response as ResponseType>::Type>>

Send a request to the Telegram server and wait for a response, timing out after duration. Future will resolve to None if timeout fired.

§Examples
use std::time::Duration;

let future = api.send_timeout(GetMe, Duration::from_secs(5));
future.and_then(|me| Ok(assert!(me.is_some())));
Source

pub fn send<Req: Request>( &self, request: Req, ) -> TelegramFuture<<Req::Response as ResponseType>::Type>

Send a request to the Telegram server and wait for a response.

§Examples
let future = api.send(GetMe);
future.and_then(|me| Ok(println!("{:?}", me)));
Examples found in repository?
examples/get_me.rs (line 18)
11fn main() {
12    tokio::runtime::current_thread::Runtime::new()
13        .unwrap()
14        .block_on(lazy(|| {
15            let token = env::var("TELEGRAM_BOT_TOKEN").unwrap();
16            let api = Api::new(token).unwrap();
17
18            tokio::executor::current_thread::spawn(api.send(GetMe).then(|r| {
19                println!("{:?}", r);
20
21                Ok(())
22            }));
23
24            Ok::<_, Error>(())
25        }))
26        .unwrap();
27}
More examples
Hide additional examples
examples/features.rs (line 19)
18fn test_message(api: Api, message: Message) {
19    let simple = api.send(message.text_reply("Simple message"));
20
21    let markdown = api.send(
22        message
23            .text_reply("`Markdown message`")
24            .parse_mode(ParseMode::Markdown),
25    );
26
27    let html = api.send(
28        message
29            .text_reply("<b>Bold HTML message</b>")
30            .parse_mode(ParseMode::Html),
31    );
32
33    tokio::executor::current_thread::spawn({
34        let future = simple.and_then(|_| markdown).and_then(|_| html);
35
36        future.map_err(|_| ()).map(|_| ())
37    })
38}
39
40fn test_preview(api: Api, message: Message) {
41    let preview = api.send(message.text_reply("Message with preview https://telegram.org"));
42
43    let no_preview = api.send(
44        message
45            .text_reply("Message without preview https://telegram.org")
46            .disable_preview(),
47    );
48
49    tokio::executor::current_thread::spawn({
50        let future = preview.and_then(|_| no_preview);
51
52        future.map_err(|_| ()).map(|_| ())
53    })
54}
55
56fn test_reply(api: Api, message: Message) {
57    let msg = api.send(message.text_reply("Reply to message"));
58    let chat = api.send(message.chat.text("Text to message chat"));
59
60    let private = api.send(message.from.text("Private text"));
61
62    tokio::executor::current_thread::spawn({
63        let future = msg.and_then(|_| chat).and_then(|_| private);
64
65        future.map_err(|_| ()).map(|_| ())
66    })
67}
68
69fn test_forward(api: Api, message: Message) {
70    api.spawn(message.forward(&message.chat));
71
72    api.spawn(message.forward(&message.from))
73}
74
75fn test_edit_message(api: Api, message: Message) {
76    let round_1 = api.send(message.text_reply("Round 1"));
77
78    let duration_1 = Duration::from_secs(2);
79
80    let sleep_1 = Delay::new(Instant::now().add(duration_1)).from_err();
81
82    let round_2_api = api.clone();
83    let round_2 = round_1
84        .join(sleep_1)
85        .and_then(move |(message, _)| round_2_api.send(message.edit_text("Round 2")));
86
87    let duration_2 = Duration::from_secs(4);
88    let sleep_2 = Delay::new(Instant::now().add(duration_2)).from_err();
89
90    let round_3 = round_2
91        .join(sleep_2)
92        .map_err(|_| ())
93        .and_then(move |(message, _)| {
94            api.spawn(message.edit_text("Round 3"));
95            Ok(())
96        });
97
98    tokio::executor::current_thread::spawn(round_3)
99}
100
101fn test_get_chat(api: Api, message: Message) {
102    let chat = api.send(message.chat.get_chat());
103    let future = chat.and_then(move |chat| api.send(chat.text(format!("Chat id {}", chat.id()))));
104
105    tokio::executor::current_thread::spawn({ future.map_err(|_| ()).map(|_| ()) })
106}
107
108fn test_get_chat_administrators(api: Api, message: Message) {
109    let administrators = api.send(message.chat.get_administrators());
110    let future = administrators.and_then(move |administrators| {
111        let mut response = Vec::new();
112        for member in administrators {
113            response.push(member.user.first_name.clone())
114        }
115        api.send(message.text_reply(format!("Administrators: {}", response.join(", "))))
116    });
117
118    tokio::executor::current_thread::spawn({ future.map_err(|_| ()).map(|_| ()) })
119}
120
121fn test_get_chat_members_count(api: Api, message: Message) {
122    let count = api.send(message.chat.get_members_count());
123    let future = count
124        .and_then(move |count| api.send(message.text_reply(format!("Members count: {}", count))));
125
126    tokio::executor::current_thread::spawn({ future.map_err(|_| ()).map(|_| ()) })
127}
128
129fn test_get_chat_member(api: Api, message: Message) {
130    let member = api.send(message.chat.get_member(&message.from));
131    let future = member.and_then(move |member| {
132        let first_name = member.user.first_name.clone();
133        let status = member.status;
134        api.send(message.text_reply(format!("Member {}, status {:?}", first_name, status)))
135    });
136
137    tokio::executor::current_thread::spawn({ future.map_err(|_| ()).map(|_| ()) })
138}
139
140fn test_get_user_profile_photos(api: Api, message: Message) {
141    let photos = api.send(message.from.get_user_profile_photos());
142
143    let future = photos.and_then(move |photos| {
144        api.send(message.text_reply(format!("Found photos: {}", photos.total_count)))
145    });
146
147    tokio::executor::current_thread::spawn({ future.map_err(|_| ()).map(|_| ()) })
148}
examples/live_location.rs (line 23)
18fn test(api: Api, message: Message) {
19    let timeout = |n| Delay::new(Instant::now().add(Duration::from_secs(n))).from_err();
20    let api_future = || Ok(api.clone());
21
22    let future = api
23        .send(message.location_reply(0.0, 0.0).live_period(60))
24        .join(api_future())
25        .join(timeout(2))
26        .and_then(|((message, api), _)| api.send(message.edit_live_location(10.0, 10.0)))
27        .join(api_future())
28        .join(timeout(4))
29        .and_then(|((message, api), _)| api.send(message.edit_live_location(20.0, 20.0)))
30        .join(api_future())
31        .join(timeout(6))
32        .and_then(|((message, api), _)| api.send(message.edit_live_location(30.0, 30.0)));
33
34    tokio::executor::current_thread::spawn(future.then(|_| Ok(())));
35}

Trait Implementations§

Source§

impl Clone for Api

Source§

fn clone(&self) -> Api

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl Freeze for Api

§

impl !RefUnwindSafe for Api

§

impl !Send for Api

§

impl !Sync for Api

§

impl Unpin for Api

§

impl !UnwindSafe for Api

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.