|
| 1 | +import fetch from "node-fetch"; |
1 | 2 | import { WebhookClient, EmbedBuilder } from "discord.js";
|
2 |
| -import psi from "psi"; |
3 | 3 |
|
4 |
| -// Lee la URL del webhook desde las variables de entorno |
5 |
| -const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL; |
| 4 | +const DISCORD_WEBHOOK_URL = |
| 5 | + "https://discord.com/api/webhooks/1273321658148589660/vNk13mjIiPdzMoHJBKvQ0N1Lx9Hv002EDsmvb6VNYSqPPqnk1xzeRIMWDWwbD68-kcT7"; |
| 6 | +const API_KEY = "AIzaSyDGPzB5LGUJGfNKkNc0BpTSWspGCb-Fo6c"; |
6 | 7 |
|
7 |
| -if (!DISCORD_WEBHOOK_URL) { |
8 |
| - console.error("DISCORD_WEBHOOK_URL is not defined!"); |
| 8 | +if (!DISCORD_WEBHOOK_URL || !API_KEY) { |
| 9 | + console.error("DISCORD_WEBHOOK_URL or API_KEY is not defined!"); |
9 | 10 | process.exit(1);
|
10 | 11 | }
|
11 | 12 |
|
12 |
| -// Configura el cliente de Webhook |
13 | 13 | const webhookClient = new WebhookClient({ url: DISCORD_WEBHOOK_URL });
|
14 | 14 |
|
15 |
| -// Función para ejecutar PSI y obtener los resultados |
16 |
| -const runPSI = async (strategy) => { |
| 15 | +const getCategoryScores = async (url, strategy) => { |
17 | 16 | try {
|
18 |
| - const { data } = await psi("https://alexdevuwu.com", { |
19 |
| - nokey: "true", |
20 |
| - strategy: strategy, |
| 17 | + const apiUrl = `https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=${encodeURIComponent( |
| 18 | + url |
| 19 | + )}&strategy=${strategy}&key=${API_KEY}`; |
| 20 | + |
| 21 | + const response = await fetch(apiUrl); |
| 22 | + if (!response.ok) { |
| 23 | + throw new Error(`Failed to fetch PageSpeed Insights data: ${response.statusText}`); |
| 24 | + } |
| 25 | + |
| 26 | + const data = await response.json(); |
| 27 | + |
| 28 | + if (!data || !data.lighthouseResult || !data.lighthouseResult.categories) { |
| 29 | + throw new Error(`Invalid data structure received for ${strategy}: ${JSON.stringify(data)}`); |
| 30 | + } |
| 31 | + |
| 32 | + const scores = {}; |
| 33 | + const categories = ["performance", "accessibility", "best-practices", "seo"]; |
| 34 | + categories.forEach((category) => { |
| 35 | + const categoryData = data.lighthouseResult.categories[category]; |
| 36 | + if (categoryData) { |
| 37 | + scores[category] = categoryData.score * 100; |
| 38 | + } else { |
| 39 | + console.error(`Missing ${category} category in result data for ${strategy}`); |
| 40 | + scores[category] = null; |
| 41 | + } |
21 | 42 | });
|
22 |
| - return data; |
| 43 | + |
| 44 | + return scores; |
23 | 45 | } catch (error) {
|
24 |
| - console.error(`Error running PSI for ${strategy}:`, error); |
| 46 | + console.error(`Error getting PageSpeed Insights scores for ${strategy}:`, error); |
25 | 47 | return null;
|
26 | 48 | }
|
27 | 49 | };
|
28 | 50 |
|
29 |
| -// Función para enviar un mensaje embed a Discord |
30 |
| -const sendToDiscord = async (embed) => { |
31 |
| - try { |
32 |
| - await webhookClient.send({ embeds: [embed] }); |
33 |
| - console.log("Report sent to Discord successfully!"); |
34 |
| - } catch (error) { |
35 |
| - console.error("Error sending report to Discord:", error); |
| 51 | +const createEmbed = (strategy, scores) => { |
| 52 | + if (!scores || Object.values(scores).some((score) => score === null)) { |
| 53 | + console.error(`Invalid score data for ${strategy}`); |
| 54 | + return null; |
36 | 55 | }
|
37 |
| -}; |
38 |
| - |
39 |
| -// Función para crear un mensaje embed para Discord |
40 |
| -const createEmbed = (strategy, result) => { |
41 |
| - if (!result) return null; |
42 | 56 |
|
43 | 57 | return new EmbedBuilder()
|
44 | 58 | .setTitle(`PageSpeed Insights - ${strategy}`)
|
45 |
| - .setDescription(`Results for ${strategy} strategy`) |
| 59 | + .setDescription(`Performance scores for ${strategy} strategy`) |
46 | 60 | .addFields([
|
47 | 61 | {
|
48 |
| - name: "Speed Score", |
49 |
| - value: (result.lighthouseResult.categories.performance.score * 100).toFixed(2) + "%", |
50 |
| - inline: true, |
51 |
| - }, |
52 |
| - { |
53 |
| - name: "Accessibility", |
54 |
| - value: (result.lighthouseResult.categories.accessibility.score * 100).toFixed(2) + "%", |
55 |
| - inline: true, |
| 62 | + name: "Performance Score", |
| 63 | + value: scores["performance"]?.toFixed(2) || "N/A", |
| 64 | + inline: false, |
56 | 65 | },
|
57 | 66 | {
|
58 |
| - name: "Best Practices", |
59 |
| - value: (result.lighthouseResult.categories["best-practices"].score * 100).toFixed(2) + "%", |
60 |
| - inline: true, |
| 67 | + name: "Accessibility Score", |
| 68 | + value: scores["accessibility"]?.toFixed(2) || "N/A", |
| 69 | + inline: false, |
61 | 70 | },
|
62 | 71 | {
|
63 |
| - name: "SEO", |
64 |
| - value: (result.lighthouseResult.categories.seo.score * 100).toFixed(2) + "%", |
65 |
| - inline: true, |
| 72 | + name: "Best Practices Score", |
| 73 | + value: scores["best-practices"]?.toFixed(2) || "N/A", |
| 74 | + inline: false, |
66 | 75 | },
|
67 |
| - { name: "URL", value: result.id, inline: false }, |
| 76 | + { name: "SEO Score", value: scores["seo"]?.toFixed(2) || "N/A", inline: false }, |
68 | 77 | ])
|
69 |
| - .setColor(strategy === "mobile" ? 0x00ff00 : 0x0000ff); // Verde para móvil, azul para escritorio |
| 78 | + .setColor(strategy === "mobile" ? 0x00ff00 : 0x0000ff); |
70 | 79 | };
|
71 | 80 |
|
72 |
| -// Función principal |
73 |
| -const main = async () => { |
| 81 | +const sendToDiscord = async (embed) => { |
74 | 82 | try {
|
75 |
| - // Ejecutar auditorías para móvil y escritorio |
76 |
| - const mobileResult = await runPSI("mobile"); |
77 |
| - const desktopResult = await runPSI("desktop"); |
| 83 | + await webhookClient.send({ embeds: [embed] }); |
| 84 | + console.log("Report sent to Discord successfully!"); |
| 85 | + } catch (error) { |
| 86 | + console.error("Error sending report to Discord:", error); |
| 87 | + } |
| 88 | +}; |
78 | 89 |
|
79 |
| - // Crear embebidos para cada estrategia |
80 |
| - const mobileEmbed = createEmbed("Mobile", mobileResult); |
81 |
| - const desktopEmbed = createEmbed("Desktop", desktopResult); |
| 90 | +const main = async () => { |
| 91 | + const url = "https://alexdevuwu.com"; |
| 92 | + const strategies = ["mobile", "desktop"]; |
82 | 93 |
|
83 |
| - // Enviar informes a Discord si existen |
84 |
| - if (mobileEmbed) await sendToDiscord(mobileEmbed); |
85 |
| - if (desktopEmbed) await sendToDiscord(desktopEmbed); |
86 |
| - } catch (error) { |
87 |
| - console.error("Error in audit process:", error); |
| 94 | + for (const strategy of strategies) { |
| 95 | + const scores = await getCategoryScores(url, strategy); |
| 96 | + const embed = createEmbed(strategy, scores); |
| 97 | + if (embed) await sendToDiscord(embed); |
88 | 98 | }
|
89 | 99 | };
|
90 | 100 |
|
91 |
| -// Ejecutar la función principal |
92 | 101 | main();
|
0 commit comments