Merge pull request #201 from pdrolopes/master

Added heroku_ping_pong_bot example
This commit is contained in:
Temirkhan Myrzamadi 2020-04-17 11:57:20 +03:00 committed by GitHub
commit 0e511da5d0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 126 additions and 0 deletions

View file

@ -0,0 +1,19 @@
[package]
name = "heroku_ping_pong_bot"
version = "0.1.0"
authors = ["Pedro Lopes <ordepi@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
log = "0.4.8"
futures = "0.3.4"
tokio = "0.2.9"
pretty_env_logger = "0.4.0"
teloxide = "0.2.0"
# Used to setup a webhook
warp = "0.2.2"
reqwest = "0.10.4"
serde_json = "1.0.50"

View file

@ -0,0 +1 @@
web: ./target/release/heroku_ping_pong_bot

View file

@ -0,0 +1,15 @@
# Heroku example
This is an example project on how to deploy `webhook_ping_pong_bot` to heroku.
You will need to configure the buildpack for heroku. We will be using [Heroku rust buildpack](https://github.com/emk/heroku-buildpack-rust). Configuration was done by using `heroku` CLI.
If you're creating a new Heroku application, run this command inside example
```
heroku create --buildpack emk/rust
```
To set buildpack for existing applicaton:
```
heroku buildpacks:set emk/rust
```

View file

@ -0,0 +1,91 @@
// The version of ping-pong-bot, which uses a webhook to receive updates from
// Telegram, instead of long polling.
use teloxide::{dispatching::update_listeners, prelude::*};
use std::{convert::Infallible, env, net::SocketAddr, sync::Arc};
use tokio::sync::mpsc;
use warp::Filter;
use reqwest::StatusCode;
#[tokio::main]
async fn main() {
run().await;
}
async fn handle_rejection(error: warp::Rejection) -> Result<impl warp::Reply, Infallible> {
log::error!("Cannot process the request due to: {:?}", error);
Ok(StatusCode::INTERNAL_SERVER_ERROR)
}
pub async fn webhook<'a>(bot: Arc<Bot>) -> impl update_listeners::UpdateListener<Infallible> {
// Heroku defines auto defines a port value
let teloxide_token = env::var("TELOXIDE_TOKEN").expect("TELOXIDE_TOKEN env variable missing");
let port: u16 = env::var("PORT")
.expect("PORT env variable missing")
.parse()
.expect("PORT value to be integer");
// Heroku host example .: "heroku-ping-pong-bot.herokuapp.com"
let host = env::var("HOST").expect("have HOST env variable");
let path = format!("bot{}", teloxide_token);
let url = format!("https://{}/{}", host, path);
bot.set_webhook(url)
.send()
.await
.expect("Cannot setup a webhook");
let (tx, rx) = mpsc::unbounded_channel();
let server = warp::post()
.and(warp::path(path))
.and(warp::body::json())
.map(move |json: serde_json::Value| {
let try_parse = match serde_json::from_str(&json.to_string()) {
Ok(update) => Ok(update),
Err(error) => {
log::error!(
"Cannot parse an update.\nError: {:?}\nValue: {}\n\
This is a bug in teloxide, please open an issue here: \
https://github.com/teloxide/teloxide/issues.",
error,
json
);
Err(error)
}
};
if let Ok(update) = try_parse {
tx.send(Ok(update))
.expect("Cannot send an incoming update from the webhook")
}
StatusCode::OK
})
.recover(handle_rejection);
let serve = warp::serve(server);
let address = format!("0.0.0.0:{}", port);
tokio::spawn(serve.run(address.parse::<SocketAddr>().unwrap()));
rx
}
async fn run() {
teloxide::enable_logging!();
log::info!("Starting ping_pong_bot!");
let bot = Bot::from_env();
Dispatcher::new(Arc::clone(&bot))
.messages_handler(|rx: DispatcherHandlerRx<Message>| {
rx.for_each(|message| async move {
message.answer("pong").send().await.log_on_error().await;
})
})
.dispatch_with_listener(
webhook(bot).await,
LoggingErrorHandler::with_custom_text("An error from the update listener"),
)
.await;
}