This repository has been archived on 2024-07-25. You can view files and clone it, but cannot push or open issues or pull requests.
yandexgpt_tg_bot/main.mjs

70 lines
1.6 KiB
JavaScript

import TelegramBot from "node-telegram-bot-api";
import {
option,
readerTaskEither as rte,
readonlyArray,
semigroup,
string,
} from "fp-ts";
import { flow, pipe } from "fp-ts/lib/function.js";
import { describeArticle } from "./api.mjs";
import config from "./config.mjs";
const bot = new TelegramBot(config.telegramBotToken, {
polling: true,
});
console.log("The telegram bot listens for updates");
bot.on("channel_post", async (msg) => {
const link = extractMessageLink(msg);
if (option.isNone(link)) {
console.log("cannot find link in msg:", msg);
return;
}
pipe(
describeArticle(link.value),
rte.map(
flow(
readonlyArray.foldMap({
...string.Monoid,
...pipe(string.Semigroup, semigroup.intercalate("\n")),
})((row) => `- ${row}`),
string.trimLeft,
),
),
rte.match(
(err) => console.log({ err }),
(res) =>
bot.editMessageText(msg.text + "\n\nYandexGPT:\n\n" + res, {
chat_id: msg.chat.id,
message_id: msg.message_id,
}),
),
)(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";
}