defmodule Esperantisto.Speaker do
@moduledoc """
Modulo kiu efektivigas ropotprogramon por Telegram
"""
use GenServer
require Logger
alias Esperantisto.DB
defmodule State do
defstruct offset: 0
end
def start_link(args) do
GenServer.start_link(__MODULE__, args)
end
@impl true
def init(_args) do
{:ok, %State{}, {:continue, :schedule}}
end
@impl true
def handle_continue(:schedule, state = %State{offset: offset}) do
new_offset = check(offset)
{:noreply, %{state | offset: new_offset}}
end
@impl true
def handle_info(:schedule, state = %State{offset: offset}) do
new_offset = check(offset)
{:noreply, %State{state | offset: new_offset}}
end
defp check(offset) do
Logger.debug("Fetching telegram updates from offset: #{offset}")
offset =
case Nadia.get_updates(limit: 1, timeout: 30, offset: offset) do
{:error, err} ->
Logger.error("Telegram error: #{err}")
offset
{:ok, resp} ->
Logger.debug("Telegram resp: #{inspect(resp)}")
case resp do
[] ->
offset
[update] ->
handle_update(update)
update.update_id + 1
end
end
send(self(), :schedule)
offset
end
defp handle_update(update) do
Logger.info("Got update #{inspect(update)}")
case update.message.text do
"/" <> command ->
reply = command(String.split(command))
case Nadia.send_message(update.message.chat.id, reply) do
{:ok, _} ->
:ok
{:error, err} ->
Logger.error("Telegram error: #{err}")
:ok
end
_ ->
:ok
end
end
defp command([cmd]) do
cmd_without_params(cmd)
end
defp cmd_without_params("word") do
DB.random_word()
end
defp cmd_without_params(cmd) do
Logger.warning("Unknown command #{cmd}")
end
end