munin/source/targets/telegram_bot.ts
2025-06-30 13:02:06 +02:00

154 lines
3.3 KiB
TypeScript

/*
This file is part of »munin«.
Copyright 2025 'Fenris Wolf' <fenris@folksprak.org>
»munin« is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
»munin« is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with »munin«. If not, see <http://www.gnu.org/licenses/>.
*/
namespace _munin.targets.telegram_bot
{
/**
*/
export type type_parameters = {
bot_token : string;
chat_id : int;
hide_tags : boolean;
reminders : Array<_munin.type_reminder>;
};
/**
*/
function render_event(
parameters : type_parameters,
labels : _munin.type_labels,
event : _munin.type_event
) : string
{
return lib_plankton.string.coin(
"{{title_label}} | {{macro_tags}}{{title_value}}\n{{time_label}} | {{time_value}}{{macro_location}}{{macro_description}}",
{
"macro_tags": (
(parameters.hide_tags || (event.tags === null))
?
""
:
(event.tags.map(tag => ("{" + tag + "}")).join(" ") + " ")
),
"title_label": labels.title.toUpperCase(),
"title_value": event.title,
"time_label": labels.time.toUpperCase(),
"time_value": lib_plankton.pit.timespan_format(
event.begin,
event.end,
{
"adjust_to_ce": true,
}
),
"macro_location": (
(event.location === null)
?
""
:
lib_plankton.string.coin(
"\n{{location_label}} | {{location_value}}",
{
"location_label": labels.location.toUpperCase(),
"location_value": event.location,
}
)
),
"macro_description": (
(event.description === null)
?
""
:
lib_plankton.string.coin(
"\n\n{{description_value}}",
{
"description_value": event.description,
}
)
),
}
);
}
/**
*/
async function send(
parameters : type_parameters,
labels : _munin.type_labels,
events : Array<_munin.type_event>
) : Promise<void>
{
await lib_plankton.telegram.bot_call_send_message(
parameters.bot_token,
parameters.chat_id,
lib_plankton.string.coin(
"*{{head_core}}{{head_extra}}*\n\n{{events}}",
{
"head_core": labels.head,
"head_extra": (
(events.length <= 1)
?
""
:
lib_plankton.string.coin(
" ({{count}} {{events}})",
{
"count": events.length.toFixed(0),
"events": labels.events,
}
)
),
"events": (
events
.map(event => render_event(parameters, labels, event))
.join("\n\n---\n\n")
),
}
),
{
"parse_mode": "Markdown",
}
);
}
/**
*/
export function implementation_target(
parameters : type_parameters
) : _munin.type_target
{
return {
"reminders": parameters.reminders,
"show": () => lib_plankton.string.coin(
"telegram:{{chat_id}}",
{
"chat_id": parameters.chat_id.toFixed(0),
}
),
"send": (labels, events) => send(parameters, labels, events),
};
}
}