diff --git a/src/dl.rs b/src/dl.rs index 3137393..674b799 100644 --- a/src/dl.rs +++ b/src/dl.rs @@ -1 +1 @@ -pub mod download; \ No newline at end of file +pub mod download; diff --git a/src/dl/download.rs b/src/dl/download.rs index e69de29..2ee31cc 100644 --- a/src/dl/download.rs +++ b/src/dl/download.rs @@ -0,0 +1,28 @@ +use pyo3::prelude::*; +use tokio::task::{spawn_blocking, JoinError}; + +pub async fn download_url(url: String) -> Result { + spawn_blocking(move || { + let res: PyResult<()> = Python::with_gil(|py| { + let yt_dlp = PyModule::import(py, "yt_dlp")?; + let yt = yt_dlp.getattr("YoutubeDL")?; + + let yt_obj = yt.call((), None)?; + + yt_obj.call_method0("__enter__")?; + yt_obj.call_method1("download", (url,))?; + yt_obj.call_method0("__exit__")?; + + Ok(()) + }); + + match res { + Ok(_) => true, + Err(e) => { + println!("{}", e); + false + } + } + }) + .await +} diff --git a/src/main.rs b/src/main.rs index ac0fc0b..1eac791 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,5 @@ use anyhow; use dotenv::dotenv; -use teloxide::dispatching::dialogue::GetChatId; use std::env; use std::fmt; use std::str; @@ -12,7 +11,7 @@ use teloxide::dispatching::UpdateHandler; use teloxide::{prelude::*, update_listeners::Polling, utils::command::BotCommands}; mod dl; -use dl::download::download; +use dl::download::download_url; type State = (); type MyDialogue = Dialogue>; @@ -62,8 +61,8 @@ fn schema() -> UpdateHandler { let command_handler = teloxide::filter_command::() - .branch(case![Command::Test].endpoint(test)); - //.branch(case![Command::Download(download)].endpoint(download)); + .branch(case![Command::Test].endpoint(test)) + .branch(case![Command::Download(url)].endpoint(download)); let message_handler = Update::filter_message().branch(command_handler); let raw_message_handler = Update::filter_message().branch(dptree::endpoint(handle_message)); @@ -88,6 +87,15 @@ async fn test(bot: Bot, msg: Message) -> HandlerResult { Ok(()) } +async fn download(bot: Bot, msg: Message, url: String) -> HandlerResult { + match download_url(url).await { + Ok(_) => bot.send_message(msg.chat.id, "downloaded"), + Err(_) => bot.send_message(msg.chat.id, "failed to download") + }.await?; + + Ok(()) +} + async fn handle_message(_bot: Bot, _dialogue: MyDialogue, msg: Message) -> HandlerResult { println!( "msg {} kind {:?} text {}",