From 93df40a2e5e8e2623eef12687846622d603ddb5d Mon Sep 17 00:00:00 2001 From: Desiders Date: Sun, 29 Oct 2023 00:53:38 +0300 Subject: [PATCH] Update example of using `InputFile` for `StreamFile` --- examples/input_file/Cargo.toml | 5 ++++- examples/input_file/src/main.rs | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/examples/input_file/Cargo.toml b/examples/input_file/Cargo.toml index 45d69d3e..4415d498 100644 --- a/examples/input_file/Cargo.toml +++ b/examples/input_file/Cargo.toml @@ -6,6 +6,9 @@ edition = "2021" [dependencies] telers = { path = "../..", features = ["default"] } tokio = { version = "1.28", features = ["macros"] } +tokio-util = { version = "0.7.9", features = ["codec"] } reqwest = "0.11" +futures = "0.3" +bytes = "1.3" tracing = "0.1" -tracing-subscriber = { version = "0.3", features = ["env-filter"] } \ No newline at end of file +tracing-subscriber = { version = "0.3", features = ["env-filter"] } \ No newline at end of file diff --git a/examples/input_file/src/main.rs b/examples/input_file/src/main.rs index a50c36e3..7161c4c7 100644 --- a/examples/input_file/src/main.rs +++ b/examples/input_file/src/main.rs @@ -5,6 +5,8 @@ //! RUST_LOG={log_level} BOT_TOKEN={your_bot_token} cargo run --package input_file //! ``` +use bytes::BytesMut; +use futures::{TryFutureExt as _, TryStreamExt as _}; use telers::{ enums::UpdateType, errors::HandlerError, @@ -14,12 +16,15 @@ use telers::{ types::{InputFile, InputMediaPhoto, Message}, Bot, Dispatcher, }; +use tokio_util::codec::{BytesCodec, FramedRead}; use tracing::{event, Level}; use tracing_subscriber::{fmt, layer::SubscriberExt as _, util::SubscriberInitExt as _, EnvFilter}; const CAT_URL: &str = "https://http.cat/images/200.jpg"; const CAT_FS_PATH: &str = "cat.jpg"; +const DEFAULT_CAPACITY: usize = 64 * 1024; // 64 KiB + /// This handler will be called on bot startup. /// It will download file from URL and save it to the file system as `cat.jpg` for further usage in handlers. async fn on_startup() -> simple::HandlerResult { @@ -92,6 +97,16 @@ async fn input_file_handler(bot: Bot, message: Message) -> telegram::HandlerResu HandlerError::new(err) })?); + // Using `InputFile::stream` to send file by stream + let cat_stream_input_file = InputFile::stream(Box::pin( + tokio::fs::File::open(CAT_FS_PATH) + .map_ok(move |file| { + FramedRead::with_capacity(file, BytesCodec::new(), DEFAULT_CAPACITY) + .map_ok(BytesMut::freeze) + }) + .try_flatten_stream(), + )); + let result_message = bot .send(SendMediaGroup::new( message.chat_id(), @@ -99,6 +114,7 @@ async fn input_file_handler(bot: Bot, message: Message) -> telegram::HandlerResu InputMediaPhoto::new(cat_url_input_file).caption("Cat by URL"), InputMediaPhoto::new(cat_fs_input_file).caption("Cat by file system"), InputMediaPhoto::new(cat_buffered_input_file).caption("Cat by bytes"), + InputMediaPhoto::new(cat_stream_input_file).caption("Cat by stream"), ], )) .await?;