Prechádzať zdrojové kódy

[Telegram] Extracted file download into separate function

Signed-off-by: Slava Barinov <rayslava@gmail.com>
Slava Barinov 4 rokov pred
rodič
commit
993fc9f02a
3 zmenil súbory, kde vykonal 36 pridanie a 24 odobranie
  1. 2 0
      Cargo.lock
  2. 2 0
      Cargo.toml
  3. 32 24
      src/telegram.rs

+ 2 - 0
Cargo.lock

@@ -997,6 +997,7 @@ dependencies = [
  "cc",
  "chrono",
  "csv",
+ "derive_more",
  "libc",
  "log",
  "pickledb",
@@ -1009,6 +1010,7 @@ dependencies = [
  "shellexpand",
  "structopt",
  "teloxide",
+ "thiserror",
  "tokio",
 ]
 

+ 2 - 0
Cargo.toml

@@ -19,6 +19,8 @@ teloxide = { version = "0.4", features = ["auto-send"] }
 log = "0.4.8"
 pretty_env_logger = "0.4.0"
 tokio = { version =  "1.3", features = ["rt-multi-thread", "macros"] }
+derive_more = "0.99.13"
+thiserror = "1.0.24"
 
 [build-dependencies]
 cc = "1.0"

+ 32 - 24
src/telegram.rs

@@ -1,8 +1,11 @@
 // This bot throws a dice on each incoming message.
 
+use derive_more::From;
 use teloxide::prelude::*;
 use teloxide::types::*;
 use teloxide::{net::Download, types::File as TgFile, Bot};
+use teloxide::{DownloadError, RequestError};
+use thiserror::Error;
 use tokio::fs::File;
 
 #[tokio::main]
@@ -10,6 +13,30 @@ pub async fn bot() {
     run().await;
 }
 
+/// Possible error while receiving a file
+#[derive(Debug, Error, From)]
+enum FileReceiveError {
+    /// Download process error
+    #[error("File download error: {0}")]
+    Download(#[source] DownloadError),
+    /// Telegram request error
+    #[error("Web request error: {0}")]
+    Request(#[source] RequestError),
+    /// Io error while writing file
+    #[error("An I/O error: {0}")]
+    Io(#[source] std::io::Error),
+}
+
+async fn download_file(downloader: &Bot, file_id: &str) -> Result<String, FileReceiveError> {
+    let TgFile {
+        file_id, file_path, ..
+    } = downloader.get_file(file_id).send().await?;
+    let filepath = format!("/tmp/{}", file_id);
+    let mut file = File::create(&filepath).await?;
+    downloader.download_file(&file_path, &mut file).await?;
+    Ok(filepath)
+}
+
 async fn run() {
     teloxide::enable_logging!();
     log::info!("Starting dices_bot...");
@@ -20,31 +47,12 @@ async fn run() {
         let update = &message.update;
         if let MessageKind::Common(msg) = &update.kind {
             if let MediaKind::Document(doc) = &msg.media_kind {
-                log::info!("{:?}", &doc.document);
-                if let Ok(TgFile {
-                    file_id,
-                    file_path,
-                    file_size,
-                    ..
-                }) = &message
-                    .requester
-                    .get_file(&doc.document.file_id)
-                    .send()
-                    .await
+                if let Ok(newfile) =
+                    download_file(&message.requester.inner(), &doc.document.file_id).await
                 {
-                    let filepath = format!("/tmp/{}", file_id);
-                    if let Ok(mut file) = File::create(filepath).await {
-                        if message
-                            .requester
-                            .download_file(&file_path, &mut file)
-                            .await
-                            .is_ok()
-                        {
-                            message
-                                .answer(format!("File received: {:} bytes", file_size))
-                                .await?;
-                        }
-                    }
+                    message
+                        .answer(format!("File received: {:} ", newfile))
+                        .await?;
                 }
 
                 message.answer_dice().await?;