implement bot command to download video

This commit is contained in:
mykola2312 2024-02-21 21:04:21 +02:00
parent 7fb721496a
commit 72a7eb0239
2 changed files with 39 additions and 2 deletions

View file

@ -7,8 +7,12 @@ use std::time::Duration;
use teloxide::dispatching::dialogue;
use teloxide::dispatching::dialogue::InMemStorage;
use teloxide::dispatching::UpdateHandler;
use teloxide::types::InputFile;
use teloxide::{prelude::*, update_listeners::Polling, utils::command::BotCommands};
use crate::dl::delete_if_exists;
use crate::dl::download;
type State = ();
type MyDialogue = Dialogue<State, InMemStorage<State>>;
@ -80,6 +84,22 @@ async fn cmd_test(bot: Bot, msg: Message) -> HandlerResult {
}
async fn cmd_download(bot: Bot, msg: Message, url: String) -> HandlerResult {
let output_path = match download(url.as_str()).await {
Ok(path) => path,
Err(e) => {
bot.send_message(msg.chat.id, e.to_string()).await?;
return Ok(());
}
};
if let Err(e) = bot
.send_video(msg.chat.id, InputFile::file(&output_path))
.await
{
delete_if_exists(&output_path);
return Err(Box::new(e));
}
Ok(())
}

View file

@ -1,6 +1,9 @@
use std::fmt;
use std::fs;
use std::path::Path;
use teloxide::types::Message;
use self::spawn::SpawnError;
use self::yt_dlp::{YtDlp, YtDlpError, YtDlpFormat, YtDlpInfo};
@ -26,6 +29,20 @@ impl From<YtDlpError> for DownloadError {
}
}
impl fmt::Display for DownloadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use DownloadError as DE;
match &self {
DE::Message(msg) => write!(f, "{}", msg),
DE::NoFormatFound => write!(
f,
"no best format found. you may want to specify one yourself"
),
DE::MakePathError => write!(f, "failed to make path for download file"),
}
}
}
fn make_download_path(info: &YtDlpInfo, format: &YtDlpFormat) -> Result<String, DownloadError> {
std::env::temp_dir()
.join(format!("{}.{}", info.id, format.ext))
@ -37,7 +54,7 @@ fn make_download_path(info: &YtDlpInfo, format: &YtDlpFormat) -> Result<String,
fn file_exists(path: &str) -> bool {
match fs::metadata(path) {
Ok(_) => true,
Err(_) => false
Err(_) => false,
}
}