From 17a6f1cc45e78f7dddcf4c890cc786441b6020f9 Mon Sep 17 00:00:00 2001 From: notohh Date: Mon, 17 Jun 2024 16:04:50 -0400 Subject: [PATCH] feat: add commands & refactor refactored how helix api is handled, + other stuff rename fill -> massping --- src/api.rs | 61 ++++++++++++++++++++++++++++------------ src/commands/lastfm.rs | 9 +++--- src/commands/massping.rs | 54 +++++++++++++++++++++++++++++++++++ src/commands/mod.rs | 1 + src/commands/ping.rs | 6 ++-- src/commands/user.rs | 32 ++++++++++----------- src/main.rs | 12 +++++--- 7 files changed, 131 insertions(+), 44 deletions(-) create mode 100644 src/commands/massping.rs diff --git a/src/api.rs b/src/api.rs index b19a15a..93723a4 100644 --- a/src/api.rs +++ b/src/api.rs @@ -4,22 +4,47 @@ use reqwest::{ }; use std::env; -pub fn helix_client() -> Client { - let twitch_client_id = env::var("TWITCH_CLIENT_ID").expect("a"); - let twitch_bearer = env::var("TWITCH_BEARER").expect("a"); - - let mut headers = HeaderMap::new(); - - headers.insert( - "Authorization", - HeaderValue::from_str(&twitch_bearer).expect("a"), - ); - headers.insert( - "Client-Id", - HeaderValue::from_str(&twitch_client_id).expect("a"), - ); - - let client = Client::builder().default_headers(headers).build().unwrap(); - - return client; +pub struct HelixClient { + pub base_url: String, + pub headers: HeaderMap, + pub client: Client, } + +// pub struct GqlClient { +// pub base_url: String, +// pub headers: HeaderMap, +// pub client: Client, +// } + +impl HelixClient { + pub fn new(base_url: &str) -> HelixClient { + let twitch_client_id = env::var("TWITCH_CLIENT_ID").expect("a"); + let twitch_auth_token = env::var("TWITCH_AUTH").expect("a"); + + let mut headers = HeaderMap::new(); + + headers.insert( + "Authorization", + HeaderValue::from_str(&twitch_auth_token).expect("a"), + ); + headers.insert( + "Client-Id", + HeaderValue::from_str(&twitch_client_id).expect("a"), + ); + + let client = Client::builder() + .default_headers(headers.clone()) + .build() + .unwrap(); + + HelixClient { + base_url: base_url.to_string(), + headers, + client, + } + } +} + +// impl GqlClient { +// pub fn new() {} +// } diff --git a/src/commands/lastfm.rs b/src/commands/lastfm.rs index 79f28fc..2659eab 100644 --- a/src/commands/lastfm.rs +++ b/src/commands/lastfm.rs @@ -2,6 +2,7 @@ use crate::client::TwitchClient; use dotenv::dotenv; use serde::{Deserialize, Serialize}; use std::env; +use std::error::Error; use twitch_irc::message::PrivmsgMessage; @@ -75,7 +76,7 @@ pub enum Size { Small, } -pub async fn lastfm_command(m: &PrivmsgMessage, c: &TwitchClient) { +pub async fn lastfm_command(m: &PrivmsgMessage, c: &TwitchClient) -> Result<(), Box> { dotenv().ok(); let lastfm_api_key = env::var("LASTFM_API_KEY").expect("Failed to load lastfm api key."); @@ -91,7 +92,7 @@ pub async fn lastfm_command(m: &PrivmsgMessage, c: &TwitchClient) { match client.get(recent_tracks_url).send().await { Ok(response) => { if response.status().is_success() { - let body = response.text().await.unwrap_or_default(); + let body = response.text().await?; match serde_json::from_str::(&body) { Ok(payload) => { if let Some(tracks) = payload.recenttracks.track.first() { @@ -101,8 +102,7 @@ pub async fn lastfm_command(m: &PrivmsgMessage, c: &TwitchClient) { ); c.twitch_client .say(m.channel_login.to_owned(), s.to_owned()) - .await - .expect("Error sending message to twitch"); + .await? } } Err(e) => error!("{}", e), @@ -113,4 +113,5 @@ pub async fn lastfm_command(m: &PrivmsgMessage, c: &TwitchClient) { } Err(e) => error!("Error sending request: {}", e), } + Ok(()) } diff --git a/src/commands/massping.rs b/src/commands/massping.rs new file mode 100644 index 0000000..7398dd8 --- /dev/null +++ b/src/commands/massping.rs @@ -0,0 +1,54 @@ +use dotenv::dotenv; +use std::error::Error; +use twitch_irc::message::PrivmsgMessage; + +use serde::{Deserialize, Serialize}; + +use crate::api::HelixClient; +use crate::client::TwitchClient; + +#[derive(Debug, Serialize, Deserialize)] +struct Data { + data: Vec, +} + +#[derive(Debug, Serialize, Deserialize)] +struct UserData { + user_name: String, +} + +pub async fn massping_command(m: &PrivmsgMessage, c: &TwitchClient) -> Result<(), Box> { + dotenv().ok(); + + let base_url = + "https://api.twitch.tv/helix/chat/chatters?broadcaster_id=69768189&moderator_id=69768189"; + + let helix_client = HelixClient::new(base_url).client; + + let twitch_client = c.twitch_client.clone(); + + match helix_client.get(base_url).send().await { + Ok(response) => { + if response.status().is_success() { + let body = response.text().await?; + match serde_json::from_str::(&body) { + Ok(payload) => { + for items in payload.data { + let s = items.user_name.to_string(); + twitch_client + .say(m.channel_login.to_owned(), s) + .await + .expect("Failed to send message"); + } + } + Err(e) => error!("Failed: {}", e), + } + } else { + let error = format!("Error with response: {}", response.status()); + twitch_client.say(m.channel_login.to_owned(), error).await? + } + } + Err(e) => error!("Error sending request: {}", e), + } + Ok(()) +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 22d442b..7bc4299 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,4 +1,5 @@ pub mod lastfm; pub mod logs; +pub mod massping; pub mod ping; pub mod user; diff --git a/src/commands/ping.rs b/src/commands/ping.rs index 3d747c4..8ddbfff 100644 --- a/src/commands/ping.rs +++ b/src/commands/ping.rs @@ -1,9 +1,10 @@ use crate::client::TwitchClient; use sysinfo::System; +use std::error::Error; use twitch_irc::message::PrivmsgMessage; -pub async fn ping_command(m: &PrivmsgMessage, c: &TwitchClient) { +pub async fn ping_command(m: &PrivmsgMessage, c: &TwitchClient) -> Result<(), Box> { let mut sys = System::new_all(); sys.refresh_all(); @@ -24,6 +25,7 @@ pub async fn ping_command(m: &PrivmsgMessage, c: &TwitchClient) { "🚀Pong! | ↑: {}m {}s | Host: {} | Mem: {:.2} MB", uptime_minute, remaining_seconds, host, mem ); - let _message = c.twitch_client.say(m.channel_login.to_owned(), s).await; + c.twitch_client.say(m.channel_login.to_owned(), s).await?; } + Ok(()) } diff --git a/src/commands/user.rs b/src/commands/user.rs index f502a33..87ac1fe 100644 --- a/src/commands/user.rs +++ b/src/commands/user.rs @@ -3,8 +3,9 @@ use twitch_irc::message::PrivmsgMessage; use serde::{Deserialize, Serialize}; -use crate::api::helix_client; +use crate::api::HelixClient; use crate::client::TwitchClient; +use std::error::Error; #[derive(Debug, Serialize, Deserialize)] struct Data { @@ -26,19 +27,21 @@ struct UserData { view_count: i64, } -pub async fn get_user_command(m: &PrivmsgMessage, c: &TwitchClient, a: &[&str]) { +pub async fn get_user_command( + m: &PrivmsgMessage, + c: &TwitchClient, + a: &[&str], +) -> Result<(), Box> { dotenv().ok(); - let url = format!("https://api.twitch.tv/helix/users?login={}", a.join(" ")); - - let helix_client = helix_client(); - + let base_url = format!("https://api.twitch.tv/helix/users?login={}", a.join(" ")); + let helix_client = HelixClient::new(&base_url).client; let twitch_client = c.twitch_client.clone(); - match helix_client.get(url).send().await { + match helix_client.get(base_url).send().await { Ok(response) => { if response.status().is_success() { - let body = response.text().await.unwrap_or_default(); + let body = response.text().await?; match serde_json::from_str::(&body) { Ok(payload) => { for items in payload.data { @@ -50,22 +53,19 @@ pub async fn get_user_command(m: &PrivmsgMessage, c: &TwitchClient, a: &[&str]) items.broadcaster_type.to_uppercase(), items.profile_image_url ); - twitch_client - .say(m.channel_login.to_owned(), s) - .await - .expect("Failed to send message"); + twitch_client.say(m.channel_login.to_owned(), s).await? } } Err(e) => error!("Failed: {}", e), } } else { - let error = format!("Error with response: {}", response.status()); twitch_client - .say(m.channel_login.to_owned(), error) - .await - .expect("Error sending message to twitch."); + .say(m.channel_login.to_owned(), response.status().to_string()) + .await? } } Err(e) => error!("Error sending request: {}", e), } + + Ok(()) } diff --git a/src/main.rs b/src/main.rs index 59df8f7..e04e305 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ use commands::lastfm::lastfm_command; use commands::logs::logs_command; +use commands::massping::massping_command; use commands::ping::ping_command; use commands::user::get_user_command; use std::collections::HashMap; @@ -18,8 +19,8 @@ extern crate pretty_env_logger; #[tokio::main] pub async fn main() { pretty_env_logger::try_init().expect("Failed to load logger"); - let mut initial_channels = HashMap::new(); + let mut initial_channels = HashMap::new(); let mut client = client(); initial_channels.insert("notnotoh", ()); @@ -50,10 +51,13 @@ pub async fn main() { let arguments: Vec<&str> = parts.collect(); match command { - "ping" => ping_command(&msg, &client).await, - "song" => lastfm_command(&msg, &client).await, - "user" => get_user_command(&msg, &client, &arguments).await, + "ping" => ping_command(&msg, &client).await.unwrap_or_default(), + "song" => lastfm_command(&msg, &client).await.unwrap_or_default(), + "user" => get_user_command(&msg, &client, &arguments) + .await + .unwrap_or_default(), "logs" => logs_command(&msg, &client, &arguments).await, + "massping" => massping_command(&msg, &client).await.unwrap_or_default(), _ => {} } }