Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
{
"rust-analyzer.check.features": ["tls-native", "serde"],
"rust-analyzer.cargo.features": ["tls-native", "serde"]
"rust-analyzer.cargo.features": ["tls-native", "serde"],
"rust-analyzer.check.command": "clippy",
"rust-analyzer.diagnostics.experimental.enable": true,
}
29 changes: 13 additions & 16 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,32 @@ license = "Apache-2.0"
keywords = [ "chat", "twitch", "youtube", "live" ]
authors = [ "Carson M. <carson@pyke.io>" ]
repository = "https://github.com/pykeio/brainrot"
edition = "2021"
rust-version = "1.75"
edition = "2024"
rust-version = "1.89"

[dependencies]
tracing = "0.1"
tracing = { version = "0.1", default-features = false, features = [ "std" ] }
irc = { version = "1.0", optional = true, default-features = false }
tokio = { version = "1.42", default-features = false, features = [ "net" ] }
futures-util = { version = "0.3", default-features = false }
futures-util = { version = "0.3", default-features = false, features = [ "std" ] }
thiserror = "2.0"
chrono = { version = "0.4", default-features = false, features = [ "clock", "std" ] }
serde = { version = "1.0", optional = true, features = [ "derive" ] }
serde-aux = { version = "4.4", optional = true }
uuid = { version = "1.11", optional = true }
reqwest = { version = "0.12", default-features = false, optional = true, features = [ "charset", "http2" ] }
simd-json = { version = "0.17", optional = true }
url = { version = "2.5", optional = true }
rand = { version = "0.9", optional = true }
regex = { version = "1.11", optional = true }
simd-json = { version = "0.17", default-features = false, optional = true, features = [ "serde_impl" ] }
http = { version = "1.0", optional = true }
bytes = { version = "1.2", default-features = false, optional = true }
fastrand = { version = "2.3", optional = true }
async-stream-lite = "0.2"
pin-project-lite = "0.2"

[dev-dependencies]
anyhow = "1.0"
tokio = { version = "1.42", features = [ "rt", "rt-multi-thread", "macros", "net" ] }
reqwest = "0.12"

[features]
default = [ "tls-native", "twitch", "youtube" ]
twitch = [ "dep:irc", "dep:uuid" ]
youtube = [ "dep:simd-json", "dep:reqwest", "dep:rand", "dep:serde", "dep:url", "dep:regex", "dep:serde-aux" ]
serde = [ "dep:serde", "chrono/serde", "uuid?/serde" ]
tls-native = [ "irc?/tls-native", "reqwest?/native-tls" ]
tls-rust = [ "irc?/tls-rust", "reqwest?/rustls-tls" ]
youtube = [ "dep:simd-json", "dep:http", "dep:bytes", "dep:fastrand", "dep:serde" ]
serde = [ "dep:serde", "uuid?/serde" ]
tls-native = [ "irc?/tls-native" ]
tls-rust = [ "irc?/tls-rust" ]
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ A live chat interface for Twitch & YouTube written in Rust.
* ⚡ Low latency
* ⏪ Supports VODs
* 🔓 No authentication required
- 🤝 **Simulcast** - Receive from multiple streams & platforms simultaneously

## Usage
See [`examples/twitch.rs`](https://github.com/vitri-ent/brainrot/blob/main/examples/twitch.rs) & [`examples/youtube.rs`](https://github.com/vitri-ent/brainrot/blob/main/examples/youtube.rs).
1 change: 1 addition & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
msrv = "1.89"
6 changes: 3 additions & 3 deletions examples/twitch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@

use std::env::args;

use brainrot::{TwitchChat, TwitchChatEvent, twitch};
use brainrot::twitch::{Anonymous, Chat, ChatEvent};
use futures_util::StreamExt;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
let mut client = TwitchChat::new(args().nth(1).as_deref().unwrap_or("miyukiwei"), twitch::Anonymous).await?;
let mut client = Chat::new(args().nth(1).as_deref().unwrap_or("miyukiwei"), Anonymous).await?;

while let Some(message) = client.next().await.transpose()? {
if let TwitchChatEvent::Message { user, contents, .. } = message {
if let ChatEvent::Message { user, contents, .. } = message {
println!("{}: {}", user.display_name, contents.iter().map(|c| c.to_string()).collect::<String>());
}
}
Expand Down
103 changes: 88 additions & 15 deletions examples/youtube.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,101 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::env::args;
use std::{env::args, fmt::Write};

use brainrot::youtube::{self, Action, ChatItem};
use brainrot::youtube::{self, ChatEvent, MembershipRedemption, RequestExecutor, Run, StreamChatMode, StreamContext, StreamStatus};
use futures_util::StreamExt;

#[derive(Debug, Default)]
struct ReqwestExecutor(reqwest::Client);

impl RequestExecutor for ReqwestExecutor {
type Response = ReqwestResponse;
type Error = reqwest::Error;

async fn make_request(&self, req: http::Request<bytes::Bytes>) -> Result<Self::Response, Self::Error> {
self.0.execute(req.try_into().unwrap()).await.map(ReqwestResponse)
}

async fn sleep(dur: std::time::Duration) {
tokio::time::sleep(dur).await
}
}

#[derive(Debug)]
struct ReqwestResponse(reqwest::Response);

impl youtube::Response for ReqwestResponse {
type Error = reqwest::Error;

fn status_code(&self) -> u16 {
self.0.status().as_u16()
}

async fn recv_chunk(&mut self) -> Result<Option<bytes::Bytes>, Self::Error> {
self.0.chunk().await
}
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
let context =
youtube::ChatContext::new_from_channel(args().nth(1).as_deref().unwrap_or("@miyukiwei"), youtube::ChannelSearchOptions::LatestLiveOrUpcoming).await?;
let mut stream = youtube::stream(&context).await?;
while let Some(Ok(c)) = stream.next().await {
if let Action::AddChatItem {
item: ChatItem::TextMessage { message_renderer_base, message },
..
} = c
{
let Some(channel_id) = args().nth(1) else {
anyhow::bail!("cargo run --example youtube -- <channel_id>");
};

let client = youtube::Client::<ReqwestExecutor>::default();
let streams = youtube::query_channel(&channel_id, &client).await?;

let Some(stream) = streams.iter().find(|stream| stream.status() == StreamStatus::Live) else {
eprintln!("Channel has no live streams right now");
return Ok(());
};

println!("Viewing {} (https://www.youtube.com/watch?v={})", stream.title(), stream.id());
println!("{}", "=".repeat(80));

let context = StreamContext::new(client, stream.id(), StreamChatMode::Live).await?;
let mut chat = youtube::Chat::new(context).await?;

for event in chat.initial_events() {
print_event(event);
}

while let Some(event) = chat.next().await.transpose()? {
print_event(event);
}

Ok(())
}

fn stringify_runs(runs: &[Run]) -> String {
let mut s = String::new();
for run in runs {
write!(&mut s, "{run}").unwrap();
}
s
}

fn print_event(event: ChatEvent) {
match event {
ChatEvent::Message { author, contents, superchat, .. } => {
let text = stringify_runs(&contents);
if let Some(superchat) = superchat {
println!("{} sent {}: {}", author.name.unwrap_or(author.id), superchat.amount, text);
} else {
println!("{}: {}", author.name.unwrap_or(author.id), text);
}
}
ChatEvent::Membership { user, contents, redemption_type, .. } => {
println!(
"{}: {}",
message_renderer_base.author_name.unwrap_or_default().simple_text,
message.unwrap().runs.into_iter().map(|c| c.to_chat_string()).collect::<String>()
"Membership for {}: {}{}",
user.name.unwrap_or(user.id),
stringify_runs(&contents),
if redemption_type == MembershipRedemption::Gift { " (gifted)" } else { "" }
);
}
ChatEvent::MembershipGift { gifter, contents, .. } => {
println!("{} gifted memberships: {}", gifter.name.unwrap_or(gifter.id), stringify_runs(&contents));
}
}
Ok(())
}
10 changes: 2 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.

#![warn(clippy::unwrap_used)]

#[cfg(feature = "twitch")]
pub mod twitch;
#[cfg(feature = "twitch")]
pub use self::twitch::{Chat as TwitchChat, ChatEvent as TwitchChatEvent, MessageSegment as TwitchMessageSegment, TwitchIdentity};

#[cfg(feature = "youtube")]
pub mod youtube;

#[cfg(all(feature = "twitch", feature = "youtube"))]
mod multicast;
#[cfg(all(feature = "twitch", feature = "youtube"))]
pub use self::multicast::{Multicast, MulticastError, VariantChat};

pub(crate) mod util;
115 changes: 0 additions & 115 deletions src/multicast.rs

This file was deleted.

Loading
Loading