Skip to content

Commit

Permalink
feat: Lighthouse command
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanccn committed Nov 22, 2023
1 parent 27cb927 commit 7eca739
Show file tree
Hide file tree
Showing 3 changed files with 119 additions and 10 deletions.
105 changes: 105 additions & 0 deletions src/commands/lighthouse.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
use anyhow::Result;
use std::{collections::HashMap, env, time::Duration};

use poise::{serenity_prelude as serenity, CreateReply};
use serde::{Deserialize, Serialize};

use crate::{reqwest_client::HTTP, Context};

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct LighthouseAuditData {
id: String,
title: String,
description: Option<String>,
score: f32,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct LighthouseResultData {
categories: HashMap<String, LighthouseAuditData>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct PagespeedResponse {
lighthouse_result: LighthouseResultData,
}

/// Run Lighthouse on a URL using Google's PageSpeed API
#[poise::command(slash_command, guild_only)]
pub async fn lighthouse(
ctx: Context<'_>,
#[description = "The URL to test"] url: String,
) -> Result<()> {
ctx.defer().await?;

if let Ok(pagespeed_token) = env::var("PAGESPEED_API_KEY") {
let reply_handle = ctx
.send(
CreateReply::new().embed(
serenity::CreateEmbed::new()
.title("Lighthouse audit in progress")
.description("This could take around a minute!")
.color(0x66d9e8)
.timestamp(serenity::Timestamp::now()),
),
)
.await?;

let mut api_url = "https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed"
.parse::<reqwest::Url>()?;

api_url
.query_pairs_mut()
.append_pair("url", &url)
.append_pair("strategy", "MOBILE")
.append_pair("category", "PERFORMANCE")
.append_pair("category", "ACCESSIBILITY")
.append_pair("category", "BEST_PRACTICES")
.append_pair("category", "SEO")
.append_pair("key", &pagespeed_token);

let resp = HTTP
.get(api_url)
.timeout(Duration::from_secs(60))
.send()
.await?;

let data: PagespeedResponse = resp.json().await?;

let mut report_embed = serenity::CreateEmbed::new()
.title("Lighthouse report")
.description(url)
.color(0x74c0fc)
.timestamp(serenity::Timestamp::now());

eprintln!(
"{:#?}",
data.lighthouse_result.categories.keys().collect::<Vec<_>>()
);

for key in ["performance", "accessibility", "best-practices", "seo"] {
if let Some(value) = data.lighthouse_result.categories.get(key) {
report_embed =
report_embed.field(&value.title, format!("{:.0}", value.score * 100.0), false);
}
}

reply_handle
.edit(ctx, CreateReply::new().embed(report_embed))
.await?;
} else {
ctx.send(
CreateReply::new().embed(
serenity::CreateEmbed::new()
.title(r#"PageSpeed API key not provided!"#)
.description(r#"The `PAGESPEED_API_KEY` environment variable is required to be set to use this command."#),
),
)
.await?;
}

Ok(())
}
22 changes: 13 additions & 9 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
use crate::Context;

pub mod owo;
pub mod ping;
pub mod pomelo;
pub mod presence;
pub mod say;
pub mod self_timeout;
pub mod shiggy;
pub mod translate;
mod lighthouse;
mod owo;
mod ping;
mod pomelo;
mod presence;
mod say;
mod self_timeout;
mod shiggy;
mod translate;

pub use presence::restore as restore_presence;

pub fn to_vec() -> Vec<
::poise::Command<
poise::Command<
<Context<'static> as poise::_GetGenerics>::U,
<Context<'static> as poise::_GetGenerics>::E,
>,
> {
vec![
lighthouse::lighthouse(),
owo::owo(),
ping::ping(),
pomelo::pomelo(),
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ async fn main() -> Result<()> {
if let Ok(redis_url) = std::env::var("REDIS_URL") {
let client = redis::Client::open(redis_url)?;

if let Err(err) = commands::presence::restore(ctx, &client).await {
if let Err(err) = commands::restore_presence(ctx, &client).await {
eprintln!("{err}");
};

Expand Down

0 comments on commit 7eca739

Please sign in to comment.