Current section
Files
Jump to
Current section
Files
src/telega@adapters@wisp.erl
-module(telega@adapters@wisp).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-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/adapters/wisp.gleam", 74).
-spec is_bot_request(
telega:telega(any(), any()),
gleam@http@request:request(any())
) -> boolean().
is_bot_request(Telega, Req) ->
case fun gleam@http@request:path_segments/1(Req) of
[Segment] ->
telega:is_webhook_path(Telega, Segment);
_ ->
false
end.
-file("src/telega/adapters/wisp.gleam", 66).
-spec is_secret_token_valid(
telega:telega(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/adapters/wisp.gleam", 34).
?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/adapters/wisp as telega_wisp\n"
"\n"
" fn handle_request(req: Request, bot: Bot) -> Response {\n"
" use <- telega_wisp.handle_bot(req)\n"
" // ...\n"
" }\n"
" ```\n"
).
-spec handle_bot(
gleam@http@request:request(wisp@internal:connection()),
telega:telega(any(), any()),
fun(() -> gleam@http@response:response(wisp:body()))
) -> gleam@http@response:response(wisp:body()).
handle_bot(Req, Telega, Handler) ->
gleam@bool:lazy_guard(
not is_bot_request(Telega, Req),
Handler,
fun() ->
wisp:require_json(
Req,
fun(Json) -> case telega@update:decode(Json) of
{ok, Message} ->
gleam@bool:lazy_guard(
not is_secret_token_valid(Telega, Req),
fun() -> {response, 401, [], empty} end,
fun() ->
gleam@otp@task:async(
fun() ->
telega:handle_update(
Telega,
Message
)
end
),
wisp:ok()
end
);
{error, Error} ->
case Error of
{unknown_update_error, Update} ->
telega@internal@log:warn(
<<"Unknown update received: "/utf8,
(gleam@string:inspect(Update))/binary>>
),
wisp:ok();
_ ->
wisp:internal_server_error()
end
end end
)
end
).