feat: logs && users commands

also init the helix client, and refactor a bit aswell.

fmt
This commit is contained in:
notohh 2024-06-17 11:28:10 -04:00
parent d578978a92
commit b510e65052
Signed by: notohh
GPG key ID: BD47506D475EE86D
8 changed files with 142 additions and 18 deletions

25
src/api.rs Normal file
View file

@ -0,0 +1,25 @@
use reqwest::{
header::{HeaderMap, HeaderValue},
Client,
};
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;
}

View file

@ -11,7 +11,7 @@ pub struct TwitchClient {
pub twitch_client: TwitchIRCClient<SecureTCPTransport, StaticLoginCredentials>, pub twitch_client: TwitchIRCClient<SecureTCPTransport, StaticLoginCredentials>,
} }
pub fn create_client() -> ClientConfig<StaticLoginCredentials> { pub fn client_config() -> ClientConfig<StaticLoginCredentials> {
dotenv().ok(); dotenv().ok();
let twitch_id = env::var("TWITCH_ID").expect("Failed to load twitch id"); let twitch_id = env::var("TWITCH_ID").expect("Failed to load twitch id");
@ -23,7 +23,7 @@ pub fn create_client() -> ClientConfig<StaticLoginCredentials> {
} }
pub fn client() -> TwitchClient { pub fn client() -> TwitchClient {
let config = create_client(); let config = client_config();
let (incoming_messages, twitch_client) = let (incoming_messages, twitch_client) =
TwitchIRCClient::<SecureTCPTransport, StaticLoginCredentials>::new(config); TwitchIRCClient::<SecureTCPTransport, StaticLoginCredentials>::new(config);

View file

@ -91,7 +91,7 @@ pub async fn lastfm_command(m: &PrivmsgMessage, c: &TwitchClient) {
match client.get(recent_tracks_url).send().await { match client.get(recent_tracks_url).send().await {
Ok(response) => { Ok(response) => {
if response.status().is_success() { if response.status().is_success() {
let body = response.text().await.unwrap(); let body = response.text().await.unwrap_or_default();
match serde_json::from_str::<Data>(&body) { match serde_json::from_str::<Data>(&body) {
Ok(payload) => { Ok(payload) => {
if let Some(tracks) = payload.recenttracks.track.first() { if let Some(tracks) = payload.recenttracks.track.first() {
@ -105,7 +105,7 @@ pub async fn lastfm_command(m: &PrivmsgMessage, c: &TwitchClient) {
.expect("Error sending message to twitch"); .expect("Error sending message to twitch");
} }
} }
Err(e) => eprintln!("{}", e), Err(e) => error!("{}", e),
} }
} else { } else {
error!("Response error: {}", response.status()); error!("Response error: {}", response.status());

18
src/commands/logs.rs Normal file
View file

@ -0,0 +1,18 @@
use dotenv::dotenv;
use twitch_irc::message::PrivmsgMessage;
use crate::client::TwitchClient;
pub async fn logs_command(m: &PrivmsgMessage, c: &TwitchClient, a: &[&str]) {
dotenv().ok();
let url = format!(
"https://logs.flake.sh/?channel={}&username={}",
a.first().unwrap(),
a.get(1).unwrap()
);
let twitch_client = c.twitch_client.clone();
let _response = twitch_client.say(m.channel_login.to_owned(), url).await;
}

View file

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

View file

@ -21,12 +21,9 @@ pub async fn ping_command(m: &PrivmsgMessage, c: &TwitchClient) {
let host = System::name().unwrap(); let host = System::name().unwrap();
let s = format!( let s = format!(
"Pong! | ↑: {}m {}s | Host: {} | Mem: {:.2} MB", "🚀Pong! | ↑: {}m {}s | Host: {} | Mem: {:.2} MB",
uptime_minute, remaining_seconds, host, mem uptime_minute, remaining_seconds, host, mem
); );
let _message = c let _message = c.twitch_client.say(m.channel_login.to_owned(), s).await;
.twitch_client
.say(m.channel_login.to_owned(), s.to_owned())
.await;
} }
} }

71
src/commands/user.rs Normal file
View file

@ -0,0 +1,71 @@
use dotenv::dotenv;
use twitch_irc::message::PrivmsgMessage;
use serde::{Deserialize, Serialize};
use crate::api::helix_client;
use crate::client::TwitchClient;
#[derive(Debug, Serialize, Deserialize)]
struct Data {
data: Vec<UserData>,
}
#[derive(Debug, Serialize, Deserialize)]
struct UserData {
broadcaster_type: String,
created_at: String,
description: String,
display_name: String,
id: String,
login: String,
offline_image_url: String,
profile_image_url: String,
#[serde(rename = "type")]
datum_type: String,
view_count: i64,
}
pub async fn get_user_command(m: &PrivmsgMessage, c: &TwitchClient, a: &[&str]) {
dotenv().ok();
let url = format!("https://api.twitch.tv/helix/users?login={}", a.join(" "));
let helix_client = helix_client();
let twitch_client = c.twitch_client.clone();
match helix_client.get(url).send().await {
Ok(response) => {
if response.status().is_success() {
let body = response.text().await.unwrap_or_default();
match serde_json::from_str::<Data>(&body) {
Ok(payload) => {
for items in payload.data {
let s = format!(
"Name: {} | Created: {} | ID: {} | Broadcaster status: {} | PFP: {}",
items.display_name,
items.created_at,
items.id,
items.broadcaster_type.to_uppercase(),
items.profile_image_url
);
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
.expect("Error sending message to twitch.");
}
}
Err(e) => error!("Error sending request: {}", e),
}
}

View file

@ -1,10 +1,13 @@
use commands::lastfm::lastfm_command; use commands::lastfm::lastfm_command;
use commands::logs::logs_command;
use commands::ping::ping_command; use commands::ping::ping_command;
use commands::user::get_user_command;
use std::collections::HashMap; use std::collections::HashMap;
use client::client; use client::client;
use twitch_irc::message::ServerMessage; use twitch_irc::message::ServerMessage;
mod api;
mod client; mod client;
mod commands; mod commands;
@ -22,7 +25,6 @@ pub async fn main() {
initial_channels.insert("notnotoh", ()); initial_channels.insert("notnotoh", ());
initial_channels.insert("notohh", ()); initial_channels.insert("notohh", ());
initial_channels.insert("daph", ()); initial_channels.insert("daph", ());
initial_channels.insert("elis", ());
for (channels, _) in initial_channels.iter() { for (channels, _) in initial_channels.iter() {
match client.twitch_client.join(channels.to_owned().to_string()) { match client.twitch_client.join(channels.to_owned().to_string()) {
@ -35,14 +37,23 @@ pub async fn main() {
while let Some(message) = client.incoming_messages.recv().await { while let Some(message) = client.incoming_messages.recv().await {
match message { match message {
ServerMessage::Privmsg(msg) => { ServerMessage::Privmsg(msg) => {
println!( let channel = msg.channel_login.clone();
"(#{}) {}: {}", let sender = msg.sender.name.clone();
msg.channel_login, msg.sender.name, msg.message_text let contents = msg.message_text.clone();
); let prefix = "*";
if msg.sender.name == "notohh" {
match msg.message_text.as_str() { println!("(#{}) {}: {}", &channel, &sender, &contents);
"*ping" => ping_command(&msg, &client).await,
"*song" => lastfm_command(&msg, &client).await, if sender == "notohh" && contents.starts_with(prefix) {
let mut parts = contents.split_whitespace();
let command = parts.next().unwrap_or("").trim_start_matches(prefix);
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,
"logs" => logs_command(&msg, &client, &arguments).await,
_ => {} _ => {}
} }
} }