Add twitch chat

This commit is contained in:
2024-08-06 03:26:03 +02:00
parent 8c48301c9e
commit fba10ef647
4 changed files with 260 additions and 2 deletions

View File

@@ -0,0 +1,79 @@
use anyhow::bail;
use anyhow::Result;
use irc::client::data::Config as IrcConfig;
use irc::client::prelude::Capability as IrcCap;
use irc::client::Client as IrcClient;
use irc::client::ClientStream as IrcStream;
use super::auth;
use super::helix;
impl<T: auth::TokenStorage> helix::Client<T> {
pub async fn connect_chat(&mut self, channels: Vec<String>) -> Result<(IrcClient, IrcStream)> {
match self.validate_token().await {
Err(e) => {
println!("{e:?}");
bail!("Invalid refresh token or no internet");
}
_ => {}
};
let channels = channels
.into_iter()
.map(|c| {
format!(
"{0}{1}",
if c.starts_with("#") { "" } else { "#" },
c.to_lowercase()
)
})
.collect();
let config = IrcConfig {
server: Some("irc.chat.twitch.tv".to_owned()),
port: Some(6697),
use_tls: Some(true),
nickname: Some(self.get_token_user_login().await?.to_lowercase().to_owned()),
password: Some(format!("oauth:{0}", self.token.access_token)),
channels: channels,
..Default::default()
};
let mut client = match IrcClient::from_config(config).await {
Ok(v) => v,
Err(e) => {
println!("{e:?}");
bail!("IrcClient::from_config failed");
}
};
match client.send_cap_req(&[
IrcCap::Custom("twitch.tv/tags"),
IrcCap::Custom("twitch.tv/commands"),
]) {
Err(e) => {
println!("{e:?}");
bail!("IrcClient.send_cap_req failed");
}
_ => {}
};
match client.identify() {
Err(e) => {
println!("{e:?}");
bail!("IrcClient.identify failed");
}
_ => {}
};
let stream = match client.stream() {
Ok(v) => v,
Err(e) => {
println!("{e:?}");
bail!("IrcClient.stream failed");
}
};
Ok((client, stream))
}
}

View File

@@ -1,6 +1,7 @@
pub mod eventsub;
pub mod helix;
pub mod auth;
pub mod chat;
use chrono::{DateTime, Utc};
use futures::StreamExt;
@@ -63,7 +64,7 @@ pub async fn notify_stream_online(title: String, game: String) {
impl TwitchBot {
pub async fn start() {
pub async fn start_twitch_eventsub() {
println!("Starting Twitch bot...");
let token_storage = TokenStorage {
@@ -103,8 +104,11 @@ impl TwitchBot {
],
config::CONFIG.twitch_channel_id.clone()
).await.unwrap();
println!("Connected to Twitch EventSub...");
let (_chat_client, mut chat_stream) = client.connect_chat(vec![config::CONFIG.twitch_channel_id.clone()]).await.unwrap();
println!("Connected to Twitch Chat...");
client.validate_token().await.unwrap();
loop {
@@ -160,6 +164,15 @@ impl TwitchBot {
}
}
if let Some(event) = chat_stream.next().await {
match event {
Ok(v) => {
println!("{:?}", v);
},
Err(_) => {},
}
}
client.validate_token().await.unwrap();
}
}