diff --git a/.gitignore b/.gitignore index 232c735..77a3132 100644 --- a/.gitignore +++ b/.gitignore @@ -25,5 +25,5 @@ aier_bot-*.tar # Temporary files, for example, from tests. /tmp/ .DS_Store -downloads -dev.sh \ No newline at end of file +.local +run.sh \ No newline at end of file diff --git a/lib/aier_bot/bot.ex b/lib/aier_bot/bot.ex index d64438b..d317863 100644 --- a/lib/aier_bot/bot.ex +++ b/lib/aier_bot/bot.ex @@ -3,6 +3,8 @@ defmodule AierBot.Bot do alias AierBot.AierApi alias AierBot.OpenaiApi + alias AierBot.FileDownloader + @bot :aier_bot use ExGram.Bot, @@ -37,9 +39,11 @@ defmodule AierBot.Bot do def handle({:text, text, %{chat: chat}}, context) do # TODO: repeat # request download API - file_content = CobaltClient.json(text) + url = CobaltClient.json(text) + {file_name, file_content} = FileDownloader.download(url) + - {:ok, message} = ExGram.send_document(chat.id, {:file_content, file_content, "video.mp4"}) + {:ok, message} = ExGram.send_document(chat.id, {:file_content, file_content, file_name}) IO.inspect(message) answer(context, "done") diff --git a/lib/aier_bot/cobalt_client.ex b/lib/aier_bot/cobalt_client.ex index 40efe21..01f304a 100644 --- a/lib/aier_bot/cobalt_client.ex +++ b/lib/aier_bot/cobalt_client.ex @@ -1,5 +1,4 @@ defmodule AierBot.CobaltClient do - alias AierBot.FileDownloader use Tesla plug(Tesla.Middleware.BaseUrl, "https://api.cobalt.tools") @@ -19,8 +18,7 @@ defmodule AierBot.CobaltClient do # "url" => "https://video.twimg.com/amplify_video/1814202798097268736/vid/avc1/720x1192/HAD9zyJn1xoP4oRN.mp4?tag=16" # } %{"url" => url} = response.body - file_content = FileDownloader.download(url, "video.mp4") - file_content + url # TODO send photo to telegram diff --git a/lib/aier_bot/file_downloader.ex b/lib/aier_bot/file_downloader.ex index 9f30639..549a458 100644 --- a/lib/aier_bot/file_downloader.ex +++ b/lib/aier_bot/file_downloader.ex @@ -1,12 +1,24 @@ defmodule AierBot.FileDownloader do use Tesla - def download(url, file_path) do + def download(url) do + # https://video.twimg.com/amplify_video/1814202798097268736/vid/avc1/720x1192/HAD9zyJn1xoP4oRN.mp4?tag=16 + + IO.puts(url) case get(url) do - {:ok, %Tesla.Env{status: 200, body: body}} -> - File.write("./downloads/#{file_path}", body) + {:ok, %Tesla.Env{status: 200, body: body, headers: headers}} -> + # TODO: 可以使用异步,并且实时更新 bot 状态 + IO.puts("Downloading file...") + + # [..., {"content-type", "video/mp4"}, ...] = headers + utc_now_str = DateTime.utc_now() |> DateTime.shift_zone!("Etc/UTC") |> DateTime.to_iso8601() + content_type = headers |> Enum.find(fn {k, _} -> k == "content-type" end) |> elem(1) + # IO.puts("Content-Type: #{content_type}") + file_path = utc_now_str <> "_" <> content_type |> String.replace("/", ".") + + File.write("./.local/storage/#{file_path}", body) IO.puts("File downloaded successfully.") - body + {file_path, body} {:ok, %Tesla.Env{status: status}} -> IO.puts("Failed to download file. Status: #{status}")