Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add local TBA file downloading #1173

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

LasterAlex
Copy link
Collaborator

Inspired by https://t.me/teloxide/22547

Made it just because it was quick and I could, if it seems useful - would be glad to see this merged, but it's not very important

Code snippet to test this:

use std::str::FromStr;

use teloxide::{
    dispatching::{UpdateFilterExt, UpdateHandler},
    net::Download,
    prelude::*,
};

type HandlerResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;

async fn download_document(bot: Bot, message: Message) -> HandlerResult {
    if let Some(document) = message.document() {
        let file = bot.get_file(document.file.id.clone()).await?;
        let mut dest = tokio::fs::File::create("test.txt").await?;
        bot.download_file(&file.path, &mut dest).await?;

        assert!(tokio::fs::read_to_string("test.txt").await.is_ok());

        bot.send_message(message.chat.id, "Downloaded!").await?;

        tokio::fs::remove_file("test.txt").await?;
    } else {
        bot.send_message(message.chat.id, "Not a document").await?;
    }
    Ok(())
}

fn handler_tree() -> UpdateHandler<Box<dyn std::error::Error + Send + Sync + 'static>> {
    dptree::entry().branch(Update::filter_message().endpoint(download_document))
}

#[tokio::main]
async fn main() {
    let bot = Bot::from_env().set_api_url(reqwest::Url::from_str("http://localhost:8081").unwrap());

    Dispatcher::builder(bot, handler_tree())
        .enable_ctrlc_handler()
        .build()
        .dispatch()
        .await;
}

Cargo.toml:

[dependencies]
teloxide = { git = "https://github.com/LasterAlex/teloxide", branch = "add-local-file-downloading"}
tokio = { version = "1.38", features = ["rt-multi-thread", "macros"] }
reqwest = "0.12.7"

Just send a .txt file to this bot

@teloxidebot
Copy link
Collaborator

r? @hirrolot

(teloxidebot has picked a reviewer for you, use r? to override)

@teloxidebot teloxidebot added C-core crate: teloxide-core S-waiting-on-review Status: Awaiting review from the assignee labels Sep 22, 2024
@LasterAlex LasterAlex changed the title Added local TBA file downloading Add local TBA file downloading Sep 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-core crate: teloxide-core S-waiting-on-review Status: Awaiting review from the assignee
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants