tw_api/
chat.rs

1use anyhow::bail;
2use anyhow::Result;
3
4use irc::client::data::Config as IrcConfig;
5use irc::client::prelude::Capability as IrcCap;
6use irc::client::Client as IrcClient;
7use irc::client::ClientStream as IrcStream;
8
9impl<T: crate::auth::TokenStorage> crate::helix::Client<T> {
10    pub async fn connect_chat(&mut self, channels: Vec<String>) -> Result<(IrcClient, IrcStream)> {
11        match self.validate_token().await {
12            Err(e) => {
13                println!("{e:?}");
14                bail!("Invalid refresh token or no internet");
15            }
16            _ => {}
17        };
18
19        let channels = channels
20            .into_iter()
21            .map(|c| {
22                format!(
23                    "{0}{1}",
24                    if c.starts_with("#") { "" } else { "#" },
25                    c.to_lowercase()
26                )
27            })
28            .collect();
29
30        let config = IrcConfig {
31            server: Some("irc.chat.twitch.tv".to_owned()),
32            port: Some(6697),
33            use_tls: Some(true),
34            nickname: Some(self.get_token_user_login().await?.to_lowercase().to_owned()),
35            password: Some(format!("oauth:{0}", self.token.access_token)),
36            channels: channels,
37            ..Default::default()
38        };
39
40        let mut client = match IrcClient::from_config(config).await {
41            Ok(v) => v,
42            Err(e) => {
43                println!("{e:?}");
44                bail!("IrcClient::from_config failed");
45            }
46        };
47        match client.send_cap_req(&[
48            IrcCap::Custom("twitch.tv/tags"),
49            IrcCap::Custom("twitch.tv/commands"),
50        ]) {
51            Err(e) => {
52                println!("{e:?}");
53                bail!("IrcClient.send_cap_req failed");
54            }
55            _ => {}
56        };
57        match client.identify() {
58            Err(e) => {
59                println!("{e:?}");
60                bail!("IrcClient.identify failed");
61            }
62            _ => {}
63        };
64
65        let stream = match client.stream() {
66            Ok(v) => v,
67            Err(e) => {
68                println!("{e:?}");
69                bail!("IrcClient.stream failed");
70            }
71        };
72
73        Ok((client, stream))
74    }
75}