Current section
Files
Jump to
Current section
Files
src/telega_wisp.erl
-module(telega_wisp).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/telega_wisp.gleam").
-export([handle_bot/3]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
-file("src/telega_wisp.gleam", 58).
-spec is_secret_token_valid(
telega:telega(any(), any(), any()),
gleam@http@request:request(any())
) -> boolean().
is_secret_token_valid(Telega, Req) ->
Secret_header_value = begin
_pipe = gleam@http@request:get_header(
Req,
<<"x-telegram-bot-api-secret-token"/utf8>>
),
gleam@result:unwrap(_pipe, <<""/utf8>>)
end,
telega:is_secret_token_valid(Telega, Secret_header_value).
-file("src/telega_wisp.gleam", 69).
-spec is_bot_request(
telega:telega(any(), any(), any()),
gleam@http@request:request(wisp@internal:connection())
) -> boolean().
is_bot_request(Telega, Req) ->
Path = begin
_pipe = fun gleam@http@request:path_segments/1(Req),
gleam@string:join(_pipe, <<"/"/utf8>>)
end,
telega:is_webhook_path(Telega, Path).
-file("src/telega_wisp.gleam", 29).
?DOC(
" A middleware function to handle incoming requests from the Telegram API.\n"
" Handles a request to the bot webhook endpoint, decodes the incoming message,\n"
" validates the secret token, and passes the message to the bot for processing.\n"
"\n"
" ```gleam\n"
" import wisp.{type Request, type Response}\n"
" import telega.{type Bot}\n"
" import telega_wisp\n"
"\n"
" fn handle_request(bot: Bot, req: Request) -> Response {\n"
" use <- telega_wisp.handle_bot(req, bot)\n"
" // ...\n"
" }\n"
" ```\n"
).
-spec handle_bot(
telega:telega(any(), any(), any()),
gleam@http@request:request(wisp@internal:connection()),
fun(() -> gleam@http@response:response(wisp:body()))
) -> gleam@http@response:response(wisp:body()).
handle_bot(Telega, Req, Handler) ->
gleam@bool:lazy_guard(
not is_bot_request(Telega, Req),
Handler,
fun() ->
wisp:require_json(
Req,
fun(Json) ->
gleam@bool:lazy_guard(
not is_secret_token_valid(Telega, Req),
fun() -> wisp:response(401) end,
fun() ->
gleam@bool:lazy_guard(
telega:is_draining(Telega),
fun() -> wisp:response(503) end,
fun() ->
proc_lib:spawn_link(
fun() ->
case telega@update:decode_raw(Json) of
{ok, Message} ->
telega:handle_update(
Telega,
Message
),
nil;
{error, E} ->
erlang:error(
#{gleam_error => panic,
message => (<<"Failed to decode update"/utf8,
(telega@error:to_string(
E
))/binary>>),
file => <<?FILEPATH/utf8>>,
module => <<"telega_wisp"/utf8>>,
function => <<"handle_bot"/utf8>>,
line => 51}
)
end
end
),
wisp:ok()
end
)
end
)
end
)
end
).