implement yt-dlp FFI and working bot command to download

This commit is contained in:
mykola2312 2024-02-18 19:29:36 +02:00
parent 70c050ca19
commit b224c8fa7b
3 changed files with 41 additions and 5 deletions

View file

@ -0,0 +1,28 @@
use pyo3::prelude::*;
use tokio::task::{spawn_blocking, JoinError};
pub async fn download_url(url: String) -> Result<bool, JoinError> {
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
}

View file

@ -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<State, InMemStorage<State>>;
@ -62,8 +61,8 @@ fn schema() -> UpdateHandler<HandlerErr> {
let command_handler =
teloxide::filter_command::<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 {}",