diff --git a/flake.lock b/flake.lock index 31463f1..242ba6a 100644 --- a/flake.lock +++ b/flake.lock @@ -20,11 +20,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1687793116, - "narHash": "sha256-6xRgZ2E9r/BNam87vMkHJ/0EPTTKzeNwhw3abKilEE4=", + "lastModified": 1688188316, + "narHash": "sha256-CXuQllDKCxtZaB/umnZOvoJ/d4kJguYgffeTA9l1B3o=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "9e4e0807d2142d17f463b26a8b796b3fe20a3011", + "rev": "8277b539d371bf4308fc5097911aa58bfac1794f", "type": "github" }, "original": { diff --git a/main.mjs b/main.mjs index d2a7415..0f61bc5 100644 --- a/main.mjs +++ b/main.mjs @@ -8,6 +8,7 @@ import { } from "fp-ts"; import { flow, pipe } from "fp-ts/lib/function.js"; import { describeArticle } from "./api.mjs"; +import { extractMessageLink } from "./message.mjs"; import config from "./config.mjs"; const bot = new TelegramBot(config.telegramBotToken, { @@ -16,7 +17,7 @@ const bot = new TelegramBot(config.telegramBotToken, { console.log("The telegram bot listens for updates"); -bot.on("channel_post", async (msg) => { +bot.on("channel_post", (msg) => { const link = extractMessageLink(msg); if (option.isNone(link)) { console.log("cannot find link in msg:", msg); @@ -44,27 +45,3 @@ bot.on("channel_post", async (msg) => { ), )(config)(); }); - -function extractMessageLink(msg) { - return pipe( - getTextLink(msg), - option.orElse(() => getMessageUrl(msg)), - ); -} - -const RE_URL = - /(http|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])/; - -function getMessageUrl(msg) { - return option.fromNullable(RE_URL.exec(msg.text)?.[0]); -} - -function getTextLink(msg) { - return readonlyArray.findFirstMap( - flow(option.fromPredicate(isTextLink), option.map((link) => link.url)), - )(msg.entities ?? readonnlyArray.empty); -} - -function isTextLink(msgEntity) { - return msgEntity.type === "text_link"; -} diff --git a/message.mjs b/message.mjs new file mode 100644 index 0000000..19f83d4 --- /dev/null +++ b/message.mjs @@ -0,0 +1,28 @@ +import { option, readonlyArray } from "fp-ts"; +import { flow, pipe } from "fp-ts/lib/function.js"; + +const RE_URL = + /(http|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])/; + +// getMessageUrl :: Message -> Option +const getMessageUrl = (msg) => option.fromNullable(RE_URL.exec(msg.text)?.[0]); + +// getMessageEntities :: Message -> ReadonlyArray +const getMessageEntities = (msg) => msg.entities ?? readonlyArray.empty; + +// isTextLink :: MessageEntity -> boolean +const isTextLink = (msgEntity) => msgEntity.type === "text_link"; + +// getTextLink :: Message -> Option +const getTextLink = flow( + getMessageEntities, + readonlyArray.findFirstMap( + flow(option.fromPredicate(isTextLink), option.map((link) => link.url)), + ), +); + +export const extractMessageLink = (msg) => + pipe( + getTextLink(msg), + option.orElse(() => getMessageUrl(msg)), + );