-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathoff_broadway_telegram.exs
63 lines (53 loc) · 1.49 KB
/
off_broadway_telegram.exs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
Mix.install([
{:off_broadway_telegram, "~> 1.0"},
{:req, "~> 0.5.7"}
])
defmodule Poller do
use Broadway
def start_link(bot_token) do
Broadway.start_link(__MODULE__,
name: __MODULE__,
producer: [
module:
{OffBroadway.Telegram.Producer,
[
client: {OffBroadway.Telegram.ReqClient, [token: bot_token]}
]},
concurrency: 1
],
processors: [
default: [concurrency: 2]
]
)
end
@impl Broadway
def handle_message(_processor, %Broadway.Message{} = message, _context) do
message.data
|> IO.inspect(label: "UPDATE")
|> EchoBot.process_message()
message
end
end
defmodule EchoBot do
def secret_bot_token(), do: "your_bot_token"
def process_message(%{"message" => %{"text" => text, "chat" => %{"id" => chat_id}}})
when is_binary(text) do
send_response(chat_id, text)
end
def process_message(%{"message" => %{"chat" => %{"id" => chat_id}}}) do
send_response(chat_id, "Huh?")
end
def send_response(chat_id, text) do
Req.post!("https://api.telegram.org/bot{token}/sendMessage",
json: %{chat_id: chat_id, text: text},
path_params: [token: secret_bot_token()],
path_params_style: :curly
)
end
end
poller = {Poller, [EchoBot.secret_bot_token()]}
{:ok, _} = Supervisor.start_link([poller], strategy: :one_for_one)
# unless running from IEx, sleep idenfinitely so we can serve requests
unless IEx.started?() do
Process.sleep(:infinity)
end