From 45a032116d5967faf5e2c22f45731186507c74b8 Mon Sep 17 00:00:00 2001 From: Sergey Levitin Date: Sat, 11 Jan 2020 16:02:49 +0300 Subject: [PATCH] Add ping_bot example --- .gitignore | 4 +++- examples/Cargo.toml | 16 ++++++++++++++++ examples/README.md | 9 +++++++++ examples/ping_bot.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 examples/Cargo.toml create mode 100644 examples/README.md create mode 100644 examples/ping_bot.rs diff --git a/.gitignore b/.gitignore index 0668c27c..7c5b00ed 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ /target **/*.rs.bk Cargo.lock -.idea/ \ No newline at end of file +.idea/ +.vscode/ +examples/target diff --git a/examples/Cargo.toml b/examples/Cargo.toml new file mode 100644 index 00000000..f2ed9e4e --- /dev/null +++ b/examples/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "examples" +version = "0.0.0" +publish = false +edition = "2018" + +[dev-dependencies] +teloxide = { path = "../" } +tokio = "0.2.6" +pretty_env_logger = "0.3" +futures = "0.3.1" +log = "0.4.8" + +[[example]] +name = "ping_bot" +path = "ping_bot.rs" diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 00000000..f7528628 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,9 @@ +# Examples of how to use Teloxide. + +All examples can be executed with: + +``` +cargo run --example $name +``` + +If you've got an example you'd like to see here, please feel free to open an issue. Otherwise if you've got an example you'd like to add, please feel free to make a PR! diff --git a/examples/ping_bot.rs b/examples/ping_bot.rs new file mode 100644 index 00000000..84574be0 --- /dev/null +++ b/examples/ping_bot.rs @@ -0,0 +1,43 @@ +use futures::stream::StreamExt; +use teloxide::{ + dispatching::{ + private::Dispatcher, update_listeners::polling_default, SessionState, + }, + requests::Request, + types::{Message, Update, UpdateKind}, + Bot, +}; + +extern crate pretty_env_logger; +#[macro_use] +extern crate log; + +#[tokio::main] +async fn main() { + pretty_env_logger::init(); + let bot = &Bot::new("1061598315:AAErEDodTsrqD3UxA_EvFyEfXbKA6DT25G0"); + let mut updater = Box::pin(polling_default(bot)); + let handler = |s, upd: Update| async move { + match upd.kind { + UpdateKind::Message(m) => { + if m.text() == "ping" { + let msg = bot.send_message(m.chat.id, "pong"); + } + msg.send().await.unwrap(); + } + _ => {} + } + SessionState::Continue(s) + }; + let mut dp = Dispatcher::<'_, (), _>::new(handler); + info!("Starting the message handler."); + loop { + let u = updater.next().await.unwrap(); + match u { + Err(e) => error!("{}", e), + Ok(u) => { + let _ = dp.dispatch(u).await; + } + } + } +}