Files
legica-bot/controllers/Client.controller.ts
2022-03-13 11:40:26 +01:00

56 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Client, Message, MessageEmbed, TextChannel } from "discord.js";
import * as cron from "node-cron";
import axios from "axios";
import cheerio from "cheerio";
class ClientController {
constructor(private client: Client) {}
public register = (): void => {
this.client.on("ready", (): void => {
cron.schedule("0 9 * * *", this.sendMessage);
});
};
private sendMessage = async (): Promise<void> => {
const href = await getFirstHtml();
const { img, title } = await getImgTitle(href);
this.client.channels.cache.forEach(async (channel) => {
if (channel.type !== "text") return null;
const embeddedMessage = new MessageEmbed().setTitle(title).setImage(img);
const msg = await (channel as TextChannel).send(embeddedMessage);
const reactions = ["1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6⃣", "7⃣", "8⃣", "9⃣", "🔟"];
for (const reaction of reactions) {
await msg.react(reaction);
}
});
};
}
type Legica = {
img: string;
title: string;
};
async function getImgTitle(href: string): Promise<Legica> {
const response = await axios.get(href);
const html = response.data;
const $ = cheerio.load(html);
const title = $(".Article-inner > h1").text();
const { src: img } = $(".Article-media > img")?.attr();
return { title, img };
}
async function getFirstHtml(): Promise<string> {
const response = await axios.get("https://sib.net.hr/legica-dana");
const html = response.data;
const $ = cheerio.load(html);
const { href } = $(".News-link.c-def")?.attr() || {};
return href;
}
export default ClientController;