error_handling/
error_handling.rs1use telebot::{Bot, File};
2use failure::Error;
3use futures::stream::Stream;
4use futures::Future;
5use std::env;
6
7use telebot::functions::*;
9
10fn main() {
11 let mut bot = Bot::new(&env::var("TELEGRAM_BOT_KEY").unwrap()).update_interval(200);
13
14 enum LocationErr {
16 Telegram(Error),
17 WrongLocationFormat,
18 }
19
20 let handle = bot.new_cmd("/location")
21 .then(|result| {
22 let (bot, mut msg) = result.expect("Strange telegram error!");
23
24 if let Some(pos) = msg.text.take() {
25 let mut elms = pos.split_whitespace().take(2).filter_map(
26 |x| x.parse::<f32>().ok(),
27 );
28
29 if let (Some(a), Some(l)) = (elms.next(), elms.next()) {
30 return Ok((bot, msg, a, l));
31 }
32 }
33
34 return Err((bot, msg, LocationErr::WrongLocationFormat));
35 })
36 .and_then(|(bot, msg, long, alt)| {
37 bot.location(msg.chat.id, long, alt).send().map_err(|err| {
38 (bot, msg, LocationErr::Telegram(err))
39 })
40 })
41 .or_else(|(bot, msg, err)| {
42 let text = {
43 match err {
44 LocationErr::Telegram(err) => format!("Telegram error: {:?}", err),
45 LocationErr::WrongLocationFormat => "Couldn't parse the location!".into(),
46 }
47 };
48
49 bot.message(msg.chat.id, text).send()
50 })
51 .for_each(|_| Ok(()));
52
53 enum PhotoErr {
55 Telegram(Error),
56 NoPhoto,
57 }
58
59 let handle2 = bot.new_cmd("/get_my_photo")
60 .then(|result| {
61 let (bot, msg) = result.expect("Strange telegram error!");
62
63 let user_id = msg.from.clone().unwrap().id;
64
65 bot.get_user_profile_photos(user_id)
66 .limit(1u32)
67 .send()
68 .then(|result| match result {
69 Ok((bot, photos)) => {
70 if photos.total_count == 0 {
71 return Err((bot, msg, PhotoErr::NoPhoto));
72 }
73
74 return Ok((bot, msg, photos.photos[0][0].clone().file_id));
75 }
76 Err(err) => Err((bot, msg, PhotoErr::Telegram(err))),
77 })
78 })
79 .and_then(|(bot, msg, file_id)| {
80 bot.photo(msg.chat.id)
81 .file(File::Telegram(file_id))
82 .send()
83 .map_err(|err| (bot, msg, PhotoErr::Telegram(err)))
84 })
85 .or_else(|(bot, msg, err)| {
86 let text = match err {
87 PhotoErr::Telegram(err) => format!("Telegram Error: {:?}", err),
88 PhotoErr::NoPhoto => "No photo exists!".into(),
89 };
90
91 bot.message(msg.chat.id, text).send()
92 })
93 .for_each(|_| Ok(()));
94
95 bot.run_with(handle.join(handle2));
97}