2023-06-28 14:45:04 +03:00
|
|
|
import TelegramBot from "node-telegram-bot-api";
|
|
|
|
import {
|
2023-07-01 14:06:47 +03:00
|
|
|
option,
|
2023-06-28 14:45:04 +03:00
|
|
|
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,
|
|
|
|
});
|
|
|
|
|
2023-07-01 00:32:58 +03:00
|
|
|
console.log("The telegram bot listens for updates");
|
|
|
|
|
2023-06-28 14:45:04 +03:00
|
|
|
bot.on("channel_post", async (msg) => {
|
|
|
|
const link = extractMessageLink(msg);
|
2023-07-01 14:06:47 +03:00
|
|
|
if (option.isNone(link)) {
|
2023-07-01 00:32:58 +03:00
|
|
|
console.log("cannot find link in msg:", msg);
|
|
|
|
return;
|
|
|
|
}
|
2023-06-28 14:45:04 +03:00
|
|
|
|
|
|
|
pipe(
|
2023-07-01 14:06:47 +03:00
|
|
|
describeArticle(link.value),
|
2023-06-28 14:45:04 +03:00
|
|
|
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) {
|
2023-07-01 14:06:47 +03:00
|
|
|
return pipe(
|
|
|
|
getTextLink(msg),
|
|
|
|
option.orElse(() => getMessageUrl(msg)),
|
|
|
|
);
|
2023-07-01 00:32:58 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
const RE_URL =
|
|
|
|
/(http|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])/;
|
|
|
|
|
|
|
|
function getMessageUrl(msg) {
|
2023-07-01 14:06:47 +03:00
|
|
|
return option.fromNullable(RE_URL.exec(msg.text)?.[0]);
|
2023-07-01 00:32:58 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
function getTextLink(msg) {
|
2023-07-01 14:06:47 +03:00
|
|
|
return readonlyArray.findFirstMap(
|
|
|
|
flow(option.fromPredicate(isTextLink), option.map((link) => link.url)),
|
|
|
|
)(msg.entities ?? readonnlyArray.empty);
|
2023-06-28 14:45:04 +03:00
|
|
|
}
|
|
|
|
|
2023-07-01 00:32:58 +03:00
|
|
|
function isTextLink(msgEntity) {
|
2023-06-28 14:45:04 +03:00
|
|
|
return msgEntity.type === "text_link";
|
|
|
|
}
|