feat: add commands & refactor

refactored how helix api is handled, + other stuff

rename fill -> massping
This commit is contained in:
notohh 2024-06-17 16:04:50 -04:00
parent b510e65052
commit 17a6f1cc45
Signed by: notohh
GPG key ID: BD47506D475EE86D
7 changed files with 131 additions and 44 deletions

View file

@ -4,22 +4,47 @@ use reqwest::{
};
use std::env;
pub fn helix_client() -> Client {
pub struct HelixClient {
pub base_url: String,
pub headers: HeaderMap<HeaderValue>,
pub client: Client,
}
// pub struct GqlClient {
// pub base_url: String,
// pub headers: HeaderMap<HeaderValue>,
// 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_bearer = env::var("TWITCH_BEARER").expect("a");
let twitch_auth_token = env::var("TWITCH_AUTH").expect("a");
let mut headers = HeaderMap::new();
headers.insert(
"Authorization",
HeaderValue::from_str(&twitch_bearer).expect("a"),
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).build().unwrap();
let client = Client::builder()
.default_headers(headers.clone())
.build()
.unwrap();
return client;
HelixClient {
base_url: base_url.to_string(),
headers,
client,
}
}
}
// impl GqlClient {
// pub fn new() {}
// }

View file

@ -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<dyn Error>> {
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::<Data>(&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(())
}

54
src/commands/massping.rs Normal file
View file

@ -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<UserData>,
}
#[derive(Debug, Serialize, Deserialize)]
struct UserData {
user_name: String,
}
pub async fn massping_command(m: &PrivmsgMessage, c: &TwitchClient) -> Result<(), Box<dyn Error>> {
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::<Data>(&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(())
}

View file

@ -1,4 +1,5 @@
pub mod lastfm;
pub mod logs;
pub mod massping;
pub mod ping;
pub mod user;

View file

@ -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<dyn Error>> {
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(())
}

View file

@ -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<dyn Error>> {
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::<Data>(&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(())
}

View file

@ -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(),
_ => {}
}
}