handler.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import type { Handler } from "aws-lambda";
  2. import { createRestAPIClient } from "masto";
  3. import "dotenv/config";
  4. import ScraperArticles from "../../utils/scraper-articles";
  5. import RedisClient from "../../libs/redis-client";
  6. import config from "../../config";
  7. import LogLevels from "../../enums/log-levels";
  8. import Emojis from "../../enums/emojis";
  9. export const handler: Handler = async (event, context) => {
  10. const name = "The Clinic";
  11. try {
  12. const redisClient = new RedisClient();
  13. const mastodon = createRestAPIClient({
  14. url: config.MASTODON_URL,
  15. accessToken: config.MASTODON_ACCESS_TOKEN
  16. });
  17. const scraperArticles = new ScraperArticles(name, {
  18. url: config.THECLINIC,
  19. articlesSelector: ".listado article",
  20. titleSelector: ".titulares h2 a",
  21. contentSelector: ".titulares h2 a",
  22. linkSelector: ".titulares h2 a",
  23. imageSelector: ".imagen-post a img",
  24. authorSelector: "",
  25. dateSelector: ""
  26. });
  27. const articles = await scraperArticles.getArticles();
  28. if (config.LOG_LEVEL === LogLevels.DEBUG) {
  29. console.log("Articles", articles);
  30. }
  31. let totalPublished = 0;
  32. const length = articles.length;
  33. // Order has to be reversed to appear in the correct order when posting
  34. for (let i = length - 1; i >= 0; i--) {
  35. const article = articles[i];
  36. const exists = await redisClient.retrieve(article.link);
  37. if (exists !== null) {
  38. continue;
  39. }
  40. const date = new Date(Date.now()).toLocaleDateString();
  41. const message = `${Emojis.NEWS} ${article.title}\n${article.link}`;
  42. if (message.trim().length === 0) {
  43. continue;
  44. }
  45. console.log("\nSending", message);
  46. await mastodon.v1.statuses.create({ status: message });
  47. await redisClient.store(article.link, date, { EX: 60 * 60 * 24 }); // EX: 24 hrs expiration
  48. totalPublished++
  49. }
  50. console.log(`Published ${totalPublished} new articles`);
  51. } catch (err: any) {
  52. console.log('An error has occurred\n')
  53. console.error(err.message);
  54. if (config.LOG_LEVEL === LogLevels.DEBUG) {
  55. console.debug("\nEvent\n");
  56. console.debug(event);
  57. console.debug("\nContext\n");
  58. console.debug(context);
  59. }
  60. }
  61. return "The End.";
  62. };