diff options
author | Jordan Bracco <href@random.sh> | 2025-06-25 19:22:59 +0200 |
---|---|---|
committer | Jordan Bracco <href@random.sh> | 2025-06-25 19:22:59 +0200 |
commit | c934e79e5852e05f714b2d542cc2678e287c49b8 (patch) | |
tree | 55779a0168260fce03e4775eacdd613ffc945588 /lib/telegram | |
parent | updates (diff) |
format.
Diffstat (limited to 'lib/telegram')
-rw-r--r-- | lib/telegram/room.ex | 183 |
1 files changed, 118 insertions, 65 deletions
diff --git a/lib/telegram/room.ex b/lib/telegram/room.ex index 9db551b..05c3eeb 100644 --- a/lib/telegram/room.ex +++ b/lib/telegram/room.ex @@ -7,7 +7,7 @@ defmodule Nola.TelegramRoom do def rooms(), do: rooms(:with_docs) - @spec rooms(:with_docs | :ids) :: [Map.t | integer( )] + @spec rooms(:with_docs | :ids) :: [Map.t() | integer()] def rooms(:with_docs) do case Couch.get(@couch, :all_docs, include_docs: true) do {:ok, %{"rows" => rows}} -> {:ok, for(%{"doc" => doc} <- rows, do: doc)} @@ -33,9 +33,13 @@ defmodule Nola.TelegramRoom do def after_start() do {:ok, rooms} = rooms(:ids) + for id <- rooms do - spawn(fn() -> - Telegram.Bot.ChatBot.Chat.Session.Supervisor.start_child(Nola.Telegram, Integer.parse(id) |> elem(0)) + spawn(fn -> + Telegram.Bot.ChatBot.Chat.Session.Supervisor.start_child( + Nola.Telegram, + Integer.parse(id) |> elem(0) + ) end) end end @@ -45,34 +49,50 @@ defmodule Nola.TelegramRoom do token = Keyword.get(Application.get_env(:nola, :telegram, []), :key) {:ok, chat} = Api.request(token, "getChat", chat_id: id) Logger.metadata(transport: :telegram, id: id, telegram_room_id: id) - tg_room = case room(to_string(id)) do - {:ok, tg_room = %{"network" => _net, "channel" => _chan}} -> tg_room - _ -> - [net, chan] = String.split(chat["title"], "/", parts: 2) - {net, chan} = case Nola.Irc.Connection.get_network(net, chan) do - %Nola.Irc.Connection{} -> {net, chan} - _ -> {nil, nil} - end - {:ok, _, _} = Couch.post(@couch, %{"_id" => id, "network" => net, "channel" => chan}) - {:ok, tg_room} = room(to_string(id)) - tg_room - end + + tg_room = + case room(to_string(id)) do + {:ok, tg_room = %{"network" => _net, "channel" => _chan}} -> + tg_room + + _ -> + [net, chan] = String.split(chat["title"], "/", parts: 2) + + {net, chan} = + case Nola.Irc.Connection.get_network(net, chan) do + %Nola.Irc.Connection{} -> {net, chan} + _ -> {nil, nil} + end + + {:ok, _, _} = Couch.post(@couch, %{"_id" => id, "network" => net, "channel" => chan}) + {:ok, tg_room} = room(to_string(id)) + tg_room + end + %{"network" => net, "channel" => chan} = tg_room - Logger.info("Starting ChatBot for room #{id} \"#{chat["title"]}\" #{inspect tg_room}") - irc_plumbed = if net && chan do + Logger.info("Starting ChatBot for room #{id} \"#{chat["title"]}\" #{inspect(tg_room)}") + + irc_plumbed = + if net && chan do {:ok, _} = Registry.register(Nola.PubSub, "#{net}/#{chan}:messages", plugin: __MODULE__) {:ok, _} = Registry.register(Nola.PubSub, "#{net}/#{chan}:triggers", plugin: __MODULE__) {:ok, _} = Registry.register(Nola.PubSub, "#{net}/#{chan}:outputs", plugin: __MODULE__) true - else - Logger.warn("Did not found telegram match for #{id} \"#{chat["title"]}\"") - false - end + else + Logger.warn("Did not found telegram match for #{id} \"#{chat["title"]}\"") + false + end + {:ok, %{id: id, net: net, chan: chan, irc: irc_plumbed}} end def init(id) do - Logger.error("telegram_room: bad id (not room id)", transport: :telegram, id: id, telegram_room_id: id) + Logger.error("telegram_room: bad id (not room id)", + transport: :telegram, + id: id, + telegram_room_id: id + ) + :ignore end @@ -82,15 +102,18 @@ defmodule Nola.TelegramRoom do else first_name = Map.get(from, "first_name") last_name = Map.get(from, "last_name") - name = [first_name, last_name] - |> Enum.filter(& &1) - |> Enum.join(" ") + + name = + [first_name, last_name] + |> Enum.filter(& &1) + |> Enum.join(" ") username = Map.get(from, "username", first_name) - account = username - |> Nola.Account.new_account() - |> Nola.Account.update_account_name(name) + account = + username + |> Nola.Account.new_account() + |> Nola.Account.update_account_name(name) Nola.Account.put_meta(account, "telegram-id", user_id) @@ -99,17 +122,33 @@ defmodule Nola.TelegramRoom do end end - def handle_update(%{"message" => %{"from" => from = %{"id" => user_id}, "text" => text}}, _token, state) do + def handle_update( + %{"message" => %{"from" => from = %{"id" => user_id}, "text" => text}}, + _token, + state + ) do account = find_or_create_meta_account(from, state) - #connection = Nola.Irc.Connection.get_network(state.net) + # connection = Nola.Irc.Connection.get_network(state.net) Nola.Irc.send_message_as(account, state.net, state.chan, text, true, origin: __MODULE__) {:ok, state} end - def handle_update(data = %{"message" => %{"from" => from = %{"id" => user_id}, "location" => %{"latitude" => lat, "longitude" => lon}}}, _token, state) do + def handle_update( + data = %{ + "message" => %{ + "from" => from = %{"id" => user_id}, + "location" => %{"latitude" => lat, "longitude" => lon} + } + }, + _token, + state + ) do account = find_or_create_meta_account(from, state) - #connection = Nola.Irc.Connection.get_network(state.net) - Nola.Irc.send_message_as(account, state.net, state.chan, "@ #{lat}, #{lon}", true, origin: __MODULE__) + # connection = Nola.Irc.Connection.get_network(state.net) + Nola.Irc.send_message_as(account, state.net, state.chan, "@ #{lat}, #{lon}", true, + origin: __MODULE__ + ) + {:ok, state} end @@ -133,62 +172,76 @@ defmodule Nola.TelegramRoom do body = if Map.get(message.meta, :self), do: text, else: "<#{nick}> #{text}" Nola.Telegram.send_message(state.id, body) end + {:ok, state} end def handle_info(info, state) do - Logger.info("UNhandled #{inspect info}") + Logger.info("UNhandled #{inspect(info)}") {:ok, state} end - defp upload(_type, %{"message" => m = %{"chat" => %{"id" => chat_id}, "from" => from = %{"id" => user_id}}}, token, state) do + defp upload( + _type, + %{"message" => m = %{"chat" => %{"id" => chat_id}, "from" => from = %{"id" => user_id}}}, + token, + state + ) do account = find_or_create_meta_account(from, state) + if account do - {content, type} = cond do - m["photo"] -> {m["photo"], "photo"} - m["voice"] -> {m["voice"], "voice message"} - m["video"] -> {m["video"], "video"} - m["document"] -> {m["document"], "file"} - m["animation"] -> {m["animation"], "gif"} - end + {content, type} = + cond do + m["photo"] -> {m["photo"], "photo"} + m["voice"] -> {m["voice"], "voice message"} + m["video"] -> {m["video"], "video"} + m["document"] -> {m["document"], "file"} + m["animation"] -> {m["animation"], "gif"} + end - file = if is_list(content) && Enum.count(content) > 1 do - Enum.sort_by(content, fn(p) -> p["file_size"] end, &>=/2) - |> List.first() - else - content - end + file = + if is_list(content) && Enum.count(content) > 1 do + Enum.sort_by(content, fn p -> p["file_size"] end, &>=/2) + |> List.first() + else + content + end file_id = file["file_id"] file_unique_id = file["file_unique_id"] text = if(m["caption"], do: m["caption"] <> " ", else: "") - spawn(fn() -> - with \ - {:ok, file} <- Telegram.Api.request(token, "getFile", file_id: file_id), - path = "https://api.telegram.org/file/bot#{token}/#{file["file_path"]}", - {:ok, %HTTPoison.Response{status_code: 200, body: body}} <- HTTPoison.get(path), - <<smol_body::binary-size(20), _::binary>> = body, - {:ok, magic} <- GenMagic.Pool.perform(Nola.GenMagic, {:bytes, smol_body}), - bucket = Application.get_env(:nola, :s3, []) |> Keyword.get(:bucket), - ext = Path.extname(file["file_path"]), - s3path = "#{account.id}/#{file_unique_id}#{ext}", - s3req = ExAws.S3.put_object(bucket, s3path, body, acl: :public_read, content_type: magic.mime_type), - {:ok, _} <- ExAws.request(s3req) - do + spawn(fn -> + with {:ok, file} <- Telegram.Api.request(token, "getFile", file_id: file_id), + path = "https://api.telegram.org/file/bot#{token}/#{file["file_path"]}", + {:ok, %HTTPoison.Response{status_code: 200, body: body}} <- HTTPoison.get(path), + <<smol_body::binary-size(20), _::binary>> = body, + {:ok, magic} <- GenMagic.Pool.perform(Nola.GenMagic, {:bytes, smol_body}), + bucket = Application.get_env(:nola, :s3, []) |> Keyword.get(:bucket), + ext = Path.extname(file["file_path"]), + s3path = "#{account.id}/#{file_unique_id}#{ext}", + s3req = + ExAws.S3.put_object(bucket, s3path, body, + acl: :public_read, + content_type: magic.mime_type + ), + {:ok, _} <- ExAws.request(s3req) do path = NolaWeb.Router.Helpers.url(NolaWeb.Endpoint) <> "/files/#{s3path}" txt = "#{type}: #{text}#{path}" - #connection = Nola.Irc.Connection.get_network(state.net) + # connection = Nola.Irc.Connection.get_network(state.net) Nola.Irc.send_message_as(account, state.net, state.chan, txt, true, origin: __MODULE__) else error -> - Telegram.Api.request(token, "sendMessage", chat_id: chat_id, text: "File upload failed, sorry.") - Logger.error("Failed upload from Telegram: #{inspect error}") + Telegram.Api.request(token, "sendMessage", + chat_id: chat_id, + text: "File upload failed, sorry." + ) + + Logger.error("Failed upload from Telegram: #{inspect(error)}") end end) {:ok, state} end end - end |