diff options
author | href <href@random.sh> | 2021-09-02 05:57:21 +0200 |
---|---|---|
committer | href <href@random.sh> | 2021-09-02 06:37:06 +0200 |
commit | fccd0d02849f4a800fe878cb43f239f3d5e28636 (patch) | |
tree | 8bb20091bd3c9e723b25d6e7d85e1dc9e733cb0f /lib/lsg/telegram_room.ex | |
parent | Revert "preums: remove migration code" (diff) |
telegram: plumb room
Diffstat (limited to '')
-rw-r--r-- | lib/lsg/telegram_room.ex | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/lib/lsg/telegram_room.ex b/lib/lsg/telegram_room.ex new file mode 100644 index 0000000..8c228e1 --- /dev/null +++ b/lib/lsg/telegram_room.ex @@ -0,0 +1,55 @@ +defmodule LSG.TelegramRoom do + require Logger + @behaviour Telegram.ChatBot + alias Telegram.Api + + @impl Telegram.ChatBot + def init(id) do + token = Keyword.get(Application.get_env(:lsg, :telegram, []), :key) + {:ok, chat} = Api.request(token, "getChat", chat_id: id) + Logger.debug("Starting ChatBot for room #{id} \"#{chat["title"]}\"") + [net, chan] = String.split(chat["title"], "/", parts: 2) + case IRC.Connection.get_network(net, chan) do + %IRC.Connection{} -> + :global.register_name({__MODULE__, net, chan}, self()) + {:ok, _} = Registry.register(IRC.PubSub, "#{net}/#{chan}:message", plugin: __MODULE__) + {:ok, _} = Registry.register(IRC.PubSub, "#{net}/#{chan}:triggers", plugin: __MODULE__) + err -> + Logger.warn("Did not found telegram match for #{id} \"#{chat["title"]}\"") + end + {:ok, %{id: id, net: net, chan: chan}} + end + + def handle_update(%{"message" => %{"from" => %{"id" => user_id}, "text" => text}}, _token, state) do + account = IRC.Account.find_meta_account("telegram-id", user_id) + user = IRC.UserTrack.find_by_account(state.net, account) + nick = if(user, do: user.nick, else: account.name) + prefix = "<#{nick}> " + IRC.Connection.broadcast_message(state.net, state.chan, "#{prefix}#{text}") + {:ok, state} + end + + def handle_update(update, token, state) do + {:ok, state} + end + + def handle_info({:irc, _, %IRC.Message{sender: %{nick: nick}, text: text}}, state) do + LSG.Telegram.send_message(state.id, "<#{nick}> #{text}") + {:ok, state} + end + + def handle_info({:raw, lines}, state) when is_list(lines) do + formatted = for l <- lines, into: <<>>, do: l <> "\n" + LSG.Telegram.send_message(state.id, formatted) + {:ok, state} + end + + def handle_info({:raw, line}, state) do + handle_info({:raw, [line]}, state) + end + + def handle_info(info, state) do + {:ok, state} + end + +end |