move message utils to a separate file

This commit is contained in:
Dmitriy Pleshevskiy 2023-07-02 11:41:03 +03:00
parent 961f494fa2
commit b74e24da32
Signed by: pleshevskiy
GPG Key ID: 79C4487B44403985
3 changed files with 33 additions and 28 deletions

View File

@ -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": {

View File

@ -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";
}

28
message.mjs Normal file
View File

@ -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<string>
const getMessageUrl = (msg) => option.fromNullable(RE_URL.exec(msg.text)?.[0]);
// getMessageEntities :: Message -> ReadonlyArray<MessageEntity>
const getMessageEntities = (msg) => msg.entities ?? readonlyArray.empty;
// isTextLink :: MessageEntity -> boolean
const isTextLink = (msgEntity) => msgEntity.type === "text_link";
// getTextLink :: Message -> Option<string>
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)),
);