horoscope.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. const req = require('request'),
  2. { JSDOM } = require('jsdom'),
  3. https = require('https');
  4. const SIGNS = JSON.parse(process.env.SIGNS),
  5. CHANNEL = "#jenkins-up";
  6. (function() {
  7. function upperCaseFirstLetter(str) {
  8. return str.substr(0, 1).toUpperCase() +str.substr(1).toLowerCase();
  9. }
  10. function horoscopesToAttachments(horoscopes) {
  11. return horoscopes.map(i => {
  12. return {
  13. title: i.sign,
  14. title_link: i.source,
  15. text: i.text,
  16. thumb_url: i.image,
  17. fields: [{
  18. title: "Personnes",
  19. value: i.people.join(", "),
  20. short: false
  21. }]
  22. };
  23. }).sort((a, b) => a.title.localeCompare(b.title));
  24. }
  25. function horoscopesToSingleAttachment(horoscopes) {
  26. const signsEmojis = {
  27. balance: ":libra:",
  28. belier: ":aries:",
  29. taureau: ":taurus:",
  30. gemeaux: ":gemini:",
  31. cancer: ":cancer:",
  32. lion: ":leo:",
  33. vierge: ":virgo:",
  34. scorpion: ":scorpius:",
  35. sagittaire: ":sagittarius:",
  36. capricorne: ":capricorn:",
  37. verseau: ":aquarius:",
  38. poisson: ":pisces:"
  39. };
  40. return [{
  41. text: horoscopes.sort((a, b) => a.sign.localeCompare(b.sign)).map(i => {
  42. return signsEmojis[i.sign.toLowerCase()] +" *<" +i.source +"|" +i.sign +">*\n" +
  43. i.text +'\n' +
  44. "_" +i.people.join(", ") +"_";
  45. }).join("\n\n")
  46. }];
  47. }
  48. function sendMsg(horoscopes) {
  49. const req = https.request({
  50. hostname: 'team-009.slack.com',
  51. port: 443,
  52. path: '/services/hooks/jenkins-ci?token=' +process.env.JENKINS_TOKEN,
  53. method: 'POST',
  54. }, (res) => {
  55. console.log(`statusCode: ${res.statusCode}`);
  56. res.on('data', d => console.log(new String(d)));
  57. });
  58. var data = {
  59. channel: CHANNEL,
  60. text: "Bien le bonjour. Voici les horoscopes de la semaine.",
  61. attachments: horoscopesToSingleAttachment(horoscopes)
  62. };
  63. req.write(JSON.stringify(data));
  64. req.end();
  65. }
  66. function getHoroscope(sign, people) {
  67. return new Promise((res, rej) => {
  68. const url = "http://www.elle.fr/Astro/Horoscope/Hebdo/" +sign;
  69. req.get(url, (err, _, body) => {
  70. if (err) {
  71. console.error("Cannot get horoscope for sign " +sign, err);
  72. res({ sign: sign });
  73. return;
  74. }
  75. var dom = new JSDOM(body);
  76. res({
  77. sign: sign,
  78. source: url,
  79. people: people,
  80. image: "http://knacki.info/zodiac/" +sign.toLowerCase() +".png",
  81. text: dom.window.document.querySelector(".zone-resultat").textContent
  82. });
  83. });
  84. });
  85. }
  86. Promise.all(Object.keys(SIGNS).map(i => getHoroscope(upperCaseFirstLetter(i), SIGNS[i]))).then(results => sendMsg(results));
  87. })();