Skip to content

Commit

Permalink
Update example of using InputFile for StreamFile
Browse files Browse the repository at this point in the history
  • Loading branch information
Desiders committed Oct 28, 2023
1 parent a44ecc9 commit 93df40a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
5 changes: 4 additions & 1 deletion examples/input_file/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
16 changes: 16 additions & 0 deletions examples/input_file/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 {
Expand Down Expand Up @@ -92,13 +97,24 @@ 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(),
[
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?;
Expand Down

0 comments on commit 93df40a

Please sign in to comment.