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]).
-define(FILEPATH, "src/telega/adapters/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/adapters/wisp.gleam", 60).
-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", 52).
-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", 31).
?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(bot: Bot, req: Request) -> Response {\n"
" use <- telega_wisp.handle_bot(req, bot)\n"
" // ...\n"
" }\n"
" ```\n"
).
-spec handle_bot(
telega:telega(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() -> {response, 401, [], empty} end,
fun() ->
proc_lib:spawn_link(
fun() ->
Message@1 = case telega@update:decode_raw(
Json
) of
{ok, Message} -> Message;
_assert_fail ->
erlang:error(
#{gleam_error => let_assert,
message => <<"Pattern match failed, no pattern matched the value."/utf8>>,
file => <<?FILEPATH/utf8>>,
module => <<"telega/adapters/wisp"/utf8>>,
function => <<"handle_bot"/utf8>>,
line => 45,
value => _assert_fail,
start => 1426,
'end' => 1474,
pattern_start => 1437,
pattern_end => 1448}
)
end,
telega:handle_update(Telega, Message@1)
end
),
wisp:ok()
end
)
end
)
end
).