# Poll Telegram API until response

**URL:** <https://forum.elixirforum.com/t/poll-telegram-api-until-response/16246>\
**Category:** Questions\
**Tags:** asynchronous\
**Created:** [September 2, 2018, 3:56pm UTC](https://forum.elixirforum.com/t/poll-telegram-api-until-response/16246 "2018-09-02T15:56:57Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![idi527](https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/i/85e7bf/32.png) [@idi527](https://forum.elixirforum.com/u/idi527)\
**Post date:** [September 2, 2018, 5:13pm UTC](https://forum.elixirforum.com/t/poll-telegram-api-until-response/16246/4 "2018-09-02T17:13:15Z")

</div>

Ah, I seem to have misunderstood the question then …

I’ve never used telegram’s polling api, but I guess the same principles as with webhooks would apply – in general, I abstract the polling / webhooks into a separate process which acts as a “telegram message producer” and allows other processes to subscribe to it, I then have another processes for it as consumers which in their turn output “actions” for a “telegram broadcaster” process … (The last one acting as a queue because telegram doesn’t allow sending more than 30 messages per second).

In your case however, it seems that this is not necessary. So maybe you can have a single process that would keep a map of auth codes as its state and match against them for every incoming message:

```elixir
defmodule Auther do
  @moduledoc """
  Polls for new messages from telegram and compares them with auth codes
  """
  use GenServer

  defstruct :last_update_id, :auth_codes

  @doc false
  def start_link(opts) do
    GenServer.start_link( __MODULE__ , opts, name: opts[:name])
  end

  @doc false
  def init(opts) do
    send(self(), :poll)
    last_update_id = opts[:update_id] || 0
    {:ok, % __MODULE__ {last_update_id: last_update_id, auth_codes: %{}}}
  end

  @doc false
  def handle_info(:poll, state) do
    case get_updates(last_update_id) do
      [] ->
        Process.send_after(self(), :poll, 5000)
        {:noreply, state}
      new_messages ->
        {:noreply, handle_new_messages(state, new_messages)}
    end
  end

  defp handle_new_messages(state, new_messages) do
    [%{id: last_update_id} | _rest] = :lists.reverse(new_messages)
    auth_codes = # iterate over messages, get the ones that provide new auth codes or what have you
    %{state | last_update_id: last_update_id, auth_codes: auth_codes}
  end

  defp get_updates(last_update_id) do
    # gets updates since the last_update_id
  end
end

```

The map could look like `%{chat_id => auth_code}`, so when you receive a message for `chat_id`, you compare the contents of that message with `auth_code` and then do something about it …

---

_[View the full topic](https://forum.elixirforum.com/t/poll-telegram-api-until-response/16246)._
