#youtube #chat #real-time #live #comments #interface #fetching

youtube_chat

提供 Rust 接口以获取 YouTube 直播聊天评论

7 个版本

0.2.1 2023年7月17日
0.2.0 2023年7月13日
0.1.4 2023年2月23日

网页编程 中排名第 982


yadio 中使用

MIT 许可证

43KB
1K SLoC

使用方法

构建客户端

urllive_idchannel_id 构建

// pattern 1
let mut client = LiveClientBuilder::new()
    .url("https://www.youtube.com/watch?v=jfKfPfyJRdk".to_string())
    .unwrap()
    .build();
// pattern 2
let mut client = LiveChatClientBuilder::new()
    .live_id("jfKfPfyJRd".to_string())
    .build();
// pattern 3
let mut client = LiveChatClientBuilder::new()
    .channel_id("UCHVXbQzkl3rDfsXWo8xi2qw".to_string())
    .build();

添加回调函数(每个回调函数都是可选的)

  • on_start
  • on_chat
  • on_end
  • on_error
let mut client = LiveChatClientBuilder::new()
    .url("https://www.youtube.com/watch?v=Dx5qFachd3A".to_string())
    .unwrap()
    .on_start(|_live_id| {})
    .on_error(|_err| {})
    .on_chat(|_chat_item| {})
    .on_end(|| {})
    .build();

为获取直播做好准备

client.start().await.unwrap();

获取聊天评论

client.execute().await;

如果想要实时获取评论,请定期调用 execute

使用 tokio 的示例

use std::time::Duration;

use tokio::{task, time};
use youtube_chat::live_chat::LiveChatClientBuilder;

#[tokio::main]
async fn main() {
    let mut client = LiveChatClientBuilder::new()
        .url("https://www.youtube.com/watch?v=jfKfPfyJRdk".to_string())
        .unwrap()
        .on_chat(|chat_item| println!("{:?}", chat_item.message))
        .on_error(|error| eprintln!("{:?}", error))
        .build();
    client.start().await.unwrap();
    let forever = task::spawn(async move {
        let mut interval = time::interval(Duration::from_millis(3000));
        loop {
            interval.tick().await;
            client.execute().await;
        }
    });

    forever.await.unwrap();
}

依赖项

~7–22MB
~313K SLoC